Python flask.g.current_user() Examples

The following are 30 code examples of flask.g.current_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: authorization.py    From amivapi with GNU Affero General Public License v3.0 6 votes vote down vote up
def _validate_only_self_enrollment_for_event(self, enabled, field, value):
        """Validate if the user can be used to enroll for an event.

        1.  Anyone can signup with no user id
        2.  other id: Registered users can only enter their own id
        3.  Exception are resource admins: they can sign up others as well

        Args:
            enabled (bool): validates nothing if set to false
            field (string): field name
            value: field value

        The rule's arguments are validated against this schema:
        {'type': 'boolean'}
        """
        if enabled:
            if g.resource_admin or value is None:
                return
            if g.get('current_user') != str(value):
                self._error(field, "You can only enroll yourself. (%s: "
                                   "%s is yours)." % (field, g.current_user)) 
Example #2
Source File: auth.py    From amivapi with GNU Affero General Public License v3.0 6 votes vote down vote up
def has_item_write_permission(self, user_id, item):
        """Check if the user is allowed to modify the item.

        Implement this function for your resource.
        Default behaviour: No user has write permission.

        Args:
            user (str): The id of the user that wants to access the item
            item (dict): The item the user wants to change or delete.
                Attention! If they are any ObjectIds in here, Eve will not have
                converted them yet, so be sure to cast them to str if you want
                to compare them to e.g. g.current_user

        Returns:
            bool: True if user has permission to change the item, False if not.
        """
        return False 
Example #3
Source File: test_auth.py    From amivapi with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_authentication_defaults(self):
        """Make sure authenticate sets defaults for all auth values."""
        expect_none = 'current_token', 'current_user', 'current_session'
        expect_false = 'resource_admin', 'resource_admin_readonly'

        with self.app.test_request_context():
            # Nothing there before
            for item in expect_none + expect_false:
                with self.assertRaises(AttributeError):
                    getattr(g, item)

            authenticate()
            for item in expect_none:
                self.assertIsNone(getattr(g, item))

            check_if_admin('someresource')
            for item in expect_false:
                self.assertFalse(getattr(g, item)) 
Example #4
Source File: auth.py    From amivapi with GNU Affero General Public License v3.0 5 votes vote down vote up
def check_item_write_permission(auth, resource, item):
    """Check if the user is allowed to PATCH or DELETE the item."""
    user = g.current_user
    if not (user and auth.has_item_write_permission(user, item)):
        current_app.logger.debug(
            "Access denied: "
            "The current user has no permission to write.")
        abort(403) 
Example #5
Source File: auth.py    From amivapi with GNU Affero General Public License v3.0 5 votes vote down vote up
def add_lookup_filter(auth, resource, request, lookup):
    """Get and add lookup filter for GET, PATCH and DELETE."""
    extra_lookup = auth.create_user_lookup_filter(g.current_user)

    if extra_lookup is None:
        abort(403)  # No lookup at all

    if extra_lookup:
        # Add the additional lookup with an `$and` condition
        # or extend existing `$and`s
        lookup.setdefault('$and', []).append(extra_lookup) 
Example #6
Source File: auth.py    From flicket with MIT License 5 votes vote down vote up
def verify_password(username, password):
    user = FlicketUser.query.filter_by(username=username).first()
    if user is None:
        return False
    g.current_user = user
    return user.check_password(password) 
Example #7
Source File: auth.py    From flicket with MIT License 5 votes vote down vote up
def verify_token(token):
    g.current_user = FlicketUser.check_token(token) if token else None
    return g.current_user is not None 
Example #8
Source File: comments.py    From flasky-with-celery with MIT License 5 votes vote down vote up
def new_post_comment(id):
    post = Post.query.get_or_404(id)
    comment = Comment.from_json(request.json)
    comment.author = g.current_user
    comment.post = post
    db.session.add(comment)
    db.session.commit()
    return jsonify(comment.to_json()), 201, \
        {'Location': url_for('api.get_comment', id=comment.id,
                             _external=True)} 
Example #9
Source File: views.py    From USSD-Python-Demo with MIT License 5 votes vote down vote up
def ussd_callback():
    """Handles post call back from AT"""
    session_id = g.session_id
    user = g.current_user
    session = g.session
    user_response = g.user_response
    if isinstance(user, AnonymousUser):
        # register user
        menu = RegistrationMenu(session_id=session_id, session=session, phone_number=g.phone_number,
                                user_response=user_response, user=user)
        return menu.execute()
    level = session.get('level')
    if level < 2:
        menu = LowerLevelMenu(session_id=session_id, session=session, phone_number=g.phone_number,
                              user_response=user_response, user=user)
        return menu.execute()

    if level >= 50:
        menu = Deposit(session_id=session_id, session=session, phone_number=g.phone_number,
                       user_response=user_response, user=user, level=level)
        return menu.execute()

    if level >= 40:
        menu = WithDrawal(session_id=session_id, session=session, phone_number=g.phone_number,
                          user_response=user_response, user=user, level=level)
        return menu.execute()

    if level >= 10:
        menu = Airtime(session_id=session_id, session=session, phone_number=g.phone_number, user_response=user_response,
                       user=user, level=level)
        return menu.execute()

    response = make_response("END nothing here", 200)
    response.headers['Content-Type'] = "text/plain"
    return response 
Example #10
Source File: posts.py    From flasky-with-celery with MIT License 5 votes vote down vote up
def new_post():
    post = Post.from_json(request.json)
    post.author = g.current_user
    db.session.add(post)
    db.session.commit()
    return jsonify(post.to_json()), 201, \
        {'Location': url_for('api.get_post', id=post.id, _external=True)} 
Example #11
Source File: test_auth.py    From amivapi with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_lookup_added(self):
        """Test if lookup filters are added."""
        user = 'does not matter'
        lookup = {}
        expected = {'$and': [{'_id': user}]}

        with self._init_context(current_user=user, auth_required=True):
            add_lookup_filter('fake', None, lookup)
            self.assertEqual(lookup, expected) 
Example #12
Source File: posts.py    From flasky-with-celery with MIT License 5 votes vote down vote up
def edit_post(id):
    post = Post.query.get_or_404(id)
    if g.current_user != post.author and \
            not g.current_user.can(Permission.ADMINISTER):
        return forbidden('Insufficient permissions')
    post.body = request.json.get('body', post.body)
    db.session.add(post)
    return jsonify(post.to_json()) 
Example #13
Source File: authentication.py    From flasky-with-celery with MIT License 5 votes vote down vote up
def verify_password(email_or_token, password):
    if email_or_token == '':
        g.current_user = AnonymousUser()
        return True
    if password == '':
        g.current_user = User.verify_auth_token(email_or_token)
        g.token_used = True
        return g.current_user is not None
    user = User.query.filter_by(email=email_or_token).first()
    if not user:
        return False
    g.current_user = user
    g.token_used = False
    return user.verify_password(password) 
Example #14
Source File: authentication.py    From flasky-with-celery with MIT License 5 votes vote down vote up
def before_request():
    if not g.current_user.is_anonymous() and \
            not g.current_user.confirmed:
        return forbidden('Unconfirmed account') 
Example #15
Source File: fake_auth.py    From amivapi with GNU Affero General Public License v3.0 5 votes vote down vote up
def _init_context(self, **g_updates):
        """Create an app context and fill g with values."""
        with self.app.app_context():
            # Defaults - no admins and nothing
            g.current_token = g.current_session = g.current_user = None
            g.resource_admin = g.resource_admin_readonly = False

            # Update g
            for key, value in g_updates.items():
                setattr(g, key, value)

            yield 
Example #16
Source File: auth.py    From amivapi with GNU Affero General Public License v3.0 5 votes vote down vote up
def authenticate_token(token):
    """Authenticate user and set g.current_token, g.current_session and
    g.current_user.

    See also the authenticate function.
    """
    # Set defaults
    g.current_token = g.current_session = g.current_user = None

    if token:
        g.current_token = token

        # Get session
        sessions = current_app.data.driver.db['sessions']
        session = sessions.find_one({'token': token})

        if session:
            # Update timestamp (remove microseconds to match mongo precision)
            new_time = dt.utcnow().replace(microsecond=0)
            sessions.update_one({'_id': session['_id']},
                                {'$set': {
                                    '_updated': new_time
                                }})
            session['_updated'] = new_time

            # Save user_id and session with updated timestamp in g
            g.current_session = session
            g.current_user = str(session['user'])  # ObjectId to str


# Hooks begin here 
Example #17
Source File: authentication.py    From flasky-first-edition with MIT License 5 votes vote down vote up
def before_request():
    if not g.current_user.is_anonymous and \
            not g.current_user.confirmed:
        return forbidden('Unconfirmed account') 
Example #18
Source File: auth.py    From amivapi with GNU Affero General Public License v3.0 5 votes vote down vote up
def abort_if_not_public(*args):
    """Abort if the resource is not public and there is no user/admin.

    If auth is required and we are no admin, check if a user is logged in.
    If not abort, since the requested resource is not public.
    """
    if g.current_user is None:
        current_app.logger.debug(
            "Access denied: "
            "Action is not public and user can't be authenticated.")
        abort(401) 
Example #19
Source File: decorators.py    From USSD-Python-Demo with MIT License 5 votes vote down vote up
def validate_ussd_user(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        """Get user trying to access to USSD session and the session id and adds them to the g request variable"""
        # get user response
        text = request.values.get("text", "default")
        text_array = text.split("*")
        # get phone number
        phone_number = request.values.get("phoneNumber")
        # get session id
        session_id = request.values.get("sessionId") or str(uuid.uuid4())
        # get user
        user = User.by_phoneNumber(phone_number) or AnonymousUser()
        # get session
        session = redis.get(session_id)
        if session is None:
            session = {"level": 0, "session_id": session_id}
            redis.set(session_id, json.dumps(session))
        else:
            session = json.loads(session.decode())
        # add user, response and session to the request variable g
        g.user_response = text_array[len(text_array) - 1]
        g.session = session
        g.current_user = user
        g.phone_number = phone_number
        g.session_id = session_id
        return func(*args, **kwargs)

    return wrapper 
Example #20
Source File: auth.py    From todoism with MIT License 5 votes vote down vote up
def validate_token(token):
    s = Serializer(current_app.config['SECRET_KEY'])
    try:
        data = s.loads(token)
    except (BadSignature, SignatureExpired):
        return False
    user = User.query.get(data['id'])
    if user is None:
        return False
    g.current_user = user
    return True 
Example #21
Source File: resources.py    From todoism with MIT License 5 votes vote down vote up
def delete(self):
        """Clear current user's completed items."""
        Item.query.with_parent(g.current_user).filter_by(done=True).delete()
        db.session.commit()  # TODO: is it better use for loop?
        return '', 204 
Example #22
Source File: resources.py    From todoism with MIT License 5 votes vote down vote up
def get(self):
        """Get current user's completed items."""
        page = request.args.get('page', 1, type=int)
        pagination = Item.query.with_parent(g.current_user).filter_by(done=True).paginate(
            page, per_page=current_app.config['TODOISM_ITEM_PER_PAGE'])
        items = pagination.items
        current = url_for('.items', page=page, _external=True)
        prev = None
        if pagination.has_prev:
            prev = url_for('.completed_items', page=page - 1, _external=True)
        next = None
        if pagination.has_next:
            next = url_for('.completed_items', page=page + 1, _external=True)
        return jsonify(items_schema(items, current, prev, next, pagination)) 
Example #23
Source File: resources.py    From todoism with MIT License 5 votes vote down vote up
def get(self):
        """Get current user's active items."""
        page = request.args.get('page', 1, type=int)
        pagination = Item.query.with_parent(g.current_user).filter_by(done=False).paginate(
            page, per_page=current_app.config['TODOISM_ITEM_PER_PAGE'])
        items = pagination.items
        current = url_for('.items', page=page, _external=True)
        prev = None
        if pagination.has_prev:
            prev = url_for('.active_items', page=page - 1, _external=True)
        next = None
        if pagination.has_next:
            next = url_for('.active_items', page=page + 1, _external=True)
        return jsonify(items_schema(items, current, prev, next, pagination)) 
Example #24
Source File: resources.py    From todoism with MIT License 5 votes vote down vote up
def post(self):
        """Create new item."""
        item = Item(body=get_item_body(), author=g.current_user)
        db.session.add(item)
        db.session.commit()
        response = jsonify(item_schema(item))
        response.status_code = 201
        response.headers['Location'] = url_for('.item', item_id=item.id, _external=True)
        return response 
Example #25
Source File: resources.py    From todoism with MIT License 5 votes vote down vote up
def get(self):
        return jsonify(user_schema(g.current_user)) 
Example #26
Source File: resources.py    From todoism with MIT License 5 votes vote down vote up
def delete(self, item_id):
        """Delete item."""
        item = Item.query.get_or_404(item_id)
        if g.current_user != item.author:
            return api_abort(403)
        db.session.delete(item)
        db.session.commit()
        return '', 204 
Example #27
Source File: resources.py    From todoism with MIT License 5 votes vote down vote up
def patch(self, item_id):
        """Toggle item."""
        item = Item.query.get_or_404(item_id)
        if g.current_user != item.author:
            return api_abort(403)
        item.done = not item.done
        db.session.commit()
        return '', 204 
Example #28
Source File: resources.py    From todoism with MIT License 5 votes vote down vote up
def put(self, item_id):
        """Edit item."""
        item = Item.query.get_or_404(item_id)
        if g.current_user != item.author:
            return api_abort(403)
        item.body = get_item_body()
        db.session.commit()
        return '', 204 
Example #29
Source File: resources.py    From todoism with MIT License 5 votes vote down vote up
def get(self, item_id):
        """Get item."""
        item = Item.query.get_or_404(item_id)
        if g.current_user != item.author:
            return api_abort(403)
        return jsonify(item_schema(item)) 
Example #30
Source File: comments.py    From circleci-demo-python-flask with MIT License 5 votes vote down vote up
def new_post_comment(id):
    post = Post.query.get_or_404(id)
    comment = Comment.from_json(request.json)
    comment.author = g.current_user
    comment.post = post
    db.session.add(comment)
    db.session.commit()
    return jsonify(comment.to_json()), 201, \
        {'Location': url_for('api.get_comment', id=comment.id,
                             _external=True)}