refresh tokens 0.1.2
This commit is contained in:
+27
-7
@@ -3,6 +3,9 @@ import bcrypt
|
||||
from src.errors.http_errors.errors import Errors
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from src.models.configs_read.env import env_settings
|
||||
from uuid import uuid4
|
||||
import hashlib
|
||||
|
||||
'''Hash/Check hash'''
|
||||
class Hashes:
|
||||
|
||||
@@ -15,32 +18,49 @@ class Hashes:
|
||||
def verify_password(self, plain_password:str, hashed_password:str)->bool:
|
||||
return bcrypt.checkpw(plain_password.encode("utf-8"), hashed_password.encode("utf-8"))
|
||||
|
||||
def token_to_hash(self, token:str)->str:
|
||||
return hashlib.sha256(token.encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
'''jwt'''
|
||||
class Jwt:
|
||||
def __init__(self) -> None:
|
||||
self.error=Errors()
|
||||
|
||||
def create_token(self, data:dict)->str:
|
||||
def __init__(self) -> None:
|
||||
|
||||
self.error=Errors()
|
||||
|
||||
def create_access_token(self, data:dict)->str:
|
||||
|
||||
user_info=data.copy()
|
||||
user_info.update({"exp": datetime.now(timezone.utc)+timedelta(minutes=env_settings.ACCESS_TOKEN_EXPIRE_MINUTES)})
|
||||
user_info.update({"exp": datetime.now(timezone.utc)+timedelta(minutes=env_settings.ACCESS_TOKEN_EXPIRE_MINUTES),
|
||||
"token_type":"access"})
|
||||
|
||||
return jwt.encode(user_info, env_settings.SECRET_KEY, env_settings.ALGORITHM)
|
||||
|
||||
|
||||
def create_refresh_token(self, data:dict)->tuple[str, str]:
|
||||
|
||||
user_info=data.copy()
|
||||
jti=str(uuid4())
|
||||
user_info.update({"exp":datetime.now(timezone.utc)+timedelta(days=env_settings.REFRESH_TOKEN_EXPIRE_DAYS),
|
||||
"token_type":"refresh",
|
||||
"jti":jti
|
||||
})
|
||||
|
||||
return jwt.encode(user_info, env_settings.SECRET_KEY, env_settings.ALGORITHM), jti
|
||||
|
||||
|
||||
|
||||
def jwt_decode(self, token:str)->dict:
|
||||
|
||||
try:
|
||||
|
||||
payload=jwt.decode(token, env_settings.SECRET_KEY, algorithms=[env_settings.ALGORITHM])
|
||||
|
||||
if (payload.get("sub")) is None:
|
||||
raise self.error.credentials_error(detail="Sub block is missing")
|
||||
|
||||
except JWTError as e:
|
||||
|
||||
raise self.error.credentials_error(detail="JWTerror") from e
|
||||
|
||||
return payload
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user