-
Notifications
You must be signed in to change notification settings - Fork 1
/
app.py
296 lines (233 loc) · 7.54 KB
/
app.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
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
import logging
from os import getenv
from uuid import uuid4
from flask import Flask, jsonify, redirect, render_template, request, session
from flask_oauthlib.provider import OAuth1Provider
from flask_sqlalchemy import SQLAlchemy
from werkzeug.security import gen_salt
logger = logging.getLogger("flask_oauthlib")
logger.addHandler(logging.StreamHandler())
logger.setLevel(logging.DEBUG)
app = Flask(__name__, template_folder="templates")
app.secret_key = str(uuid4())
app.config.update(
{
"SQLALCHEMY_DATABASE_URI": "sqlite:///:memory:",
"SQLALCHEMY_TRACK_MODIFICATIONS": False,
"OAUTH1_PROVIDER_ENFORCE_SSL": False,
"OAUTH1_PROVIDER_KEY_LENGTH": (10, 100),
}
)
db = SQLAlchemy(app)
oauth = OAuth1Provider(app)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(40), unique=True)
email = db.Column(db.String(40))
name = db.Column(db.String(100))
class Client(db.Model):
client_key = db.Column(db.String(40), primary_key=True)
client_secret = db.Column(db.String(55), index=True, nullable=False)
# creator of the client
user_id = db.Column(db.ForeignKey("user.id"))
user = db.relationship("User")
_realms = db.Column(db.Text)
_redirect_uris = db.Column(db.Text)
@property
def redirect_uris(self):
if self._redirect_uris:
return self._redirect_uris.split()
return []
@property
def default_redirect_uri(self):
return self.redirect_uris[0]
@property
def default_realms(self):
if self._realms:
return self._realms.split()
return []
class RequestToken(db.Model):
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey("user.id", ondelete="CASCADE"))
user = db.relationship("User")
client_key = db.Column(
db.String(40),
db.ForeignKey("client.client_key"),
nullable=False,
)
client = db.relationship("Client")
token = db.Column(db.String(255), index=True, unique=True)
secret = db.Column(db.String(255), nullable=False)
verifier = db.Column(db.String(255))
redirect_uri = db.Column(db.Text)
_realms = db.Column(db.Text)
@property
def realms(self):
if self._realms:
return self._realms.split()
return []
class Nonce(db.Model):
id = db.Column(db.Integer, primary_key=True)
timestamp = db.Column(db.Integer)
nonce = db.Column(db.String(40))
client_key = db.Column(
db.String(40),
db.ForeignKey("client.client_key"),
nullable=False,
)
client = db.relationship("Client")
request_token = db.Column(db.String(50))
access_token = db.Column(db.String(50))
class AccessToken(db.Model):
id = db.Column(db.Integer, primary_key=True)
client_key = db.Column(
db.String(40),
db.ForeignKey("client.client_key"),
nullable=False,
)
client = db.relationship("Client")
user_id = db.Column(
db.Integer,
db.ForeignKey("user.id"),
)
user = db.relationship("User")
token = db.Column(db.String(255))
secret = db.Column(db.String(255))
_realms = db.Column(db.Text)
@property
def realms(self):
if self._realms:
return self._realms.split()
return []
def current_user():
if "id" in session:
uid = session["id"]
return User.query.get(uid)
return None
@app.route("/", methods=("GET", "POST"))
def home():
if request.method == "POST":
username = request.form.get("username")
user = User.query.filter_by(username=username).first()
session["id"] = user.id
if "next" in request.args:
return redirect(request.args["next"])
return redirect("/")
user = current_user()
return render_template("home.html", user=user)
@oauth.clientgetter
def load_client(client_key):
return Client.query.get(client_key)
@oauth.grantgetter
def load_request_token(token):
return RequestToken.query.filter_by(token=token).first()
@oauth.grantsetter
def save_request_token(token, request):
if hasattr(oauth, "realms") and oauth.realms:
realms = " ".join(request.realms)
else:
realms = None
grant = RequestToken(
token=token["oauth_token"],
secret=token["oauth_token_secret"],
client=request.client,
redirect_uri=request.redirect_uri,
_realms=realms,
)
db.session.add(grant)
db.session.commit()
return grant
@oauth.verifiergetter
def load_verifier(verifier, token):
return RequestToken.query.filter_by(verifier=verifier, token=token).first()
@oauth.verifiersetter
def save_verifier(token, verifier, *args, **kwargs):
tok = RequestToken.query.filter_by(token=token).first()
tok.verifier = verifier["oauth_verifier"]
tok.user = current_user()
db.session.add(tok)
db.session.commit()
return tok
@oauth.noncegetter
def load_nonce(client_key, timestamp, nonce, request_token, access_token):
return Nonce.query.filter_by(
client_key=client_key,
timestamp=timestamp,
nonce=nonce,
request_token=request_token,
access_token=access_token,
).first()
@oauth.noncesetter
def save_nonce(client_key, timestamp, nonce, request_token, access_token):
nonce = Nonce(
client_key=client_key,
timestamp=timestamp,
nonce=nonce,
request_token=request_token,
access_token=access_token,
)
db.session.add(nonce)
db.session.commit()
return nonce
@oauth.tokengetter
def load_access_token(client_key, token, *args, **kwargs):
return AccessToken.query.filter_by(client_key=client_key, token=token).first()
@oauth.tokensetter
def save_access_token(token, request):
tok = AccessToken(
client=request.client,
user=request.user,
token=token["oauth_token"],
secret=token["oauth_token_secret"],
_realms=token["oauth_authorized_realms"],
)
db.session.add(tok)
db.session.commit()
@app.route("/oauth/request_token", methods=["GET", "POST"])
@oauth.request_token_handler
def request_token():
return {}
@app.route("/oauth/access_token", methods=["GET", "POST"])
@oauth.access_token_handler
def access_token():
return {}
@app.route("/oauth/authorize", methods=["GET", "POST"])
@oauth.authorize_handler
def authorize(*args, **kwargs):
user = current_user()
if not user:
return redirect(f"/?next={request.url}")
if request.method == "GET":
client_key = kwargs.get("resource_owner_key")
client = Client.query.filter_by(client_key=client_key).first()
kwargs["client"] = client
kwargs["user"] = user
return render_template("authorize.html", **kwargs)
confirm = request.form.get("confirm", "no")
return confirm == "yes"
@app.route("/api/me")
@oauth.require_oauth()
def me():
user = request.oauth.access_token.user
return jsonify(
id=user.id,
screen_name=user.username,
email=user.email,
name=user.name,
)
@app.route("/api/health")
def health():
return ""
if __name__ == "__main__":
with app.app_context():
db.create_all()
client = Client(
client_key=getenv("OAUTH1_CLIENT_ID"),
client_secret=getenv("OAUTH1_CLIENT_SECRET"),
_redirect_uris=getenv("OAUTH1_REDIRECT_URI"),
)
user = User(username="example-user", email="[email protected]", name="test name")
db.session.add(user)
db.session.add(client)
db.session.commit()
app.run(host="0.0.0.0")