-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathauth.py
77 lines (61 loc) · 2.16 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
from authlib.integrations.flask_client import OAuth, OAuthError
from flask import Blueprint
from flask import flash
from flask import redirect
from flask import request
from flask import session
from flask import url_for
from urllib.parse import unquote, urlparse
import config
auth = Blueprint('auth', __name__, template_folder='templates')
oauth = OAuth()
oauth.register(
name='google',
client_id=config.GOOGLE_OAUTH_CONSUMER_KEY,
client_secret=config.GOOGLE_OAUTH_CONSUMER_SECRET,
server_metadata_url='https://accounts.google.com/.well-known/openid-configuration',
client_kwargs={
'scope': 'openid email profile',
},
)
def configure_auth(app):
oauth.init_app(app)
app.register_blueprint(auth, url_prefix='/auth')
@auth.route('/')
@auth.route('/login')
def login():
next_path = request.args.get('next')
if next_path:
# Since passing along the "next" URL as a GET param requires
# a different callback for each page, and Google requires us to
# whitelist each allowed callback page, we can't pass it as a GET
# param. Instead, we sanitize and put into the session.
request_components = urlparse(request.url)
path = unquote(next_path)
if path[0] == '/':
# This first slash is unnecessary since we force it in when we
# format next_url.
path = path[1:]
next_url = "{scheme}://{netloc}/{path}".format(
scheme=request_components.scheme,
netloc=request_components.netloc,
path=path,
)
session['next_url'] = next_url
return oauth.google.authorize_redirect(
redirect_uri=url_for('.authorized', _external=True))
@auth.route('/logout')
def logout():
session.pop('user', None)
return redirect(url_for('index'))
@auth.route('/login/authorized')
def authorized():
next_url = session.pop('next_url', url_for('index'))
try:
token = oauth.google.authorize_access_token()
session.permanent = True
session['user'] = token['userinfo']
return redirect(next_url)
except OAuthError:
flash("You didn't sign in.")
return redirect(next_url)