Files
taskncoffee/src/services/auth.py
2025-09-20 13:55:36 +03:00

45 lines
1.7 KiB
Python

from fastapi import HTTPException
from src.core.auth_manager import AuthManager
from src.core.settings import settings
from src.schemas.auth import Token, TokenData
from src.schemas.users import User, UserAdd, UserRequestADD, UserWithHashedPass
from src.services.base import BaseService
class AuthService(BaseService):
async def registration(self, cred: UserRequestADD) -> User:
hashed_pass = AuthManager.get_password_hash(cred.password)
user_to_insert = UserAdd(
username=cred.username,
email=cred.email,
hashed_password=hashed_pass,
)
result = await self.session.user.create_one(user_to_insert.model_dump())
await self.session.commit()
return User.model_validate(result)
async def login(self, username: str, password: str):
result = await self.session.user.get_one_or_none(username=username)
if result is None:
raise HTTPException(
status_code=401,
detail="Incorrect username or password",
)
user = UserWithHashedPass.model_validate(result)
user_token = TokenData.model_validate(user.model_dump())
verify = AuthManager.verify_password(
plain_password=password, hashed_password=user.hashed_password
)
if not verify or user.is_active is False:
raise HTTPException(
status_code=401,
detail="Incorrect username or password",
)
access_token = AuthManager.create_access_token(
user_token.model_dump()
)
return Token(
access_token=access_token, token_type=settings.access_token.token_type
)