|
5 | 5 | from rest_framework_simplejwt.views import TokenRefreshView as SimpleJWTTokenRefreshView
|
6 | 6 | from django.contrib.auth import authenticate
|
7 | 7 | from db.renderer import UserRenderer
|
8 |
| -from rest_framework_simplejwt.tokens import RefreshToken |
| 8 | +from rest_framework_simplejwt.tokens import RefreshToken, AccessToken |
9 | 9 | from rest_framework_simplejwt.exceptions import TokenError
|
10 | 10 | from rest_framework.permissions import AllowAny
|
11 | 11 | from django.utils.encoding import smart_str
|
@@ -155,19 +155,24 @@ def post(self, request, uid, token, format=None):
|
155 | 155 | except ValidationError as e:
|
156 | 156 | return Response({'error': e.detail}, status=status.HTTP_400_BAD_REQUEST)
|
157 | 157 |
|
158 |
| -# Viewset class for blocking refresh tokens after logging out. |
| 158 | +# Viewset class for blocking tokens after logging out. |
159 | 159 | class SignOutEndpoint(APIView):
|
160 | 160 | def post(self, request):
|
161 | 161 | refresh_token = request.data.get('refresh_token')
|
162 |
| - if refresh_token: |
| 162 | + access_token = request.headers.get('Authorization').split(' ')[1] #We are catching access tokens from authorization header. |
| 163 | + if refresh_token: |
163 | 164 | try:
|
164 | 165 | # Connect to Redis
|
165 | 166 | redis_conn = get_redis_connection()
|
166 |
| - token = str(RefreshToken(refresh_token)) |
167 |
| - # Blacklist the token in Redis |
168 |
| - expiration_time = int(settings.SIMPLE_JWT['REFRESH_TOKEN_LIFETIME'].total_seconds()) |
169 |
| - redis_conn.set(token, 'blacklisted') |
170 |
| - redis_conn.expire(token, expiration_time) |
| 167 | + refresh_token_str = str(RefreshToken(refresh_token)) |
| 168 | + access_token_str = str(AccessToken(access_token)) |
| 169 | + # Blacklist tokens in Redis |
| 170 | + refresh_exp_time = int(settings.SIMPLE_JWT['REFRESH_TOKEN_LIFETIME'].total_seconds()) |
| 171 | + access_exp_time = int(settings.SIMPLE_JWT['ACCESS_TOKEN_LIFETIME'].total_seconds()) |
| 172 | + with redis_conn.pipeline() as pipe: |
| 173 | + pipe.set(refresh_token_str, 'blacklisted', ex=refresh_exp_time) |
| 174 | + pipe.set(access_token_str, 'blacklisted', ex=access_exp_time) |
| 175 | + pipe.execute() |
171 | 176 | return Response({'message': 'Logged out successfully'}, status=status.HTTP_200_OK)
|
172 | 177 | except Exception:
|
173 | 178 | return Response({'error': 'Please try after some time'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
|
|
0 commit comments