Access tokens 0.1.0
This commit is contained in:
@@ -0,0 +1,51 @@
|
||||
from uuid import UUID
|
||||
from .jwt import Jwt, Hashes
|
||||
from src.database.users.crud import UsersCrudActions
|
||||
from src.errors.http_errors.errors import Errors
|
||||
|
||||
from src.models.pydantic_models.model import UserOut
|
||||
class CurrentUser:
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.jwt_service=Jwt()
|
||||
self.hash=Hashes()
|
||||
self.crud_actions=UsersCrudActions()
|
||||
self.error=Errors()
|
||||
|
||||
|
||||
def get_current_user(self, token:str)->UserOut:
|
||||
|
||||
payload=self.jwt_service.jwt_decode(token)
|
||||
sub=payload.get("sub")
|
||||
print(sub)
|
||||
if sub is None:
|
||||
raise self.error.credentials_error(detail="Jwt token is incorrect")
|
||||
try:
|
||||
UUID(sub)
|
||||
except (ValueError, TypeError):
|
||||
raise self.error.credentials_error(detail="Jwt token is incorrect")
|
||||
|
||||
user=self.crud_actions.get_user_by_id(UUID(sub))
|
||||
|
||||
if user is None:
|
||||
raise self.error.not_found_error(detail="User with this email address not found")
|
||||
|
||||
return UserOut.model_validate(user)
|
||||
|
||||
|
||||
def create_token(self, form_data_email:str, form_data_password:str)->dict:
|
||||
|
||||
user=self.crud_actions.get_user_by_email(form_data_email)
|
||||
|
||||
if user is None:
|
||||
raise self.error.credentials_error(detail="Wrong credentials")
|
||||
|
||||
if not self.hash.verify_password(plain_password=form_data_password, hashed_password=user.hashed_password):
|
||||
raise self.error.credentials_error(detail="Wrong credentials")
|
||||
|
||||
if user.status is False:
|
||||
raise self.error.credentials_error(detail="This user is deactivated")
|
||||
|
||||
return {"access_token":self.jwt_service.create_token({"sub":str(user.id)}), "token_type":"bearer"}
|
||||
|
||||
auth=CurrentUser()
|
||||
Reference in New Issue
Block a user