From e898fe03153122761553fb5fa9e4796bd68fffb0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sybren=20A=2E=20St=C3=BCvel?= Date: Tue, 12 Apr 2016 16:53:27 +0200 Subject: [PATCH] Use Blender ID subclient-specific token to find the user. TODO: also store expiry timestamp TODO: allow multiple subclient-specific tokens per user --- pillar/application/modules/blender_id.py | 3 +++ pillar/application/utils/authentication.py | 26 ++++++++++++++++++++++ 2 files changed, 29 insertions(+) diff --git a/pillar/application/modules/blender_id.py b/pillar/application/modules/blender_id.py index 8e4dfbc5..b9faa493 100644 --- a/pillar/application/modules/blender_id.py +++ b/pillar/application/modules/blender_id.py @@ -90,12 +90,15 @@ def validate_subclient_token(user_id, scst): def find_user_in_db(user_id, scst, email, full_name): + """Find the user in our database, creating/updating it where needed.""" + users = current_app.data.driver.db['users'] query = {'auth': {'$elemMatch': {'user_id': user_id, 'provider': 'blender-id'}}} log.debug('Querying: %s', query) db_user = users.find_one(query) + # TODO: include token expiry in database. if db_user: log.debug('User %r already in our database, updating with info from Blender ID.', user_id) db_user['full_name'] = full_name diff --git a/pillar/application/utils/authentication.py b/pillar/application/utils/authentication.py index ee96fb2f..7227e6c0 100644 --- a/pillar/application/utils/authentication.py +++ b/pillar/application/utils/authentication.py @@ -68,7 +68,25 @@ def validate_token(): log.debug('No authentication headers, so not logged in.') return False + # Check the users to see if there is one with this Blender ID token. token = request.authorization.username + db_user = find_user_by_token(token) + if db_user is not None: + log.debug(u'Token for %s found as locally stored blender-id subclient token.', + db_user['full_name']) + current_user = dict( + user_id=db_user['_id'], + token=token, + groups=db_user['groups'], + token_expire_time=datetime.now() + timedelta(hours=1) # TODO: get from Blender ID + ) + g.current_user = current_user + return True + + # Fall back to deprecated behaviour. + log.debug('Token not found as locally stored blender-id subclient token; ' + 'falling back on deprecated behaviour.') + tokens_collection = app.data.driver.db['tokens'] lookup = {'token': token, 'expire_time': {"$gt": datetime.now()}} @@ -184,3 +202,11 @@ def make_unique_username(email): if user_from_username is None: return unique_name suffix += 1 + + +def find_user_by_token(scst): + users = app.data.driver.db['users'] + + query = {'auth': {'$elemMatch': {'provider': 'blender-id', + 'token': scst}}} + return users.find_one(query)