flaschengeist/flaschengeist/decorator.py

46 lines
1.4 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.user_agent, permission)
if not session:
logger.debug("token {{ {} }} is invalid".format(token))
raise Unauthorized
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