Python flask.g.user() Examples

The following are 30 code examples of flask.g.user(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module flask.g , or try the search function .
Example #1
Source File: web.py    From calibre-web with GNU General Public License v3.0 7 votes vote down vote up
def load_user_from_auth_header(header_val):
    if header_val.startswith('Basic '):
        header_val = header_val.replace('Basic ', '', 1)
    basic_username = basic_password = ''
    try:
        header_val = base64.b64decode(header_val).decode('utf-8')
        basic_username = header_val.split(':')[0]
        basic_password = header_val.split(':')[1]
    except (TypeError, UnicodeDecodeError, binascii.Error):
        pass
    user = _fetch_user_by_name(basic_username)
    if user and config.config_login_type == constants.LOGIN_LDAP and services.ldap:
        if services.ldap.bind_user(str(user.password), basic_password):
            return user
    if user and check_password_hash(str(user.password), basic_password):
        return user
    return 
Example #2
Source File: credit_transfer.py    From SempoBlockchain with GNU General Public License v3.0 6 votes vote down vote up
def post(self):
        post_data = request.get_json()

        transfer_account = g.user.transfer_account

        withdrawal_amount = abs(round(float(post_data.get('withdrawal_amount', transfer_account.balance)),6))

        transfer_account.initialise_withdrawal(withdrawal_amount, transfer_mode=TransferModeEnum.MOBILE)

        db.session.commit()

        response_object = {
            'message': 'Withdrawal Requested',
        }

        return make_response(jsonify(response_object)), 201 
Example #3
Source File: alias.py    From app with MIT License 6 votes vote down vote up
def toggle_alias(alias_id):
    """
    Enable/disable alias
    Input:
        alias_id: in url
    Output:
        200 along with new status:
        - enabled


    """
    user = g.user
    alias: Alias = Alias.get(alias_id)

    if alias.user_id != user.id:
        return jsonify(error="Forbidden"), 403

    alias.enabled = not alias.enabled
    db.session.commit()

    return jsonify(enabled=alias.enabled), 200 
Example #4
Source File: user_info.py    From app with MIT License 6 votes vote down vote up
def create_api_key():
    """Used to create a new api key
    Input:
    - device

    Output:
    - api_key
    """
    data = request.get_json()
    if not data:
        return jsonify(error="request body cannot be empty"), 400

    device = data.get("device")

    api_key = ApiKey.create(user_id=g.user.id, name=device)
    db.session.commit()

    return jsonify(api_key=api_key.code), 201 
Example #5
Source File: alias.py    From app with MIT License 6 votes vote down vote up
def delete_alias(alias_id):
    """
    Delete alias
    Input:
        alias_id: in url
    Output:
        200 if deleted successfully

    """
    user = g.user
    alias = Alias.get(alias_id)

    if not alias or alias.user_id != user.id:
        return jsonify(error="Forbidden"), 403

    alias_utils.delete_alias(alias, user)

    return jsonify(deleted=True), 200 
Example #6
Source File: mailbox.py    From app with MIT License 6 votes vote down vote up
def delete_mailbox(mailbox_id):
    """
    Delete mailbox
    Input:
        mailbox_id: in url
    Output:
        200 if deleted successfully

    """
    user = g.user
    mailbox = Mailbox.get(mailbox_id)

    if not mailbox or mailbox.user_id != user.id:
        return jsonify(error="Forbidden"), 403

    if mailbox.id == user.default_mailbox_id:
        return jsonify(error="You cannot delete the default mailbox"), 400

    Mailbox.delete(mailbox_id)
    db.session.commit()

    return jsonify(deleted=True), 200 
Example #7
Source File: alias.py    From app with MIT License 6 votes vote down vote up
def get_alias(alias_id):
    """
    Get alias
    Input:
        alias_id: in url
    Output:
        Alias info, same as in get_aliases

    """
    user = g.user
    alias: Alias = Alias.get(alias_id)

    if not alias:
        return jsonify(error="Unknown error"), 400

    if alias.user_id != user.id:
        return jsonify(error="Forbidden"), 403

    return jsonify(**serialize_alias_info_v2(get_alias_info_v2(alias))), 200 
Example #8
Source File: alias.py    From app with MIT License 6 votes vote down vote up
def delete_contact(contact_id):
    """
    Delete contact
    Input:
        contact_id: in url
    Output:
        200
    """
    user = g.user
    contact = Contact.get(contact_id)

    if not contact or contact.alias.user_id != user.id:
        return jsonify(error="Forbidden"), 403

    Contact.delete(contact_id)
    db.session.commit()

    return jsonify(deleted=True), 200 
Example #9
Source File: base.py    From app with MIT License 6 votes vote down vote up
def require_api_auth(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        if current_user.is_authenticated:
            g.user = current_user
        else:
            api_code = request.headers.get("Authentication")
            api_key = ApiKey.get_by(code=api_code)

            if not api_key:
                return jsonify(error="Wrong api key"), 401

            # Update api key stats
            api_key.last_used = arrow.now()
            api_key.times += 1
            db.session.commit()

            g.user = api_key.user

        return f(*args, **kwargs)

    return decorated 
Example #10
Source File: app.py    From hackit with Apache License 2.0 6 votes vote down vote up
def login():
    if g.user is not None:
        return redirect(url_for('index'))

    form = LoginForm(request.form)

    if request.method == 'POST' and form.validate():
        user = users.User.query.filter_by(username=form.username.data).first()
        if user is None:
            flash(u'El usuario no existe')
        elif not user.checkpassword(form.password.data):
            flash(u'Contraseña incorrecta')
            app.logger.info('[%s] login failed', user)
        else:
            flash(u'Bienvenido de nuevo, %s'%user.username)
            session['user_id'] = user.id
            g.user = user
            app.logger.info('[%s] login succeeded', user)
            return level.autosolve(app) or redirect(url_for('index'))

    return redirect(url_for('index')) 
Example #11
Source File: level.py    From hackit with Apache License 2.0 6 votes vote down vote up
def can_skip(self):
        if g.user is None:
            return False

        if self.state() == 'skipped':
            return False

        skipped = 0
        for k,v in g.user.levels.items():
            if v.state == 'skipped':
                skipped += 1

        if skipped > self.config['MAX_SKIP']:
            self.logger.error('[%s][%s] User has %d skips, but max %d', skipped, self.config['MAX_SKIP'])
            return False
        elif skipped == self.config['MAX_SKIP']:
            return False
        else:
            return True 
Example #12
Source File: level.py    From hackit with Apache License 2.0 6 votes vote down vote up
def state(self):
        if datetime.utcnow() < self.config['START_TIME']:
            return 'closed'

        if g.user is None:
            if self.routeidx == 0:
                return 'open'
            else:
                return 'closed'
        else:
            userstate = g.user.getstate(self).state
            if userstate == 'unsolved':
                if self.routeidx == 0:
                    return 'open'
                for prev in self.route_.levels[:self.routeidx]:
                    prevstate = g.user.getstate(prev).state
                    if prevstate not in ('solved','skipped'):
                        return 'closed'
                else:
                    return 'open'
            else:
                return userstate 
Example #13
Source File: web.py    From calibre-web with GNU General Public License v3.0 6 votes vote down vote up
def load_user_from_request(request):
    if config.config_allow_reverse_proxy_header_login:
        rp_header_name = config.config_reverse_proxy_login_header_name
        if rp_header_name:
            rp_header_username = request.headers.get(rp_header_name)
            if rp_header_username:
                user = _fetch_user_by_name(rp_header_username)
                if user:
                    return user

    auth_header = request.headers.get("Authorization")
    if auth_header:
        user = load_user_from_auth_header(auth_header)
        if user:
            return user

    return 
Example #14
Source File: decorators.py    From papers with MIT License 6 votes vote down vote up
def login_required(f):
    '''
    This decorator checks the header to ensure a valid token is set
    '''
    @wraps(f)
    def func(*args, **kwargs):
        try:
            if 'authorization' not in request.headers:
                abort(404, message="You need to be logged in to access this resource")
            token = request.headers.get('authorization')
            payload = jwt.decode(token, current_app.config['SECRET_KEY'], algorithms=['HS256'])
            user_id = payload['id']
            g.user = User.find(user_id)
            if g.user is None:
               abort(404, message="The user id is invalid")
            return f(*args, **kwargs)
        except JWTError as e:
            abort(400, message="There was a problem while trying to parse your token -> {}".format(e.message))
    return func 
Example #15
Source File: views.py    From incepiton-mysql with MIT License 6 votes vote down vote up
def register():
    form = RegisterForm()
    if form.validate_on_submit():
        user = User()
        user.name = form.username.data
        user.hash_pass = generate_password_hash(form.password.data)
        user.email = form.email.data

        # Register user's role is dev, by default.
        user.role = 'dev'

        db.session.add(user)
        db.session.commit()

        flash('You have registered successfully. Please login! ', category='success')

        return redirect(url_for('auth.login'))

    return render_template('auth/register.html', form=form) 
Example #16
Source File: auth_api.py    From SempoBlockchain with GNU General Public License v3.0 6 votes vote down vote up
def get(self):
        try:

            auth_token = g.user.encode_auth_token()

            response_object = create_user_response_object(g.user, auth_token, 'Token refreshed successfully.')

            # Update the last_seen TS for this user
            g.user.update_last_seen_ts()

            return make_response(jsonify(response_object)), 200

        except Exception as e:

            response_object = {
                'status': 'fail',
                'message': 'Some error occurred. Please try again.'
            }

            return make_response(jsonify(response_object)), 403 
Example #17
Source File: level.py    From hackit with Apache License 2.0 6 votes vote down vote up
def skip(self):
        if g.user is None:
            self.logger.info('[%s][%s] anonymous skip', g.user, self.name)
            return redirect(url_for(self.name + '.index'))

        g.user.lock()
        if not self.can_skip():
            g.user.unlock()
            self.logger.warning('[%s][%s] skip() but can\'t skip', g.user, self.name)
            return render_template('forbidden.html'), 403

        g.user.setstate(self, 'skipped')
        g.user.commit()
        self.logger.info('[%s][%s] skipped', g.user, self.name)

        flash(u"Te has saltado el nivel %d" % self.number)
        try:
            next = self.route_.levels[self.routeidx+1]
            return redirect(url_for(next.name + '.index'))
        except IndexError:
            alldone = all([l.state() == 'solved' for r in routes for l in r.levels])
            self.logger.info('[%s][%s] last level (alldone=%r)', g.user, self.name, alldone)
            return render_template('alldone.html', alldone=alldone, level=self) 
Example #18
Source File: me.py    From SempoBlockchain with GNU General Public License v3.0 6 votes vote down vote up
def get(self):

        user = g.user

        serialised_data = user_schema.dump(user).data

        # TODO: Create a better way of having multiple dummy transfer accounts for testing
        # import copy
        # new_ta = copy.deepcopy(serialised_data['transfer_accounts'][0])
        # new_ta['id'] = new_ta['id'] + 1
        # new_ta['balance'] = 99999
        # new_ta['token']['id'] = 2
        # new_ta['token']['symbol'] = 'GOOP'
        #
        # serialised_data['transfer_accounts'].append(new_ta)

        response_object = {
            'message': 'Successfully Loaded.',
            'data': {
                'user': serialised_data
            }
        }

        return make_response(jsonify(response_object)), 201 
Example #19
Source File: notification.py    From app with MIT License 6 votes vote down vote up
def mark_as_read(notification_id):
    """
    Mark a notification as read
    Input:
        notification_id: in url
    Output:
        200 if updated successfully

    """
    user = g.user
    notification = Notification.get(notification_id)

    if not notification or notification.user_id != user.id:
        return jsonify(error="Forbidden"), 403

    notification.read = True
    db.session.commit()

    return jsonify(done=True), 200 
Example #20
Source File: misc.py    From SempoBlockchain with GNU General Public License v3.0 5 votes vote down vote up
def post(self):
        e = NotImplementedError('Referral has been updated and needs to be fixed!')

        return make_response(jsonify(str(e))), 501

        # post_data = request.get_json()
        #
        # referral = Referral()
        #
        # referral.first_name = post_data.get('first_name')
        # referral.last_name = post_data.get('last_name')
        # referral.phone = post_data.get('phone')
        # referral.reason = post_data.get('reason')
        #
        # referral.referring_user = g.user
        #
        # db.session.add(referral)
        #
        # db.session.commit()
        #
        # response_object = {
        #     'message': 'Referral Created',
        #     'data': {
        #         'referral': referral_schema.dump(referral).data
        #     }
        # }

        # return make_response(jsonify(response_object)), 201 
Example #21
Source File: auth.py    From SempoBlockchain with GNU General Public License v3.0 5 votes vote down vote up
def get_user_organisations(user):
    active_organisation = getattr(g, "active_organisation", None) or user.fallback_active_organisation()

    organisations = dict(
        active_organisation_id=active_organisation.id,
        organisations=organisations_schema.dump(user.organisations).data
    )

    return organisations 
Example #22
Source File: user_info.py    From app with MIT License 5 votes vote down vote up
def user_info():
    """
    Return user info given the api-key
    """
    user = g.user

    return jsonify(
        {
            "name": user.name,
            "is_premium": user.is_premium(),
            "email": user.email,
            "in_trial": user.in_trial(),
        }
    ) 
Example #23
Source File: kyc_application_api.py    From SempoBlockchain with GNU General Public License v3.0 5 votes vote down vote up
def put(self, bank_account_id):

        put_data = request.get_json()

        kyc_application_id = put_data.get('kyc_application_id')

        bank_country = put_data.get('bank_country')
        routing_number = put_data.get('routing_number')
        account_number = put_data.get('account_number')
        currency = put_data.get('currency')

        if bank_account_id is None:
            return make_response(jsonify({'message': 'You need to provide a bank account ID'})), 400

        bank_account = BankAccount.query.filter_by(id=bank_account_id).first()

        if kyc_application_id is None:
            kyc_application_id = bank_account.kyc_application_id

        business_details = KycApplication.query.filter_by(id=kyc_application_id).first()

        if not business_details:
            return make_response(jsonify({'message': 'Cannot find kyc for id {}'.format(kyc_application_id)})), 404

        if business_details.organisation_id and AccessControl.has_suffient_role(g.user.roles,
                                                                                {'ADMIN': 'superadmin'}) is not True:
            return make_response(jsonify({'message': 'Must be a superadmin to edit admin org KYC object'})), 401

        if bank_account:
            bank_account.kyc_application_id = kyc_application_id
            bank_account.bank_country = bank_country
            bank_account.routing_number = routing_number
            bank_account.account_number = account_number
            bank_account.currency = currency

        response_object = {
            'message': 'Bank account edited',
            'data': {'kyc_application': kyc_application_schema.dump(business_details).data}
        }

        return make_response(jsonify(response_object)), 200 
Example #24
Source File: misc.py    From SempoBlockchain with GNU General Public License v3.0 5 votes vote down vote up
def post(self):
        post_data = request.get_json()

        rating = post_data.get('rating')

        if rating is None:

            response_object = {
                'message': 'No rating provided',
            }

            return make_response(jsonify(response_object)), 400

        rating = float(rating)

        question = post_data.get('question', None)
        additional_information = post_data.get('additional_information', None)

        feedback = Feedback(question=question, rating=rating, additional_information=additional_information)

        db.session.add(feedback)

        feedback.user = g.user

        db.session.commit()

        response_object = {
            'message': 'Feedback Received',
        }

        return make_response(jsonify(response_object)), 201


# TODO: fix this 
Example #25
Source File: amazon_s3.py    From SempoBlockchain with GNU General Public License v3.0 5 votes vote down vote up
def generate_new_filename(original_filename, file_type = 'UnknownType', user_id = None):

    if user_id is None:
        if g.user:
            user_id = g.user.id
        else:
            user_id = 'UnknownID'

    extension = original_filename.split('.')[-1]

    export_time = datetime.datetime.strftime(datetime.datetime.utcnow(), "%Y%m%dT%H%M%SM%f")

    return file_type.lower() + '-user_' + str(user_id) + '-' + export_time + '.' + extension 
Example #26
Source File: views.py    From Python24 with MIT License 5 votes vote down vote up
def user_list():

    page = request.args.get("p", 1)
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1

    user_model_list = []
    current_page = 1
    total_page = 1

    try:
        paginate = User.query.filter(User.is_admin == False).paginate(page, constants.ADMIN_USER_PAGE_MAX_COUNT, False)
        user_model_list = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)

    user_dict_list = []
    for user in user_model_list:
        user_dict_list.append(user.to_admin_dict())

    data = {
        "users": user_dict_list,
        "current_page": current_page,
        "total_page": total_page,
    }

    return render_template("admin/user_list.html", data=data) 
Example #27
Source File: views.py    From Python24 with MIT License 5 votes vote down vote up
def index():
    user = g.user
    return render_template("admin/index.html", user=user.to_dict()) 
Example #28
Source File: views.py    From Python24 with MIT License 5 votes vote down vote up
def login():
    """因为后台的login需要登陆成功后跳转页面,所以不需要ajax局部刷新"""

    if request.method == 'GET':
        # 判断是否已经登陆,登陆的话直接跳转到index
        user_id = session.get('user_id', None)
        is_admin = session.get('is_admin', False)

        if user_id and is_admin:
            return redirect(url_for('admin.index'))
        return render_template("admin/login.html")

    # 获取参数,没用到ajax使用的是html中的form表单
    username = request.form.get('username')
    password = request.form.get('password')

    # 验证参数,因为没用到ajax,所以不能返回一个jsonify
    if not all([username, password]):
        return render_template("admin/login.html", errmsg="参数错误")

    # 数据库查询
    try:
        user = User.query.filter(User.mobile == username, User.is_admin == True).first()
    except Exception as e:
        current_app.logger.error(e)
        return render_template("admin/login.html", errmsg="用户信息查询失败")

    if not user:
        return render_template("admin/login.html", errmsg="未查询到用户信息")

    if not user.check_passowrd(password):
        return render_template("admin/login.html", errmsg="用户名或者密码错误")

    # 保存用户信息
    session['user_id'] = user.id
    session['mobile'] = user.mobile
    session['nick_name'] = user.nick_name
    session['is_admin'] = user.is_admin

    return redirect(url_for('admin.index')) 
Example #29
Source File: views.py    From Python24 with MIT License 5 votes vote down vote up
def other_info():
    """查询其他人的用户信息"""
    user = g.user

    other_id = request.args.get("user_id")
    if not other_id:
        abort(404)

    # 数据库查询
    try:
        other = User.query.get(other_id)
    except Exception as e:
        current_app.logger.error(e)

    if not other:
        abort(404)

    # 判断当前登录用户是否关注过该用户
    is_followed = False
    if g.user:
        # if other.followers.filter(User.id == user.id).count() > 0:
        if other in user.followed:
            is_followed = True

    data = {
        "is_followed": is_followed,
        "user": g.user.to_dict() if g.user else None,
        "other_info": other
    }

    return render_template("news/other.html", data=data) 
Example #30
Source File: auth.py    From SempoBlockchain with GNU General Public License v3.0 5 votes vote down vote up
def get_complete_auth_token(user):
    auth_token = user.encode_auth_token().decode()
    tfa_token = user.encode_TFA_token(9999).decode()
    return auth_token + '|' + tfa_token