From d80f5cbb86a8c4091acadb6e5d64b80521015aba Mon Sep 17 00:00:00 2001 From: Shuhei Iitsuka Date: Fri, 29 May 2020 12:55:06 +0900 Subject: [PATCH] Mock user on the local development --- README.md | 5 +++++ src/securescaffold/contrib/appengine/users.py | 16 ++++++++++++++++ 2 files changed, 21 insertions(+) diff --git a/README.md b/README.md index 5584516..0807cd9 100644 --- a/README.md +++ b/README.md @@ -138,6 +138,11 @@ App Engine supports [the IAP service](https://cloud.google.com/iap/docs) (Identi return "Not signed-in" +#### Mocking user on the local development server + +Secure Scaffold mocks a User object as `user@example.com` by default. +You can change the mocked user's email address by setting it as the environment variable `GAESS_MOCK_EMAIL`. +If you want to test the app as an admin user, assign 1 to the environment variable `GAESS_MOCK_ADMIN`. ### Securing request handlers and cron tasks diff --git a/src/securescaffold/contrib/appengine/users.py b/src/securescaffold/contrib/appengine/users.py index 62ea4a6..bde9353 100644 --- a/src/securescaffold/contrib/appengine/users.py +++ b/src/securescaffold/contrib/appengine/users.py @@ -16,6 +16,7 @@ This only works when IAP is enabled for your App Engine instance """ import flask +import os USER_ADMIN_HEADER = "X-Appengine-User-Is-Admin" @@ -116,6 +117,8 @@ def __hash__(self): def get_current_user(): + if not in_production(): + return get_mock_user() try: return User() except UserNotFoundError: @@ -123,7 +126,20 @@ def get_current_user(): def is_current_user_admin(): + if not in_production(): + return os.getenv('GAESS_MOCK_ADMIN', False) return get_header(USER_ADMIN_HEADER) == "1" +def in_production(): + """Checks if it is production environment.""" + return os.getenv('GAE_ENV', '').startswith('standard') + +def get_mock_user(): + """Returns a mock user.""" + email = os.getenv('GAESS_MOCK_EMAIL', 'user@example.com') + auth_domain = email.split('@')[-1] + user = User(email=email, _auth_domain=auth_domain) + return user + IsCurrentAdmin = is_current_user_admin