Skip to content

Commit a3efa61

Browse files
authored
♻️ Trans exception from format JSONResponse to format HTTPException in user_managerment_app.py
2 parents c8d9c1c + 1ef6be3 commit a3efa61

File tree

5 files changed

+267
-205
lines changed

5 files changed

+267
-205
lines changed

backend/apps/user_management_app.py

Lines changed: 59 additions & 90 deletions
Original file line numberDiff line numberDiff line change
@@ -24,15 +24,16 @@
2424
async def service_health():
2525
"""Service health check"""
2626
try:
27-
is_available = await check_auth_service_health()
27+
await check_auth_service_health()
2828

29-
if is_available:
30-
return JSONResponse(status_code=HTTPStatus.OK, content={"message": "Auth service is available"})
31-
else:
32-
return JSONResponse(status_code=HTTPStatus.SERVICE_UNAVAILABLE, content={"message": "Auth service is unavailable"})
29+
return JSONResponse(status_code=HTTPStatus.OK,
30+
content={"message": "Auth service is available"})
31+
except ConnectionError as e:
32+
logging.error(f"Auth service health check failed: {str(e)}")
33+
raise HTTPException(status_code=HTTPStatus.SERVICE_UNAVAILABLE, detail="Auth service is unavailable")
3334
except Exception as e:
3435
logging.error(f"Auth service health check failed: {str(e)}")
35-
return HTTPException(status_code=HTTPStatus.INTERNAL_SERVER_ERROR, detail="Auth service is unavailable")
36+
raise HTTPException(status_code=HTTPStatus.INTERNAL_SERVER_ERROR, detail="Auth service is unavailable")
3637

3738

3839
@router.post("/signup")
@@ -50,63 +51,29 @@ async def signup(request: UserSignUpRequest):
5051
return JSONResponse(status_code=HTTPStatus.OK,
5152
content={"message":success_message, "data":user_data})
5253
except NoInviteCodeException as e:
53-
message = "Admin registration feature is not available, please contact the system administrator to configure the invite code"
54-
data = {
55-
"error_type": "INVITE_CODE_NOT_CONFIGURED",
56-
"details": "The system has not configured the admin invite code, please contact technical support"
57-
}
5854
logging.error(f"User registration failed by invite code: {str(e)}")
59-
return JSONResponse(status_code=HTTPStatus.INTERNAL_SERVER_ERROR,
60-
content={"message": message, "data": data})
55+
raise HTTPException(status_code=HTTPStatus.INTERNAL_SERVER_ERROR,
56+
detail="INVITE_CODE_NOT_CONFIGURED")
6157
except IncorrectInviteCodeException as e:
62-
message = "Admin invite code error, please check and re-enter"
63-
data = {
64-
"error_type": "INVITE_CODE_INVALID",
65-
"field": "inviteCode",
66-
"hint": "Please confirm that the invite code is entered correctly, case-sensitive"
67-
}
6858
logging.error(f"User registration failed by invite code: {str(e)}")
69-
return JSONResponse(status_code=HTTPStatus.INTERNAL_SERVER_ERROR,
70-
content={"message": message, "data": data})
59+
raise HTTPException(status_code=HTTPStatus.INTERNAL_SERVER_ERROR,
60+
detail="INVITE_CODE_INVALID")
7161
except UserRegistrationException as e:
72-
message = "Registration service is temporarily unavailable, please try again later"
73-
data = {
74-
"error_type": "REGISTRATION_SERVICE_ERROR",
75-
"details": "Authentication service response exception"
76-
}
7762
logging.error(f"User registration failed by registration service: {str(e)}")
78-
return JSONResponse(status_code=HTTPStatus.INTERNAL_SERVER_ERROR,
79-
content={"message": message, "data": data})
63+
raise HTTPException(status_code=HTTPStatus.INTERNAL_SERVER_ERROR,
64+
detail="REGISTRATION_SERVICE_ERROR")
8065
except AuthApiError as e:
81-
message = f"Email {request.email} has already been registered"
82-
data = {
83-
"error_type": "EMAIL_ALREADY_EXISTS",
84-
"field": "email",
85-
"suggestion": "Please use a different email address or try logging in to an existing account"
86-
}
8766
logging.error(f"User registration failed by email already exists: {str(e)}")
88-
return JSONResponse(status_code=HTTPStatus.CONFLICT,
89-
content={"message": message, "data": data})
67+
raise HTTPException(status_code=HTTPStatus.CONFLICT,
68+
detail="EMAIL_ALREADY_EXISTS")
9069
except AuthWeakPasswordError as e:
91-
message = "Password strength is not enough, please set a stronger password"
92-
data = {
93-
"error_type": "WEAK_PASSWORD",
94-
"field": "password",
95-
"requirements": "Password must be at least 6 characters long, including letters, numbers, and special symbols"
96-
}
9770
logging.error(f"User registration failed by weak password: {str(e)}")
98-
return JSONResponse(status_code=HTTPStatus.UNPROCESSABLE_ENTITY,
99-
content={"message": message, "data": data})
71+
raise HTTPException(status_code=HTTPStatus.UNPROCESSABLE_ENTITY,
72+
detail="WEAK_PASSWORD")
10073
except Exception as e:
101-
message = "Registration failed, please try again later"
102-
data = {
103-
"error_type": "UNKNOWN_ERROR",
104-
"details": f"System error: {str(e)[:100]}",
105-
"suggestion": "If the problem persists, please contact technical support"
106-
}
10774
logging.error(f"User registration failed, unknown error: {str(e)}")
108-
return JSONResponse(status_code=HTTPStatus.INTERNAL_SERVER_ERROR,
109-
content={"message": message, "data": data})
75+
raise HTTPException(status_code=HTTPStatus.INTERNAL_SERVER_ERROR,
76+
detail="UNKNOWN_ERROR")
11077

11178

11279
@router.post("/signin")
@@ -119,88 +86,88 @@ async def signin(request: UserSignInRequest):
11986
content=signin_content)
12087
except AuthApiError as e:
12188
logging.error(f"User login failed: {str(e)}")
122-
return JSONResponse(status_code=HTTPStatus.UNPROCESSABLE_ENTITY,
123-
content={"message": "Email or password error"})
89+
raise HTTPException(status_code=HTTPStatus.UNPROCESSABLE_ENTITY,
90+
detail="Email or password error")
12491
except Exception as e:
12592
logging.error(f"User login failed, unknown error: {str(e)}")
126-
return JSONResponse(status_code=HTTPStatus.INTERNAL_SERVER_ERROR,
127-
content={"message": "Login failed"})
93+
raise HTTPException(status_code=HTTPStatus.INTERNAL_SERVER_ERROR,
94+
detail="Login failed")
12895

12996

13097
@router.post("/refresh_token")
13198
async def user_refresh_token(request: Request):
13299
"""Refresh token"""
100+
authorization = request.headers.get("Authorization")
101+
if not authorization:
102+
raise HTTPException(status_code=HTTPStatus.UNAUTHORIZED,
103+
detail="No authorization token provided")
133104
try:
134-
authorization = request.headers.get("Authorization")
135-
if not authorization:
136-
return JSONResponse(status_code=HTTPStatus.UNAUTHORIZED,
137-
content={"message": "No authorization token provided"})
138105
session_data = await request.json()
139106
refresh_token = session_data.get("refresh_token")
140107
if not refresh_token:
141-
return JSONResponse(status_code=HTTPStatus.UNPROCESSABLE_ENTITY,
142-
content={"message": "No refresh token provided"})
108+
raise ValueError("No refresh token provided")
143109
session_info = await refresh_user_token(authorization, refresh_token)
144110
return JSONResponse(status_code=HTTPStatus.OK,
145111
content={"message":"Token refresh successful", "data":{"session": session_info}})
112+
except ValueError as e:
113+
logging.error(f"Refresh token failed: {str(e)}")
114+
raise HTTPException(status_code=HTTPStatus.UNPROCESSABLE_ENTITY,
115+
detail="No refresh token provided")
146116
except Exception as e:
147117
logging.error(f"Refresh token failed: {str(e)}")
148-
return JSONResponse(status_code=HTTPStatus.INTERNAL_SERVER_ERROR,
149-
content={"message": "Refresh token failed"})
118+
raise HTTPException(status_code=HTTPStatus.INTERNAL_SERVER_ERROR,
119+
detail="Refresh token failed")
150120

151121

152122
@router.post("/logout")
153123
async def logout(request: Request):
154124
"""User logout"""
125+
authorization = request.headers.get("Authorization")
126+
if not authorization:
127+
raise HTTPException(status_code=HTTPStatus.UNAUTHORIZED,
128+
detail="User not logged in")
155129
try:
156-
authorization = request.headers.get("Authorization")
157-
if not authorization:
158-
return JSONResponse(status_code=HTTPStatus.UNAUTHORIZED,
159-
content={"message": "User not logged in"})
160-
161130
client = get_authorized_client(authorization)
162131
client.auth.sign_out()
163132
return JSONResponse(status_code=HTTPStatus.OK,
164133
content={"message":"Logout successful"})
165134

166135
except Exception as e:
167136
logging.error(f"User logout failed: {str(e)}")
168-
return JSONResponse(status_code=HTTPStatus.INTERNAL_SERVER_ERROR,
169-
content={"message": "Logout failed!"})
137+
raise HTTPException(status_code=HTTPStatus.INTERNAL_SERVER_ERROR,
138+
detail="Logout failed!")
170139

171140

172141
@router.get("/session")
173142
async def get_session(request: Request):
174143
"""Get current user session"""
144+
authorization = request.headers.get("Authorization")
145+
if not authorization:
146+
raise HTTPException(status_code=HTTPStatus.UNAUTHORIZED,
147+
detail="User not logged in")
175148
try:
176-
authorization = request.headers.get("Authorization")
177-
if not authorization:
178-
return JSONResponse(status_code=HTTPStatus.UNAUTHORIZED,
179-
content={"message": "No authorization token provided"})
180-
181149
data = await get_session_by_authorization(authorization)
182150
return JSONResponse(status_code=HTTPStatus.OK,
183151
content={"message": "Session is valid",
184152
"data": data})
185153
except ValueError as e:
186154
logging.error(f"Get user session failed: {str(e)}")
187-
return JSONResponse(status_code=HTTPStatus.UNPROCESSABLE_ENTITY,
188-
content={"message": "Session is invalid"})
155+
raise HTTPException(status_code=HTTPStatus.UNPROCESSABLE_ENTITY,
156+
detail="Session is invalid")
189157
except Exception as e:
190158
logging.error(f"error in get user session, {str(e)}")
191-
return JSONResponse(status_code=HTTPStatus.INTERNAL_SERVER_ERROR,
192-
content={"message": "Get user session failed"})
159+
raise HTTPException(status_code=HTTPStatus.INTERNAL_SERVER_ERROR,
160+
detail="Get user session failed")
193161

194162

195163
@router.get("/current_user_id")
196164
async def get_user_id(request: Request):
197165
"""Get current user ID, return None if not logged in"""
166+
authorization = request.headers.get("Authorization")
167+
if not authorization:
168+
raise HTTPException(status_code=HTTPStatus.UNAUTHORIZED,
169+
detail="User not logged in")
198170
try:
199-
authorization = request.headers.get("Authorization")
200-
if not authorization:
201-
return JSONResponse(status_code=HTTPStatus.UNAUTHORIZED,
202-
content={"message": "No authorization token provided"})
203-
204171
# Use the unified token validation function
205172
is_valid, user = validate_token(authorization)
206173
if is_valid and user:
@@ -214,11 +181,13 @@ async def get_user_id(request: Request):
214181
return JSONResponse(status_code=HTTPStatus.OK,
215182
content={"message": "Successfully parsed user ID from token",
216183
"data": {"user_id": user_id}})
184+
raise ValueError("User not logged in or session invalid")
217185

218-
# If all methods fail, return the session invalid information
219-
return JSONResponse(status_code=HTTPStatus.UNPROCESSABLE_ENTITY,
220-
content={"message": "User not logged in or session invalid"})
186+
except ValueError as e:
187+
logging.error(f"Get user ID failed: {str(e)}")
188+
raise HTTPException(status_code=HTTPStatus.UNPROCESSABLE_ENTITY,
189+
detail="User not logged in or session invalid")
221190
except Exception as e:
222191
logging.error(f"Get user ID failed: {str(e)}")
223-
return JSONResponse(status_code=HTTPStatus.INTERNAL_SERVER_ERROR,
224-
content={"message": "Get user ID failed"})
192+
raise HTTPException(status_code=HTTPStatus.INTERNAL_SERVER_ERROR,
193+
detail="Get user ID failed")

backend/services/user_management_service.py

Lines changed: 20 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -80,35 +80,27 @@ def extend_session(client: Client, refresh_token: str) -> Optional[dict]:
8080
return None
8181

8282

83-
async def check_auth_service_health() -> bool:
83+
async def check_auth_service_health():
8484
"""
8585
Check the health status of the authentication service
8686
Return (is available, status message)
8787
"""
88-
try:
89-
supabase_url = os.getenv("SUPABASE_URL")
90-
supabase_key = os.getenv("SUPABASE_KEY")
91-
92-
health_url = f'{supabase_url}/auth/v1/health'
93-
headers = {'apikey': supabase_key}
88+
supabase_url = os.getenv("SUPABASE_URL")
89+
supabase_key = os.getenv("SUPABASE_KEY")
9490

95-
async with aiohttp.ClientSession() as session:
96-
async with session.get(health_url, headers=headers) as response:
97-
if not response.ok:
98-
return False
91+
health_url = f'{supabase_url}/auth/v1/health'
92+
headers = {'apikey': supabase_key}
9993

100-
data = await response.json()
101-
# Check if the service is available by checking if the response contains the name field and its value is "GoTrue"
102-
is_available = data and data.get("name") == "GoTrue"
94+
async with aiohttp.ClientSession() as session:
95+
async with session.get(health_url, headers=headers) as response:
96+
if not response.ok:
97+
raise ConnectionError("Auth service is unavailable")
10398

104-
return is_available
105-
106-
except aiohttp.ClientError as e:
107-
logging.error(f"Auth service connection failed: {str(e)}")
108-
return False
109-
except Exception as e:
110-
logging.error(f"Auth service health check failed: {str(e)}")
111-
return False
99+
data = await response.json()
100+
# Check if the service is available by verifying the name field equals "GoTrue"
101+
if not data or data.get("name", "") != "GoTrue":
102+
logging.error("Auth service is unavailable")
103+
raise ConnectionError("Auth service is unavailable")
112104

113105

114106
async def signup_user(email: EmailStr,
@@ -287,11 +279,12 @@ async def get_session_by_authorization(authorization):
287279
user_role = "user" # Default role
288280
if user.user_metadata and 'role' in user.user_metadata:
289281
user_role = user.user_metadata['role']
290-
return {"user": {
291-
"id": user.id,
292-
"email": user.email,
293-
"role": user_role
294-
}
282+
return {
283+
"user": {
284+
"id": user.id,
285+
"email": user.email,
286+
"role": user_role
287+
}
295288
}
296289
else:
297290
raise ValueError("Session is invalid")

frontend/components/auth/registerModal.tsx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -135,7 +135,7 @@ export function RegisterModal() {
135135

136136
// process the specific error type returned by the backend (based on HTTP status code and error_type)
137137
const httpStatusCode = error?.code;
138-
const errorType = error?.data?.error_type;
138+
const errorType = error?.message;
139139

140140
// HTTP 409 Conflict
141141
if (httpStatusCode === 409 || errorType === "EMAIL_ALREADY_EXISTS") {

0 commit comments

Comments
 (0)