File size: 2,014 Bytes
a8a2cf5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# read_me (route)
#    |
#    └── get_user_with_permissions
#            β”œβ”€β”€ get_database
#            └── get_current_user
#                    └── HTTPBearer (security)

from fastapi import Depends, HTTPException, status
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from jwt import decode, InvalidTokenError
from ..core.config.config import settings
from datetime import datetime

async def get_database():
    """
    A placeholder function to simulate database access.
    In a real application, this would return a database session/connection.
    """
    # For now, returns None - implement actual DB connection
    try:
        yield None
    finally:
        pass

security = HTTPBearer() ## we will get the header of the http request by using this method

async def get_current_user(credentials: HTTPAuthorizationCredentials = Depends(security)):

    """
    A function to get the current user based on the provided token.
    this dependency:
    - extract the token from the request header
    - validate it 
    - return the user information if valid.
    
    """
    token = credentials.credentials # It returns the raw token value (without Bearer) from the request header.

    # Validate token
    try:
        payload = decode(token, settings.SECRET_KEY, algorithms=[settings.JWT_ALGORITHM])
        user_id: str = payload.get("sub")
        if user_id is None:
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="Invalid token"
            )
    except InvalidTokenError:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Invalid or expired token"
        )
    
    return {"user_id": user_id}

async def get_user_with_permissions(
        db = Depends(get_database),
        user = Depends(get_current_user)
):
    # permissions = await fetch_user_permissions(db, user.id)
    # user.permissions = permissions
    return user