@@ -273,3 +273,76 @@ def simulate_activity():
273
273
time .sleep (1 )
274
274
275
275
return "ok" , 200
276
+
277
+
278
+ # See https://docs.docker.com/compose/how-tos/use-secrets/
279
+ with open ("/run/secrets/gh_oauth_client_id" ) as f :
280
+ GH_OAUTH_CLIENT_ID = f .read ().strip ()
281
+ with open ("/run/secrets/gh_oauth_secret" ) as f :
282
+ GH_OAUTH_CLIENT_SECRET = f .read ().strip ()
283
+ GH_OAUTH_ACCESS_TOKEN_URI = "https://github.com/login/oauth/access_token"
284
+ GH_OAUTH_REDIRECT_URI = "https://localhost/api/oauth"
285
+ GH_USER_API_URI = "https://api.github.com/user"
286
+
287
+
288
+ @app .get ("/oauth" )
289
+ def oauth_callback ():
290
+ code = request .args ["code" ]
291
+ resp = requests .post (
292
+ GH_OAUTH_ACCESS_TOKEN_URI ,
293
+ headers = {
294
+ "Accept" : "application/json" ,
295
+ },
296
+ json = {
297
+ "client_id" : GH_OAUTH_CLIENT_ID ,
298
+ "client_secret" : GH_OAUTH_CLIENT_SECRET ,
299
+ "code" : code ,
300
+ "redirect_uri" : GH_OAUTH_REDIRECT_URI ,
301
+ },
302
+ )
303
+
304
+ session ["gh_access_token" ] = resp .json ()["access_token" ]
305
+ resp = requests .get (
306
+ f"{ GH_USER_API_URI } " ,
307
+ headers = {
308
+ "Accept" : "application/json" ,
309
+ "Authorization" : f'Bearer { session ["gh_access_token" ]} ' ,
310
+ },
311
+ )
312
+ gh_user = resp .json ()
313
+
314
+ with get_db () as db :
315
+ with db .cursor () as cur :
316
+ cur .execute (
317
+ "SELECT id, name, email FROM users WHERE LOWER(email) = LOWER(%s)" ,
318
+ (gh_user ["email" ],),
319
+ )
320
+ if cur .rowcount < 1 :
321
+ cur .execute (
322
+ "INSERT INTO users(name, email) VALUES (%s, %s) RETURNING id" ,
323
+ (gh_user ["login" ], gh_user ["email" ]),
324
+ )
325
+ db .commit ()
326
+ user_session = {
327
+ "user_id" : cur .fetchone ()[0 ],
328
+ "name" : gh_user ["login" ],
329
+ "email" : gh_user ["email" ],
330
+ }
331
+ else :
332
+ user = cur .fetchone ()
333
+ user_session = {
334
+ "user_id" : user [0 ],
335
+ "name" : user [1 ],
336
+ "email" : user [2 ],
337
+ }
338
+
339
+ # Store the user_id in the Flask session to avoid a round-trip when upvoting.
340
+ session ["user_id" ] = user_session ["user_id" ]
341
+
342
+ # TODO: Error handling.
343
+ requests .patch (
344
+ f"{ REACTIVE_SERVICE_URL } /inputs/sessions" ,
345
+ json = [[session ["session_id" ], [user_session ]]],
346
+ )
347
+
348
+ return redirect ("/" )
0 commit comments