binny
binny

Reputation: 729

AttibuteError: '_AppCtxGlobals' object has no attribute 'user'

To set some context I'm creating an API through Flask. To authenticate users, I'm using flask-HTTPAuth. As a part of accessing login protected resources, I've defined my verify_password callback in auth.py. If the user credentials provided evaluate to True, the user is attached to the g object.

In app.py, there is the route /api/v1/users/token, that when requested, a token is issued to a user that is logged in. However when I try to access g.user in app.py, I get the error: AttributeError: '_AppCtxGlobals' object has no attribute 'user'.

Why isn't there any existing 'user' attribute not while accessing the g object in app.py?

auth.py

from flask import g
from flask_http import HTTPBasicAuth

from models import User

basic_auth = HTTPBasicAuth()

@basic_auth.verify_password
def verify_password(username, password):
    try:
        api_user = User.get(User.username == username)
    except User.DoesNotExist:
        return False
    user_verified = api_user.check_password(password)
    if user_verified:
        g.user = api_user
        return True
    return False

app.py

from flask import Flask, g, jsonify

from auth import basic_auth as auth

app = Flask(__name__)

@auth.login_required
@app.route("/api/v1/users/token")
def issue_api_token():
    token = g.user.request_token()
    return jsonify({'token': token})

Upvotes: 0

Views: 957

Answers (1)

Miguel Grinberg
Miguel Grinberg

Reputation: 67507

The order of your decorators is wrong, @app.route should always be first.

@app.route("/api/v1/users/token")
@auth.login_required
def issue_api_token():
    # ...

Upvotes: 1

Related Questions