-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
154 lines (123 loc) · 4.79 KB
/
main.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
import os
import secrets
from urllib.parse import urlencode
from dotenv import load_dotenv
from flask import Flask, redirect, url_for, render_template, flash, session, \
current_app, request, abort
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager, UserMixin, login_user, logout_user,\
current_user
import requests
load_dotenv()
app = Flask(__name__)
app.config['SECRET_KEY'] = 'top secret!'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqlite'
app.config['OAUTH2_PROVIDERS'] = {
# Google OAuth 2.0 documentation:
# https://developers.google.com/identity/protocols/oauth2/web-server#httprest
'strava': {
'client_id': os.environ.get('STRAVA_CLIENT_ID'),
'client_secret': os.environ.get('STRAVA_CLIENT_SECRET'),
'authorize_url': 'https://www.strava.com/oauth/authorize',
'token_url': 'https://www.strava.com/api/v3/oauth/token',
'userinfo': {
'url': 'https://www.strava.com/api/v3/athlete',
'firstname': lambda json: json['firstname'],
},
'scopes': ['read_all'],
}
}
db = SQLAlchemy(app)
login = LoginManager(app)
login.login_view = 'index'
class User(UserMixin, db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(64), nullable=False)
firstname = db.Column(db.String(64), nullable=True)
@login.user_loader
def load_user(id):
return db.session.get(User, int(id))
@app.route('/')
def index():
return render_template('index.html')
@app.route('/logout')
def logout():
logout_user()
flash('You have been logged out.')
return redirect(url_for('index'))
@app.route('/authorize/<provider>')
def oauth2_authorize(provider):
if not current_user.is_anonymous:
return redirect(url_for('index'))
provider_data = current_app.config['OAUTH2_PROVIDERS'].get(provider)
if provider_data is None:
abort(404)
# generate a random string for the state parameter
session['oauth2_state'] = secrets.token_urlsafe(16)
# create a query string with all the OAuth2 parameters
qs = urlencode({
'client_id': provider_data['client_id'],
'redirect_uri': url_for('oauth2_callback', provider=provider,
_external=True),
'response_type': 'code',
'scope': ' '.join(provider_data['scopes']),
'state': session['oauth2_state'],
})
# redirect the user to the OAuth2 provider authorization URL
return redirect(provider_data['authorize_url'] + '?' + qs)
@app.route('/callback/<provider>')
def oauth2_callback(provider):
if not current_user.is_anonymous:
return redirect(url_for('index'))
provider_data = current_app.config['OAUTH2_PROVIDERS'].get(provider)
if provider_data is None:
abort(404)
# if there was an authentication error, flash the error messages and exit
if 'error' in request.args:
for k, v in request.args.items():
if k.startswith('error'):
flash(f'{k}: {v}')
return redirect(url_for('index'))
# make sure that the state parameter matches the one we created in the
# authorization request
if request.args['state'] != session.get('oauth2_state'):
abort(401)
# make sure that the authorization code is present
if 'code' not in request.args:
abort(401)
# exchange the authorization code for an access token
response = requests.post(provider_data['token_url'], data={
'client_id': provider_data['client_id'],
'client_secret': provider_data['client_secret'],
'code': request.args['code'],
'grant_type': 'authorization_code',
'redirect_uri': url_for('oauth2_callback', provider=provider,
_external=True),
}, headers={'Accept': 'application/json'})
if response.status_code != 200:
abort(401)
oauth2_token = response.json().get('access_token')
if not oauth2_token:
abort(401)
# use the access token to get the user's email address
response = requests.get(provider_data['userinfo']['url'], headers={
'Authorization': 'Bearer ' + oauth2_token,
'Accept': 'application/json',
})
if response.status_code != 200:
abort(401)
firstname = provider_data['userinfo']['firstname'](response.json())
# find or create the user in the database
user = db.session.scalar(db.select(User).where(User.firstname == firstname))
if user is None:
user = User(firstname=firstname, username=provider_data['userinfo']['firstname'](response.json()))
db.session.add(user)
db.session.commit()
# log the user in
login_user(user)
return redirect(url_for('index'))
with app.app_context():
db.create_all()
if __name__ == '__main__':
app.run(debug=True)