|
|
@@ -94,26 +94,35 @@ async def exchange_code(request_body: ExchangeCodeRequest):
|
|
|
logger.error("[OAuth] 授权码为空!前端未传递 code 参数")
|
|
|
raise HTTPException(status_code=400, detail="授权码为空,请检查前端是否正确传递 code 参数")
|
|
|
|
|
|
- # 1. 用授权码换取 SSO access_token
|
|
|
- logger.info(f"[OAuth] 开始向 SSO 换取 token, SSO地址: {settings.SSO_BASE_URL}{settings.SSO_TOKEN_ENDPOINT}")
|
|
|
- token_data = await OAuthService.exchange_code_for_token(request_body.code)
|
|
|
- sso_access_token = token_data.get("access_token")
|
|
|
-
|
|
|
- if not sso_access_token:
|
|
|
- logger.error(f"[OAuth] SSO 返回的 token 响应中没有 access_token, 完整响应: {token_data}")
|
|
|
- raise HTTPException(status_code=400, detail="未能获取访问令牌")
|
|
|
-
|
|
|
- logger.info(f"[OAuth] SSO token 获取成功, access_token 前20字符: {sso_access_token[:20]}...")
|
|
|
-
|
|
|
- # 2. 获取完整用户信息(含角色)
|
|
|
- logger.info("[OAuth] 开始获取用户信息")
|
|
|
- user_info = await OAuthService.get_user_profile(sso_access_token)
|
|
|
- logger.info(f"[OAuth] 用户信息: {user_info}")
|
|
|
-
|
|
|
- # 3. 同步用户到本地数据库
|
|
|
- logger.info(f"[OAuth] 开始同步用户到本地数据库, username={user_info.get('username')}")
|
|
|
- user = OAuthService.sync_user_from_oauth(user_info)
|
|
|
- logger.info(f"[OAuth] 用户同步完成, user.id={user.id}, user.role={user.role}")
|
|
|
+ try:
|
|
|
+ # 1. 用授权码换取 SSO access_token
|
|
|
+ logger.info(f"[OAuth] 开始向 SSO 换取 token, SSO地址: {settings.SSO_BASE_URL}{settings.SSO_TOKEN_ENDPOINT}")
|
|
|
+ token_data = await OAuthService.exchange_code_for_token(request_body.code)
|
|
|
+ sso_access_token = token_data.get("access_token")
|
|
|
+
|
|
|
+ if not sso_access_token:
|
|
|
+ logger.error(f"[OAuth] SSO 返回的 token 响应中没有 access_token, 完整响应: {token_data}")
|
|
|
+ raise HTTPException(status_code=400, detail="未能获取访问令牌")
|
|
|
+
|
|
|
+ logger.info(f"[OAuth] SSO token 获取成功, access_token 前20字符: {sso_access_token[:20]}...")
|
|
|
+
|
|
|
+ # 2. 获取完整用户信息(含角色)
|
|
|
+ logger.info("[OAuth] 开始获取用户信息")
|
|
|
+ user_info = await OAuthService.get_user_profile(sso_access_token)
|
|
|
+ logger.info(f"[OAuth] 用户信息: {user_info}")
|
|
|
+
|
|
|
+ # 3. 同步用户到本地数据库
|
|
|
+ logger.info(f"[OAuth] 开始同步用户到本地数据库, username={user_info.get('username')}")
|
|
|
+ user = OAuthService.sync_user_from_oauth(user_info)
|
|
|
+ logger.info(f"[OAuth] 用户同步完成, user.id={user.id}, user.role={user.role}")
|
|
|
+ except ValueError as e:
|
|
|
+ logger.error(f"[OAuth] 用户角色映射失败: {e}")
|
|
|
+ raise HTTPException(status_code=403, detail=str(e))
|
|
|
+ except HTTPException:
|
|
|
+ raise
|
|
|
+ except Exception as e:
|
|
|
+ logger.error(f"[OAuth] 授权码交换异常: {e}", exc_info=True)
|
|
|
+ raise HTTPException(status_code=500, detail=f"登录失败: {str(e)}")
|
|
|
|
|
|
# 4. 签发本地 JWT
|
|
|
access_token = jwt_service.create_access_token(
|