Skip to content

Commit

Permalink
add exceptions
Browse files Browse the repository at this point in the history
  • Loading branch information
FireFading committed Oct 16, 2023
1 parent a75348e commit c1f7d65
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 21 deletions.
36 changes: 15 additions & 21 deletions app/controllers/users.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,17 @@
from datetime import datetime, timedelta, timezone

from app.config import jwt_settings
from app.exceptions.users import (
InactiveUserException,
InsufficientCredentialsException,
UnauthorizedException,
UserExistsException,
)
from app.models.users import User as UserModel
from app.schemas.users import UserCreate as UserCreateSchema
from app.schemas.users import UserUpdate as UserUpdateSchema
from app.services.users import UsersService, users_service
from fastapi import HTTPException, status
from fastapi import HTTPException
from jose import JWTError, jwt


Expand All @@ -19,10 +25,7 @@ async def register(
) -> UserModel | HTTPException:
email = user_schema.email
if await self.users_service.get_user(email=email):
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="User with this email already exists",
)
raise UserExistsException()
user = UserModel(**user_schema.model_dump())
return await self.users_service.create(user=user)

Expand All @@ -33,11 +36,7 @@ async def authenticate_user(
) -> UserModel | HTTPException:
user = await self.users_service.authenticate_user(username=username, password=password)
if not user:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Incorrect username or password",
headers={"WWW-Authenticate": "Bearer"},
)
raise UnauthorizedException()
return user

async def update_user_info(self, user: UserModel, update_user_schema: UserUpdateSchema) -> UserModel:
Expand All @@ -50,11 +49,6 @@ async def verify_token(
token: str,
token_type: str = "access",
):
credentials_exception = HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Could not validate credentials",
headers={"WWW-Authenticate": "Bearer"},
)
try:
payload = jwt.decode(
token=token,
Expand All @@ -64,22 +58,22 @@ async def verify_token(

token_exp = payload.get("exp")
if not token_exp:
raise credentials_exception
raise InsufficientCredentialsException()

now = datetime.now(timezone.utc)
if now > datetime.fromtimestamp(token_exp, tz=timezone.utc):
raise credentials_exception
raise InsufficientCredentialsException()
username = payload.get("sub")
if not username:
raise credentials_exception
raise InsufficientCredentialsException()

except JWTError:
raise credentials_exception
raise InsufficientCredentialsException()
user = await self.users_service.get_user(username=username)
if not user:
raise credentials_exception
raise InsufficientCredentialsException()
if user.disabled:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Inactive user")
raise InactiveUserException()
return user

def create_token(self, subject: str, token_type: str = "access") -> str:
Expand Down
Empty file added app/exceptions/__init__.py
Empty file.
35 changes: 35 additions & 0 deletions app/exceptions/users.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
from fastapi import HTTPException, status


class UserExistsException(HTTPException):
def __init__(self):
super().__init__(
status_code=status.HTTP_400_BAD_REQUEST,
detail="User with this email already exists",
)


class UnauthorizedException(HTTPException):
def __init__(self):
super().__init(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Incorrect username or password",
headers={"WWW-Authenticate": "Bearer"},
)


class InsufficientCredentialsException(HTTPException):
def __init__(self):
super().__init(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Insufficient credentials",
headers={"WWW-Authenticate": "Bearer"},
)


class InactiveUserException(HTTPException):
def __init__(self):
super().__init(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Inactive user",
)

0 comments on commit c1f7d65

Please sign in to comment.