Skip to content

Instantly share code, notes, and snippets.

@alanhamlett
Created July 12, 2018 02:22
Show Gist options
  • Save alanhamlett/f9c8d6414cdd81502442fb5631b41fd9 to your computer and use it in GitHub Desktop.
Save alanhamlett/f9c8d6414cdd81502442fb5631b41fd9 to your computer and use it in GitHub Desktop.
OAuth permission decorator code snippet from WakaTime blog post
""" Example for Blog Post:
https://wakatime.com/blog/34-part-3-flask-api-decorators-and-helpers
"""
def oauth(required_scopes=[]):
def wrapper(func):
@wraps(func)
def inner(*args, **kwargs):
# don't check oauth tokens if user already logged in with session cookie
if current_app.current_user.is_authenticated:
return func(*args, **kwargs)
grant = load_oauth_grant_from_request(request)
if grant is None:
return login_manager.unauthorized()
missing = get_missing_scopes(grant=grant, required_scopes=required_scopes)
if len(missing) > 0:
return jsonify(error=u'This resource requires scopes: {0}.'.format(missing)), 403
if not flask_login.login_user(grant.user):
return login_manager.unauthorized()
del session['user_id']
return func(*args, **kwargs)
return inner
return wrapper
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment