/ gellary / backend / auth / json_web_token.py
swadhinbiswas bugfix · 3/11/2024
ae81d56
35 lines · 1.2 KB
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
from dataclasses import dataclass
import jwt
import os
from auth.setting import settings 
from auth.expreance import BadCredentialsException,UnableCredentialsException

@dataclass
class JsontoWebToken:
    jwt_access_token: str
    auth0_domain: str=f"{settings.AUTH0_DOMAIN}/"
    auth0_audience: str=f"{settings.AUTH0_AUDIENCE}/"
    algorithm: str=f"{settings.ALGORITHM}"
    jwt_url=f"{auth0_domain}.well-known/jwks.json"
    
    def verify_jwt(self):
        try:
          jwt_client=jwt.PyJWKClient(jwks_uri=self.jwt_url)
          jwt_signingkey=jwt_client.get_signing_key_from_jwt(self.jwt_access_token).key
          payload=jwt.decode(self.jwt_access_token, 
                             jwt_signingkey, 
                             algorithms=[self.algorithm],
                             audience=self.auth0_audience,
                             issuer=self.auth0_domain)
          
        except jwt.exceptions.PyJWKClinetError:
          raise UnableCredentialsException
        except jwt.exceptions.PyJWTError:
          raise BadCredentialsException
        except jwt.exceptions.InvalidTokenError:
          raise BadCredentialsException
        
        return payload
      
    def validate(self):
        return self.verify_jwt()