Advertisement
Guest User

Untitled

a guest
Jul 26th, 2017
123
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.50 KB | None | 0 0
  1. # -*- encoding: UTF-8 -*-
  2. #
  3.  
  4. import datetime
  5. from models.db import User, session as db_session
  6. from models.forms import LoginForm
  7. from flask import render_template, request, url_for, session, Module, redirect
  8.  
  9. auth = Module(__name__)
  10.  
  11. SESSION_KEY = 'auth_session'
  12.  
  13. UNKNOWN_EMAIL_MESSAGE = 'Unknown e-mail address'
  14. INCORRECT_PASSWORD_MESSAGE = 'Incorrect password'
  15.  
  16. def check_credentials(email, password):
  17.     """
  18.    Verifies credentials for email and password.
  19.    Returns user id on successful login else returns the error message.
  20.    """
  21.     try:
  22.         user = User.query.filter_by(email=email).one()
  23.     except: # no user found
  24.         return UNKNOWN_EMAIL_MESSAGE
  25.     if user._encrypt_password(password) == user.password: # select the first record and encrypt pass
  26.         return user.id # successful login
  27.     else:
  28.         return INCORRECT_PASSWORD_MESSAGE
  29.    
  30. def check_auth(func):
  31.     """
  32.    A decorator which checks whether the user is logged in or not.
  33.    """
  34.     def wrap_f(*args, **kwargs):
  35.         if session.get(SESSION_KEY, None): # user is logged in
  36.             func(*args, **kwargs)
  37.         else:
  38.             return redirect(url_for('auth.login', redir=request.url))
  39.     return wrap_f
  40.    
  41. def auth_conditions(*conditions):
  42.     """
  43.    Specify some conditions for the auth
  44.    """
  45.     def wrap(func):
  46.         def wrap_f(*args, **kwargs):
  47.             for condition in conditions:
  48.                 if not condition():
  49.                     abort(403)
  50.             func(*args, **kwargs)
  51.         return wrap_f
  52.     return wrap
  53.    
  54. def user_id():
  55.     """
  56.    Return the user id
  57.    """
  58.     return session.get(SESSION_KEY) # get userid from session
  59.    
  60. # Conditions are callables that return True
  61. # if the user fulfills the conditions they define, False otherwise
  62. #
  63.  
  64. def is_admin():
  65.     """
  66.    Tell if the user is an administrator
  67.    """
  68.     return User.get_by(id=session[SESSION_KEY]).is_admin
  69.    
  70. def account_not_expired():
  71.     """
  72.    Make sure that the account hasn't yet expired
  73.    """
  74.     return User.get_by(id=session[SESSION_KEY]).days_left() is not 0
  75.    
  76.  
  77. ### The controller functions
  78.  
  79. def on_login(user_id):
  80.     """Called on successful login"""
  81.     user = User.get_by(id=user_id)
  82.     user.last_login = datetime.datetime.now() # set the last_login date/time
  83.     db_session.commit()
  84.  
  85. def on_logout(user_id):
  86.     """Called on logout"""
  87.  
  88. @auth.route('/login', methods=['POST', 'GET'])
  89. def login():
  90.     """
  91.    Log the user in.
  92.    """
  93.     form = LoginForm()
  94.        
  95.     if form.validate_on_submit():
  96.         check = check_credentials(form.email.data, form.password.data)
  97.         if check == UNKNOWN_EMAIL_MESSAGE:
  98.             form.email.errors.append(UNKNOWN_EMAIL_MESSAGE)
  99.         elif check == INCORRECT_PASSWORD_MESSAGE:
  100.             form.password.errors.append(INCORRECT_PASSWORD_MESSAGE)
  101.         else:
  102.             session[SESSION_KEY] = check # put the user id
  103.            
  104.             if form.remember_me.data == True: # if remember_me is set
  105.                 session[SESSION_KEY].permanent = True # set cookie for 31 days
  106.            
  107.             on_login(check)
  108.             return redirect(request.args.get('redir', url_for('site.index')))
  109.                
  110.     return render_template('auth/login.html', form=form)
  111.  
  112. @auth.route('/logout')
  113. def logout():
  114.     """
  115.    Log the user out deleting the session key.
  116.    """
  117.     session.pop(SESSION_KEY, None)
  118.     on_logout(user_id)
  119.     return redirect(url_for('site.index')) # redirect to homepage
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement