""" Various decorators which may be applied to specific routes See https://stackoverflow.com/a/51820573 for reference. """ from flask import g, abort, request from functools import wraps def require_user(admin = False, moderator = False): """A decorator for any routes which require authentication.""" def _require_user(handler): @wraps(handler) def __require_user(): if getattr(g, 'user', None) is None \ or (admin and not g.user.admin) \ or (moderator and not g.user.moderator): abort(401) return handler() return __require_user return _require_user def logger_request_bindings(log): """Applied to a route which logs something to have request data bound to the logger.""" def _lrb(handler): @wraps(handler) def __lrb(): log.bind( path=request.path, method=request.method, user_agent=request.user_agent, remote_ip=request.remote_addr, user=getattr(g, 'user', '(anonymous)'), ) return handler(log) return __lrb return _lrb