KrishnaCosmic commited on
Commit
548930f
·
1 Parent(s): 3fd898e

finalising

Browse files
Files changed (1) hide show
  1. middleware.py +94 -0
middleware.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Authentication middleware for API endpoints.
3
+ Supports both API key and JWT authentication.
4
+ """
5
+
6
+ import os
7
+ from fastapi import Header, HTTPException, Depends
8
+ from typing import Optional
9
+ from utils.jwt_utils import verify_jwt_token
10
+ from config.settings import settings
11
+
12
+
13
+ async def require_api_key_or_auth(
14
+ authorization: Optional[str] = Header(None),
15
+ x_api_key: Optional[str] = Header(None)
16
+ ) -> dict:
17
+ """
18
+ Authenticate request using either JWT token or API key.
19
+
20
+ Supports two authentication methods:
21
+ 1. Bearer token in Authorization header: "Authorization: Bearer <jwt_token>"
22
+ 2. API key in X-API-Key header: "X-API-Key: <api_key>"
23
+
24
+ Args:
25
+ authorization: Authorization header with Bearer token
26
+ x_api_key: X-API-Key header for API key authentication
27
+
28
+ Returns:
29
+ dict: Authentication context with user info or api_key
30
+
31
+ Raises:
32
+ HTTPException: If authentication fails
33
+ """
34
+
35
+ # Try JWT token authentication
36
+ if authorization and authorization.startswith('Bearer '):
37
+ token = authorization.replace('Bearer ', '')
38
+ try:
39
+ payload = verify_jwt_token(token)
40
+ return {
41
+ 'type': 'jwt',
42
+ 'user_id': payload.get('user_id'),
43
+ 'role': payload.get('role'),
44
+ 'authenticated': True
45
+ }
46
+ except HTTPException:
47
+ raise
48
+
49
+ # Try API key authentication
50
+ if x_api_key:
51
+ # Validate API key (can be extended to check against database)
52
+ api_key = os.environ.get('API_KEY', '')
53
+ if api_key and x_api_key == api_key:
54
+ return {
55
+ 'type': 'api_key',
56
+ 'api_key': x_api_key,
57
+ 'authenticated': True
58
+ }
59
+ raise HTTPException(status_code=401, detail="Invalid API key")
60
+
61
+ # No authentication provided
62
+ raise HTTPException(
63
+ status_code=401,
64
+ detail="Missing authentication. Provide either Bearer token or X-API-Key header"
65
+ )
66
+
67
+
68
+ async def get_optional_user(
69
+ authorization: Optional[str] = Header(None)
70
+ ) -> Optional[dict]:
71
+ """
72
+ Get the current user from JWT token if available.
73
+ Does not raise exceptions if authentication is missing.
74
+
75
+ Args:
76
+ authorization: Authorization header with Bearer token
77
+
78
+ Returns:
79
+ dict: User info if authenticated, None otherwise
80
+ """
81
+ if not authorization or not authorization.startswith('Bearer '):
82
+ return None
83
+
84
+ token = authorization.replace('Bearer ', '')
85
+ try:
86
+ payload = verify_jwt_token(token)
87
+ return {
88
+ 'user_id': payload.get('user_id'),
89
+ 'role': payload.get('role'),
90
+ 'authenticated': True
91
+ }
92
+ except HTTPException:
93
+ # Return None instead of raising exception for optional auth
94
+ return None