32 lines
1.2 KiB
Python
32 lines
1.2 KiB
Python
"""Project custom permissions"""
|
|
from rest_framework.permissions import BasePermission
|
|
from rest_framework_simplejwt.exceptions import TokenBackendError
|
|
|
|
from authorization.models import BlacklistedAccessToken
|
|
from utils.exceptions import NotValidTokenError
|
|
from utils.methods import get_token_from_cookies
|
|
|
|
|
|
class IsAuthenticatedAndTokenIsValid(BasePermission):
|
|
"""
|
|
Check if user has a valid token and authenticated
|
|
"""
|
|
|
|
def has_permission(self, request, view):
|
|
"""Check permissions by access token and default REST permission IsAuthenticated"""
|
|
user = request.user
|
|
try:
|
|
if user and user.is_authenticated:
|
|
token_bytes = get_token_from_cookies(request)
|
|
# Get access token key
|
|
token = token_bytes.decode().split(' ')[1]
|
|
# Check if user access token not expired
|
|
blacklisted = BlacklistedAccessToken.objects.by_token(token) \
|
|
.by_user(user) \
|
|
.exists()
|
|
return not blacklisted
|
|
except TokenBackendError:
|
|
raise NotValidTokenError()
|
|
else:
|
|
return False
|