File size: 2,534 Bytes
00c2d61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
66
67
68
69
70
71
72
73
74
75
76
77
78
from rest_framework_simplejwt.tokens import AccessToken
from rest_framework_simplejwt.exceptions import TokenError, InvalidToken
from django.conf import settings
from functools import wraps
from rest_framework.response import Response
from rest_framework import status
from rest_framework_simplejwt.authentication import JWTAuthentication
from .models import Bhagat
from django.http import JsonResponse


def get_token_from_request(request):
    """Extract token from Authorization header"""
    auth_header = request.META.get('HTTP_AUTHORIZATION', '')
    if auth_header.startswith('Bearer '):
        return auth_header.split(' ')[1]
    return None


def validate_jwt_token(token):
    """Validate a JWT token and return the user"""
    try:
        if not token:
            return None

        # Validate token
        valid_token = AccessToken(token)

        # Get user from token
        user_id = valid_token.payload.get('user_id')
        if not user_id:
            return None

        # Get user from database
        user = Bhagat.objects.filter(id=user_id).first()
        return user

    except (TokenError, InvalidToken):
        return None


def jwt_required(allowed_user_types=None):
    """

    Decorator for views that require JWT authentication

    Optional: Pass allowed_user_types as a list to restrict access to specific user types

    """
    def decorator(view_func):
        @wraps(view_func)
        def wrapped_view(request, *args, **kwargs):
            # Get token from header
            token = get_token_from_request(request)
            if not token:
                return JsonResponse({
                    "error": "No authentication token provided",
                    "status": "error"
                })

            # Validate token and get user
            user = validate_jwt_token(token)
            if not user:
                return JsonResponse({
                    "error": "Invalid or expired token",
                    "status": "error"
                })

            # Check user type if specified
            if allowed_user_types and user.user_type not in allowed_user_types:
                return JsonResponse({
                    "error": "Unauthorized access",
                    "status": "error"
                })

            # Add user to request
            request.user = user
            return view_func(request, *args, **kwargs)
        return wrapped_view
    return decorator