forked from drachenwald/dw_op
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauth.py
75 lines (55 loc) · 1.92 KB
/
auth.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import functools
import werkzeug.security
from flask import current_app, flash, redirect, render_template, request, session, url_for
import config
#
# User accounts
#
#
# password hash generated by:
#
# werkzeug.security.generate_password_hash('password')
#
class User(object):
def __init__(self, username, pwhash, realname, email):
self.username = username
self.pwhash = pwhash
self.realname = realname
self.email = email
def check_password(self, password):
return werkzeug.security.check_password_hash(self.pwhash, password)
#
# User authentication
#
def login_required(f):
# pass through if authentication is disabled
if getattr(config, 'DISABLE_AUTH', False):
return f
# otherwise redirect to login page if unauthenticated
@functools.wraps(f)
def decorated_function(*args, **kwargs):
if 'username' not in session:
return redirect(url_for('login', next=request.url))
return f(*args, **kwargs)
return decorated_function
def auth_user(username, password):
user = current_app.config['USERS'].get(username, None)
return user and user.check_password(password)
def handle_login(login_setup, default_redirect):
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
if auth_user(username, password):
session['username'] = username
flash('Welcome, ' + username + '.', 'notice')
login_setup(username)
return redirect(request.args.get('next') or url_for(default_redirect))
else:
flash('Invalid username or password!', 'error')
return render_template('login.html')
def handle_logout(logout_teardown):
username = session.pop('username', None)
if username:
logout_teardown(username)
flash('Goodbye, ' + username + '.', 'notice')
return redirect(url_for('login'))