Speed up authentication by trusting g.current_user if set.

This commit is contained in:
2018-01-30 12:40:19 +01:00
parent ed1e348d67
commit 4b5a961e14
5 changed files with 124 additions and 70 deletions

View File

@@ -113,7 +113,7 @@ def create_home_project(user_id, write_access):
# Re-validate the authentication token, so that the put_internal call sees the
# new group created for the project.
authentication.validate_token()
authentication.validate_token(force=True)
# There are a few things in the on_insert_projects hook we need to adjust.

View File

@@ -16,7 +16,6 @@ import bson
from bson import tz_util
from flask import g, current_app
from flask import request
from flask import current_app
from werkzeug import exceptions as wz_exceptions
from pillar.api.utils import remove_private_keys
@@ -105,7 +104,7 @@ def find_user_in_db(user_info: dict, provider='blender-id') -> dict:
return db_user
def validate_token():
def validate_token(*, force=False):
"""Validate the token provided in the request and populate the current_user
flask.g object, so that permissions and access to a resource can be defined
from it.
@@ -113,11 +112,19 @@ def validate_token():
When the token is successfully validated, sets `g.current_user` to contain
the user information, otherwise it is set to None.
@returns True iff the user is logged in with a valid Blender ID token.
:param force: don't trust g.current_user and force a re-check.
:returns: True iff the user is logged in with a valid Blender ID token.
"""
from pillar.auth import AnonymousUser
# Trust a pre-existing g.current_user
if not force:
cur = getattr(g, 'current_user', None)
if cur is not None and cur.is_authenticated:
log.debug('skipping token check because current user is already set to %s', cur)
return True
auth_header = request.headers.get('Authorization') or ''
if request.authorization:
token = request.authorization.username
@@ -359,7 +366,6 @@ def setup_app(app):
@app.before_request
def validate_token_at_each_request():
validate_token()
return None
def upsert_user(db_user):

View File

@@ -138,7 +138,8 @@ class AbstractPillarTest(TestMinimal):
self.app.process_extensions()
assert self.app.config['MONGO_DBNAME'] == 'pillar_test'
self.client = self.app.test_client()
self.app.testing = True
self.client = self.app.test_client(use_cookies=False)
assert isinstance(self.client, FlaskClient)
def tearDown(self):
@@ -157,9 +158,14 @@ class AbstractPillarTest(TestMinimal):
The app context is automatically exited upon testcase teardown.
"""
from flask import g
self._app_ctx: flask.ctx.AppContext = self.app.app_context()
self._app_ctx.__enter__()
if hasattr(g, 'current_user'):
g.current_user = None
def unload_modules(self, module_name):
"""Uploads the named module, and all submodules."""