Asma-yaseen commited on
Commit
e3ce5e3
·
verified ·
1 Parent(s): d268d79

Upload middleware/auth.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. middleware/auth.py +58 -0
middleware/auth.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ JWT Authentication Middleware.
3
+
4
+ Task: 1.5
5
+ Spec: specs/features/authentication.md
6
+ """
7
+ from fastapi import HTTPException, Depends, status
8
+ from fastapi.security import HTTPBearer
9
+ import jwt
10
+ import os
11
+
12
+ security = HTTPBearer()
13
+
14
+ # JWT Configuration
15
+ JWT_SECRET = os.getenv("JWT_SECRET", "your-secret-key-min-32-chars")
16
+ JWT_ALGORITHM = "HS256"
17
+
18
+
19
+ async def verify_token(credentials = Depends(security)) -> str:
20
+ """
21
+ Verify JWT token and extract user_id.
22
+
23
+ Args:
24
+ credentials: HTTP Bearer credentials from request header
25
+
26
+ Returns:
27
+ str: user_id extracted from token payload
28
+
29
+ Raises:
30
+ HTTPException: 401 if token is invalid or expired
31
+ """
32
+ token = credentials.credentials
33
+
34
+ try:
35
+ # Decode and verify JWT token
36
+ payload = jwt.decode(token, JWT_SECRET, algorithms=[JWT_ALGORITHM])
37
+
38
+ # Extract user_id from payload
39
+ user_id = payload.get("user_id")
40
+
41
+ if not user_id:
42
+ raise HTTPException(
43
+ status_code=status.HTTP_401_UNAUTHORIZED,
44
+ detail="Invalid token: user_id not found"
45
+ )
46
+
47
+ return user_id
48
+
49
+ except jwt.ExpiredSignatureError:
50
+ raise HTTPException(
51
+ status_code=status.HTTP_401_UNAUTHORIZED,
52
+ detail="Token expired. Please login again."
53
+ )
54
+ except jwt.InvalidTokenError:
55
+ raise HTTPException(
56
+ status_code=status.HTTP_401_UNAUTHORIZED,
57
+ detail="Invalid token. Please login again."
58
+ )