Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
from firebase_admin import auth
from flask import request, abort, current_app
from functools import wraps
from configuration.settings import SHOULD_AUTHORIZE
def validate_token(access_token: str) -> tuple:
"""
Verifies that an access-token is valid and
meant for this app.
Returns tuple of (uid,displayable_id) on success
@:raise ValueError: If the JWT was found to be invalid, or if the App was not
initialized with a credentials.Certificate.
"""
decoded_token = auth.verify_id_token(access_token)
return decoded_token['uid'], decoded_token['phone_number'] if 'phone_number' in decoded_token else \
decoded_token['email']
def authorized(func):
"""Decorator that checks that requests
contain an id-token in the request header.
Usage:
@app.route("/")
@authorized
def secured_root(user_id=None):
pass
"""
@wraps(func)
def _wrap(*args, **kwargs):
user_id = None
displayable_id = None
if SHOULD_AUTHORIZE:
displayable_id, user_id = authorize_with_auth_header(displayable_id, user_id)
else:
current_app.logger.warn('Skips authentication')
# In case the flag is open in your local testing environment, but you want to test it with a device
if 'Readable_ID' not in request.headers or 'User_ID' not in request.headers:
displayable_id, user_id = authorize_with_auth_header(displayable_id, user_id)
else:
displayable_id = request.headers['Readable_ID']
user_id = request.headers['User_ID']
return func(userid=user_id, displayable_id=displayable_id, *args, **kwargs)
def authorize_with_auth_header(displayable_id, user_id):
if 'Authorization' not in request.headers:
# Unauthorized
current_app.logger.warn("No token in header")
abort(401)
try:
user_id, displayable_id = validate_token(request.headers['Authorization'])
except ValueError as e:
current_app.logger.warn(f'Firebase token "{request.headers["Authorization"]}" is invalid - {e}')
# Unauthorized
abort(401)
return displayable_id, user_id
return _wrap
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.