0

I am trying to create token for logged in user for a particular duration and using g.user to keep track of current user.

generate_auth_token and verify_auth_token belong to class User.

However I keep getting this error:

g.user.generate_auth_token(600) 'dict' object has no attribute 'generate_auth_token'

def generate_auth_token(self, expiration=600):
    s = Serializer(app.config['SECRET_KEY'], expires_in=expiration)
    return s.dumps({'id': self.id})

@staticmethod
def verify_auth_token(token):
    s = Serializer(app.config['SECRET_KEY'])
    try:
        data = s.loads(token)
    except SignatureExpired:
        return None  # valid token, but expired
    except BadSignature:
        return None  # invalid token
    user = users.find_one({'username': userdata['username']})['_id']
    return user

@auth.login_required
def get_token():
    token = g.user.generate_auth_token(600)
    return json.dumps({'token': token.decode('ascii'), 'duration': 600})

@auth.verify_password
def verify_password(username_or_token, password):
    user = User.verify_auth_token(username_or_token)
    if not user:
        user = users.find_one({'username': username_or_token})
        if not user or not pwd_context.verify(password, user['password']):
            return False
    g.user = user
    return True

What is the mistake I made and what's the best way to do token authentication in flask for pymongo?

3
  • g.user is a dictionary, not a User instance. This is probably what users.find_one() returns. Commented Oct 3, 2015 at 18:22
  • What would you think would be the best way to get user instance. I am referencing this blog to build token based authentication: blog.miguelgrinberg.com/post/… Commented Oct 3, 2015 at 18:46
  • The technique in the blog is solid and great. But your implementation is lacking here. I don't know how pymongo works here, but clearly it is not returning an instance of the User class. Perhaps there are techniques to turn the Mongo results into a Python class instance (like SQLAlchemy does in the tutorial you found), but I haven't worked with Mongo myself so I can't answer that part. Commented Oct 3, 2015 at 19:06

2 Answers 2

1

You need an Object-Document-Mapper for your User class.

Try this

  • Use MongoEngine as your ODM. (There are other options like MongoFrames)

Here is a working example using MongoEngine as the ODM https://github.com/timosville/rest_auth_mongodb

Sign up to request clarification or add additional context in comments.

Comments

0

define generate_auth_token method inside the User class

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.