Validates the access token provided in the request headers.
| Parameters: |
-
credentials
(HTTPAuthorizationCredentials, default:
Depends(HTTPBearer())
)
–
The bearer token credentials.
|
| Returns: |
-
bool –
True if the user has access, otherwise raises HTTPException.
|
| Raises: |
-
HTTPException
–
If the token is invalid or the user is not authorized.
|
Source code in api/utils.py
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42 | async def has_access(credentials: HTTPAuthorizationCredentials = Depends(HTTPBearer())):
"""
Validates the access token provided in the request headers.
Args:
credentials (HTTPAuthorizationCredentials): The bearer token credentials.
Returns:
bool: True if the user has access, otherwise raises HTTPException.
Raises:
HTTPException: If the token is invalid or the user is not authorized.
"""
token = credentials.credentials
load_dotenv()
SECRET_KEY = os.environ.get("SECRET_KEY")
ALGORITHM = "HS256"
credentials_exception = HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Could not validate credentials",
headers={"WWW-Authenticate": "Bearer"},
)
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
username: str = payload.get("sub")
except JWTError:
raise credentials_exception
if username == "admin":
return True
else:
raise credentials_exception
|