69 lines
2.1 KiB
Python
69 lines
2.1 KiB
Python
from functools import wraps
|
|
from werkzeug.exceptions import Unauthorized
|
|
|
|
from flaschengeist import logger
|
|
from flaschengeist.controller import sessionController
|
|
|
|
|
|
def extract_session(permission=None):
|
|
from flask import request
|
|
|
|
try:
|
|
token = list(filter(None, request.headers.get("Authorization").split(" ")))[-1]
|
|
except AttributeError:
|
|
logger.debug("Missing Authorization header or ill-formed")
|
|
raise Unauthorized
|
|
|
|
session = sessionController.validate_token(token, request.headers, permission)
|
|
return session
|
|
|
|
|
|
def login_required(permission=None):
|
|
"""Decorator use to make a route only accessible by logged in users.
|
|
Sets ``current_session`` into kwargs of wrapped function with session identified by Authorization header.
|
|
|
|
Attributes:
|
|
permission: Optional permission needed for this route
|
|
|
|
Returns:
|
|
Wrapped function with login (and permission) guard
|
|
"""
|
|
|
|
def wrap(func):
|
|
@wraps(func)
|
|
def wrapped_f(*args, **kwargs):
|
|
session = extract_session(permission)
|
|
kwargs["current_session"] = session
|
|
logger.debug("token {{ {} }} is valid".format(session.token))
|
|
return func(*args, **kwargs)
|
|
|
|
return wrapped_f
|
|
|
|
return wrap
|
|
|
|
|
|
def headers(headers={}, **headers_kwargs):
|
|
"""
|
|
Wrap a Flask route to add HTTP headers.
|
|
Either pass a dictionary of headers to be set as the headerDict keyword
|
|
argument, or pass header values as keyword arguments. Or both.
|
|
|
|
The key and value of items in a dictionary will be converted to strings using
|
|
the `str` method, ensure both keys and values are serializable thusly.
|
|
Args:
|
|
headers: A dictionary of headers to be injected into the response headers.
|
|
Note, the supplied dictionary is first copied then mutated.
|
|
headers_kwargs: The headers to be injected into the response headers.
|
|
"""
|
|
_headerDict = headers.copy()
|
|
_headerDict.update(headers_kwargs)
|
|
|
|
def decorator(f):
|
|
@wraps(f)
|
|
def decorated_function(*args, **kwargs):
|
|
return f(*args, **kwargs), _headerDict
|
|
|
|
return decorated_function
|
|
|
|
return decorator
|