Skip to content

Commit 7d4885a

Browse files
committed
feat: Improved exceptions
1 parent dfc8b4b commit 7d4885a

File tree

3 files changed

+36
-4
lines changed

3 files changed

+36
-4
lines changed

app/exceptions/__init__.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
from .exceptions import (
2+
ExpiredTokenException,
3+
InvalidTokenException,
4+
NotAuthenticatedException,
5+
)
6+
7+
__all__ = [
8+
"ExpiredTokenException",
9+
"InvalidTokenException",
10+
"NotAuthenticatedException"
11+
]

app/exceptions/exceptions.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
from fastapi import HTTPException
2+
3+
4+
class NotAuthenticatedException(HTTPException):
5+
def __init__(self):
6+
super().__init__(status_code=401, code="not_authenticated")
7+
8+
9+
class ExpiredTokenException(HTTPException):
10+
def __init__(self):
11+
super().__init__(status_code=401, code="token_expired")
12+
13+
14+
class InvalidTokenException(HTTPException):
15+
def __init__(self):
16+
super().__init__(status_code=401, code="invalid_token")

app/utils/jwt_encoder.py

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,16 @@
11
from datetime import datetime, timedelta
22
from typing import Any
33

4-
from fastapi import HTTPException, Request, Response, status
4+
from fastapi import Request, Response
55
from jwt import decode, encode
66
from jwt.exceptions import ExpiredSignatureError, InvalidTokenError
77

88
from app.config import settings
9+
from app.exceptions import (
10+
ExpiredTokenException,
11+
InvalidTokenException,
12+
NotAuthenticatedException,
13+
)
914

1015

1116
async def set_auth_cookies(resp: Response, access_token: str, refresh_token: str) -> None:
@@ -57,11 +62,11 @@ def __init__(self, cookie_name: str = "access_token"):
5762
async def __call__(self, request: Request) -> dict[str, Any]:
5863
token = request.cookies.get(self.cookie_name)
5964
if not token:
60-
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Not authenticated")
65+
raise NotAuthenticatedException()
6166
try:
6267
payload = decode(token, settings.JWT_ACCESS_SECRET_KEY, algorithms=[settings.ALGORITHM])
6368
except ExpiredSignatureError as err:
64-
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Token expired") from err
69+
raise ExpiredTokenException() from err
6570
except InvalidTokenError as err:
66-
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token") from err
71+
raise InvalidTokenException() from err
6772
return payload

0 commit comments

Comments
 (0)