Skip to content

jwt_auth

A module that contains the custom JWT Auth.

Classes
  • JWTAuthentication: A class that handle custom JWT Auth.
Functions
  • generate_token(email, key): A function that generate JWT token.
  • verify_token(token, key): A function that verify JWT token.

JWTAuthentication

Bases: authentication.BaseAuthentication

Custom JWT Authentication Class.

Methods
  • authenticate(request): A function that handle JWT authentication.
Source code in backend/api/users/jwt_auth.py
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
class JWTAuthentication(authentication.BaseAuthentication):
    """Custom JWT Authentication Class.

    Methods:
        - authenticate(request):
            A function that handle JWT authentication.
    """

    def authenticate(self, request: Request):
        """Authenticate user based on JWT token in request header.

        Args:
            request: The HTTP request object.

        Raises:
            AuthenticationFailed: If the JWT token is invalid or not present in the request header.

        Returns:
            A tuple of (user, None) if authentication succeeds, or None if it fails.
        """
        token = request.headers.get('Authorization')
        if token:
            try:
                payload = verify_token(token, settings.SECRET_KEY)
                from .models import AuthUser
                user = AuthUser.objects.filter(email=payload["email"]).first()
            except jwt.InvalidTokenError:
                raise exceptions.AuthenticationFailed('Invalid token')
        else:
            raise exceptions.AuthenticationFailed('Token required')

        return user, None

authenticate(request)

Authenticate user based on JWT token in request header.

Parameters:

Name Type Description Default
request Request

The HTTP request object.

required

Raises:

Type Description
AuthenticationFailed

If the JWT token is invalid or not present in the request header.

Returns:

Type Description

A tuple of (user, None) if authentication succeeds, or None if it fails.

Source code in backend/api/users/jwt_auth.py
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
def authenticate(self, request: Request):
    """Authenticate user based on JWT token in request header.

    Args:
        request: The HTTP request object.

    Raises:
        AuthenticationFailed: If the JWT token is invalid or not present in the request header.

    Returns:
        A tuple of (user, None) if authentication succeeds, or None if it fails.
    """
    token = request.headers.get('Authorization')
    if token:
        try:
            payload = verify_token(token, settings.SECRET_KEY)
            from .models import AuthUser
            user = AuthUser.objects.filter(email=payload["email"]).first()
        except jwt.InvalidTokenError:
            raise exceptions.AuthenticationFailed('Invalid token')
    else:
        raise exceptions.AuthenticationFailed('Token required')

    return user, None

generate_token(email, key)

Generate a JSON Web Token (JWT) using the provided email and key.

Parameters:

Name Type Description Default
email str

The email address to include in the token's payload.

required
key str

The key to use for encoding the token.

required

Returns:

Type Description
str

A string representation of the generated token.

Source code in backend/api/users/jwt_auth.py
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
def generate_token(email: str, key: str) -> str:
    """Generate a JSON Web Token (JWT) using the provided email and key.

    Args:
        email: The email address to include in the token's payload.
        key: The key to use for encoding the token.

    Returns:
        A string representation of the generated token.
    """
    token = jwt.encode(
        payload={"email": email},
        key=key,
        algorithm="HS256"
    )
    return token

verify_token(token, key)

Verify a JSON Web Token (JWT) using the provided key.

Parameters:

Name Type Description Default
token str

The JWT to verify.

required
key str

The key to use for verifying the JWT.

required

Raises:

Type Description
jwt.InvalidTokenError

If the token cannot be verified or decoded.

Returns:

Type Description
dict

A dictionary representation of the decoded payload.

Source code in backend/api/users/jwt_auth.py
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
def verify_token(token: str, key: str) -> dict:
    """Verify a JSON Web Token (JWT) using the provided key.

    Args:
        token: The JWT to verify.
        key: The key to use for verifying the JWT.

    Raises:
        jwt.InvalidTokenError: If the token cannot be verified or decoded.

    Returns:
        A dictionary representation of the decoded payload.
    """
    payload = jwt.decode(
        jwt=token,
        key=key,
        algorithms=["HS256"]
    )
    return payload