@@ -9,35 +9,44 @@ async def oauth_callback(code: str, state: str = None, stored_state: str = None)
99 if not state or not stored_state or not hmac .compare_digest (state , stored_state ):
1010 raise HTTPException (status_code = 400 , detail = "Invalid state parameter" )
1111
12- async with httpx .AsyncClient () as client :
13- token_resp = await client .post (
14- settings .OAUTH_TOKEN_URL ,
15- data = {
16- "grant_type" : "authorization_code" ,
17- "code" : code ,
18- "client_id" : settings .OAUTH_CLIENT_ID ,
19- "client_secret" : settings .OAUTH_CLIENT_SECRET ,
20- "redirect_uri" : settings .OAUTH_REDIRECT_URI ,
21- }
22- )
23- if token_resp .status_code != 200 :
24- raise HTTPException (status_code = token_resp .status_code , detail = "OAuth token exchange failed" )
12+ try :
13+ async with httpx .AsyncClient () as client :
14+ token_resp = await client .post (
15+ settings .OAUTH_TOKEN_URL ,
16+ data = {
17+ "grant_type" : "authorization_code" ,
18+ "code" : code ,
19+ "client_id" : settings .OAUTH_CLIENT_ID ,
20+ "client_secret" : settings .OAUTH_CLIENT_SECRET ,
21+ "redirect_uri" : settings .OAUTH_REDIRECT_URI ,
22+ }
23+ )
24+ except httpx .RequestError as e :
25+ raise HTTPException (status_code = 502 , detail = f"Failed to connect to OAuth server: { e } " )
26+
27+ if token_resp .status_code != 200 :
28+ raise HTTPException (status_code = token_resp .status_code , detail = "OAuth token exchange failed" )
2529
26- token_data = token_resp .json ()
27- access_token = token_data ["access_token" ]
30+ token_data = token_resp .json ()
31+ access_token = token_data ["access_token" ]
32+
33+ try :
34+ async with httpx .AsyncClient () as client :
35+ profile_resp = await client .get (
36+ settings .OAUTH_USERINFO_URL ,
37+ headers = {"Authorization" : f"Bearer { access_token } " }
38+ )
39+ except httpx .RequestError as e :
40+ raise HTTPException (status_code = 502 , detail = f"Failed to fetch user info: { e } " )
41+
42+ if profile_resp .status_code != 200 :
43+ raise HTTPException (status_code = profile_resp .status_code , detail = "Cannot fetch user info" )
2844
29- profile_resp = await client .get (
30- settings .OAUTH_USERINFO_URL ,
31- headers = {"Authorization" : f"Bearer { access_token } " }
32- )
33- if profile_resp .status_code != 200 :
34- raise HTTPException (status_code = profile_resp .status_code , detail = "Cannot fetch user info" )
35-
36- userinfo = profile_resp .json ()
37- return {
38- "provider" : "nycu" ,
39- "sub" : userinfo .get ("username" ),
40- "email" : userinfo .get ("email" ),
41- "name" : userinfo .get ("username" ),
42- "avatar_url" : None
43- }
45+ userinfo = profile_resp .json ()
46+ return {
47+ "provider" : "nycu" ,
48+ "sub" : userinfo .get ("username" ),
49+ "email" : userinfo .get ("email" ),
50+ "name" : userinfo .get ("username" ),
51+ "avatar_url" : None
52+ }
0 commit comments