Skip to content

Instantly share code, notes, and snippets.

@ohadperry
Last active October 12, 2016 11:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ohadperry/338e7e689d8c64158c06 to your computer and use it in GitHub Desktop.
Save ohadperry/338e7e689d8c64158c06 to your computer and use it in GitHub Desktop.
from environment import *
from helpers_had import GlobalHelper
class AuthenticationController():
def __init__(self, app):
# before every request, verify user is logged in
@app.before_request
def login_required():
# exclude 404 errors and static routes
# uses split to handle blueprint static routes as well
if request.endpoint:
route = request.endpoint.rsplit('.', 1)[-1]
else:
route = None
return AuthenticationController.handle_route(route, app.stormpath_helper)
@staticmethod
def handle_route(route, stormpath_helper):
if GlobalHelper.no_login_required(route):
return
elif StormpathHelper.is_user_logged_in(user):
return AuthenticationController.handle_logged_in(user, route, stormpath_helper)
else:
return AuthenticationController.handle_logged_out()
@staticmethod
def handle_logged_in(user, route, stormpath_helper):
if stormpath_helper.is_social_user(user):
cloned_user_account = stormpath_helper.find_or_create_cloned_cloud_user(user)
AuthenticationController._switch_session_logged_in_user_to(cloned_user_account)
# TODO count login start and reset if needed for lock after 5 attempts
if GlobalHelper.is_logout(route):
flash_success('you have successfully logged out')
return # can't redirect to /login , have to continue to stormpath native logout method
return # don't return anything, continue with the route
@staticmethod
def handle_logged_out():
# session.setdefault('errors', [])
# session['errors'].append({'text': 'you have to log in to view this page'})
# return render_global(page = 'users/login.html')
flash_error('you have to log in to view this page')
# flash('you have to log in to view this page2')
return redirect('/login')
@staticmethod
def _switch_session_logged_in_user_to(new_user_account):
# new_user_account -> Stormpath User so it will have `is_active` attribute
new_user_account.__class__ = StormpathUser
# switching the session
login_user(new_user_account, remember=True)
return 'switched'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment