1+ from flask import Blueprint , render_template , redirect , url_for , session , request , jsonify
2+ from urllib .parse import urlencode
3+ import secrets
4+ import requests
5+ import os
6+ #from . import db
7+
8+ app_secret = ''
9+
10+ client_id = os .getenv ('GAMMA_CLIENT_ID' , '' )
11+ client_secret = os .getenv ('GAMMA_CLIENT_SECRET' , '' )
12+ redirect_uri = os .getenv ('GAMMA_REDIRECT_URI' , 'http://localhost:5000/api/auth/callbacks/gamma' )
13+ auth_uri = os .getenv ('GAMMA_AUTH_URL' , 'https://auth.chalmers.it/oauth2/authorize' )
14+ token_uri = os .getenv ('GAMMA_TOKEN_URL' , 'https://auth.chalmers.it/oauth2/token' )
15+ user_info_uri = os .getenv ('GAMMA_USER_INFO_URL' , 'https://auth.chalmers.it/oauth2/userinfo' )
16+
17+ auth = Blueprint ('auth' , __name__ )
18+
19+ @auth .route ('/login' )
20+ def login ():
21+ return render_template ('login.html' )
22+
23+ @auth .route ('/authorize' )
24+ def authorize ():
25+ # Generate and store state parameter for CSRF protection
26+ state = secrets .token_urlsafe (32 )
27+ session ['oauth2_state' ] = state
28+
29+ qs = {
30+ 'response_type' : 'code' ,
31+ 'client_id' : client_id ,
32+ 'scope' : 'openid' , #profile
33+ 'redirect_uri' : redirect_uri ,
34+ 'state' :state ,
35+ }
36+
37+ return redirect (f"{ auth_uri } ?{ urlencode (qs )} " )
38+
39+ @auth .route ('/api/auth/callbacks/gamma' )
40+ def callback ():
41+ args_dict = dict (request .args )
42+ print (args_dict )
43+
44+ if 'code' not in args_dict :
45+ return "Error: Missing authorization code parameter" , 400
46+
47+ if 'state' not in args_dict :
48+ return "Error: Missing state parameter" , 400
49+
50+ received_state = args_dict ['state' ]
51+ stored_state = session .get ('oauth2_state' )
52+
53+ if not stored_state or received_state != stored_state :
54+ return "Error: Invalid state parameter" , 400
55+
56+ session .pop ('oauth2_state' , None )
57+
58+ code = args_dict ['code' ]
59+ return code
60+
61+
62+
63+ # @auth.route('/signup')
64+ # def signup():
65+ # return 'Signup'
66+
67+ @auth .route ('/logout' )
68+ def logout ():
69+ return render_template ('logout.html' )
0 commit comments