-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.py
95 lines (76 loc) · 2.6 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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
from elixir import metadata
import models as m
import cherrypy
from helpers import error, redirect
from decorator import decorator
from cherrypy import HTTPError
def get_user_passwords():
users = m.User.query.all()
# later we can return dict which lookups from model
data = dict(((u.handle,u.password) for u in users))
return data
def hash_password(p):
return m.User.create_password_hash(p)
def set_user():
""" checks that a user is logged in or raises 403,
if user is logged in sets the cherrypy.request.user """
cherrypy.request.user = get_user_from_session()
return True
def get_user_from_session():
""" returns user found from session info """
return m.User.get_by(handle=cherrypy.session.get('user_handle'))
def get_user():
return get_user_from_session()
def check_active_login(skip=False,login=True):
"""
checks that there is an active user or sends back a 403
"""
cherrypy.log('checking active login %s %s' % (skip,login))
try:
if skip:
return True
# make sure there is a handle
if not cherrypy.session.get('user_handle'):
error(403)
# make sure there's a hash in the session
if not cherrypy.session.get('user_hash'):
error(403)
# find the user and check the hash against his password
user = m.User.get_by(handle=cherrypy.session.get('user_handle'))
if not user:
error(403)
if hash_password(user.password) != cherrypy.session.get('user_hash'):
error(403)
except HTTPError:
if login:
redirect('/login')
else:
raise
return user
def auth_credentials(handle,password):
""" returns user object if password is good """
user = m.User.get_by(handle=handle)
cherrypy.log('user: %s' % user)
if not user or hash_password(password) != user.password:
cherrypy.log('no user or no password match')
return False
return user
def set_logged_in_user(user):
""" updates the session from the user object """
cherrypy.session['user_hash'] = hash_password(user.password)
cherrypy.session['user_handle'] = user.handle
def login_user(handle,password):
user = auth_credentials(handle,password)
if user:
set_logged_in_user(user)
else:
return False
return True
def logout_user():
if 'user_handle' in cherrypy.session:
del cherrypy.session['user_handle']
if 'user_hash' in cherrypy.session:
del cherrypy.session['user_hash']
def public(f):
f._cp_config = {'tools.check_active_login.skip':True}
return f