-
Notifications
You must be signed in to change notification settings - Fork 3
/
auth.py
84 lines (61 loc) · 2.18 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
# encoding: utf-8
import os.path
from functools import wraps
import flask
from flask.ext.openid import OpenID, COMMON_PROVIDERS
import database
oid = OpenID()
auth = flask.Blueprint('auth', __name__)
def lookup_current_user():
flask.g.user = None
if 'openid_url' in flask.session:
flask.g.user = database.get_user(flask.session['openid_url'])
@auth.route('/login', methods=['GET', 'POST'])
@oid.loginhandler
def login():
if flask.g.user is not None:
return flask.redirect(oid.get_next_url())
return oid.try_login(COMMON_PROVIDERS['google'],
ask_for=['email', 'fullname', 'nickname'])
@oid.after_login
def create_or_login(resp):
flask.session['openid_url'] = resp.identity_url
flask.g.user = database.get_update_user(
openid_url=resp.identity_url,
name=resp.fullname or resp.nickname,
email=resp.email)
name = flask.g.user.name or u""
flask.flash(u"Autentificare cu succes - %s" % name, 'success')
return flask.redirect(oid.get_next_url())
@auth.route('/logout')
def logout():
flask.session.pop('openid_url', None)
flask.flash(u"Ați fost dezautentificat.")
return flask.redirect(oid.get_next_url())
def require_login(func):
@wraps(func)
def wrapper(*args, **kwargs):
if flask.g.user is None:
flask.flash(u"Vă rugăm să vă autentificați", 'error')
return flask.render_template('layout.html')
return func(*args, **kwargs)
return wrapper
def is_admin(user):
if user is None:
return False
admins = flask.current_app.config.get('ADMIN_OPENIDS', [])
return (user.openid_url in admins)
def require_admin(func):
@wraps(func)
def wrapper(*args, **kwargs):
if not is_admin(flask.g.user):
flask.flash(u"Pagină rezervată administratorilor", 'error')
return flask.render_template('layout.html')
return func(*args, **kwargs)
return wrapper
def init_app(app):
app.register_blueprint(auth)
oid.init_app(app)
oid.fs_store_path = os.path.join(app.instance_path, 'openid-store')
app.before_request(lookup_current_user)
app.jinja_env.globals['is_admin'] = is_admin