Skip to content

Instantly share code, notes, and snippets.

@3lpsy
Last active November 17, 2017 21:19
Show Gist options
  • Save 3lpsy/8de3999d9e6d69c14464341102a92d2f to your computer and use it in GitHub Desktop.
Save 3lpsy/8de3999d9e6d69c14464341102a92d2f to your computer and use it in GitHub Desktop.
Flask Decorators
## Thank you to #pocoo for the help!
### dashboard.py
from flask import redirect, url_for, render_template, make_response, Blueprint
from flasky.services.auth import Auth
from flasky.responses.invalid import unauthenticated
from flasky.middlewares.auth import is_authenticated, has_role
dashboard_blueprint = Blueprint('dashboard', __name__)
@dashboard_blueprint.route('/dashboard', methods=["GET"])
@is_authenticated
def dashboard_index():
auth = Auth(request)
if not auth.is_authenticated():
return unauthenticated()
auth_user = auth.get_user()
return make_response(render_template('dashboard.html', auth=auth_user))
@dashboard_blueprint.route('/dashboard/<int:user_id>', methods=["GET"])
@is_authenticated
@has_role(role='admin')
def dashboard_show():
auth = Auth(request)
if not auth.is_authenticated():
return unauthenticated()
auth_user = auth.get_user()
return make_response(render_template('dashboard.html', auth=auth_user))
### middleware.py
from functools import wraps
from flask import request
from flasky.services.auth import Auth
from flasky.responses.invalid import unauthenticated, unauthorized
def is_authenticated(func):
@wraps(func)
def decorated_function(*args, **kwargs):
auth = Auth(request)
if not auth.is_authenticated():
return unauthenticated(request)
return func(*args, **kwargs)
return decorated_function
def has_role(role=""):
def decorator(func):
@wraps(func)
def decorated_function(*args, **kwargs):
auth = Auth(request)
if not auth.is_authenticated(): #session and user both exist
return unauthenticated(request)
user = auth.get_user()
if not user.has_role(role_or_code):
return unauthorized(request)
return func(*args, **kwargs)
return decorated_function
return decorator
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment