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?
g.useris a dictionary, not aUserinstance. This is probably whatusers.find_one()returns.pymongoworks here, but clearly it is not returning an instance of theUserclass. 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.