-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
7 changed files
with
179 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,3 +1,4 @@ | ||
ALLOW_ORIGINS=* | ||
DATABASE_URL=postgres+asyncpg://user:password@host/db_name | ||
TRUSTED_HOST=localhost | ||
SECRET_KEY=PRODUCTION-SECRET-KEY |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,30 @@ | ||
from typing import Annotated | ||
|
||
from fastapi import APIRouter, Depends, status | ||
from sqlalchemy.ext.asyncio.session import AsyncSession | ||
|
||
from app.repositories.sessions import get_async_session | ||
from app.services.security import OAuth2PasswordRequestJson, UnauthorizedResponse | ||
from app.services.tokens import ( | ||
Token, | ||
process_token_auth_user, | ||
) | ||
|
||
router = APIRouter(prefix="/tokens") | ||
|
||
|
||
@router.post( | ||
"/users/auth", | ||
responses={ | ||
status.HTTP_401_UNAUTHORIZED: { | ||
"model": UnauthorizedResponse, | ||
}, | ||
}, | ||
response_model=Token, | ||
name="user_token_auth", | ||
) | ||
async def token_auth_user( | ||
form_data: Annotated[OAuth2PasswordRequestJson, Depends()], | ||
session: AsyncSession = Depends(get_async_session), | ||
) -> Token: | ||
return await process_token_auth_user(session, form_data) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
from fastapi.param_functions import Body | ||
from pydantic import BaseModel | ||
from typing_extensions import Annotated, Doc | ||
|
||
|
||
class UnauthorizedResponse(BaseModel): | ||
detail: str | ||
|
||
|
||
class OAuth2PasswordRequestJson: | ||
def __init__( | ||
self, | ||
*, | ||
username: Annotated[ | ||
str, | ||
Body(), | ||
Doc( | ||
""" | ||
`username` string. The OAuth2 spec requires the exact field name | ||
`username`. | ||
""" | ||
), | ||
], | ||
password: Annotated[ | ||
str, | ||
Body(), | ||
Doc( | ||
""" | ||
`password` string. The OAuth2 spec requires the exact field name | ||
`password". | ||
""" | ||
), | ||
], | ||
): | ||
self.username = username | ||
self.password = password |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,98 @@ | ||
from copy import deepcopy | ||
from datetime import datetime, timedelta | ||
from typing import List | ||
|
||
from fastapi import HTTPException, status | ||
from jose import exceptions, jwt | ||
from pydantic import BaseModel, ConfigDict, Field | ||
from sqlalchemy.ext.asyncio.session import AsyncSession | ||
|
||
from app.configs import settings | ||
from app.repositories.models import User as UserModel, UserDoesNotExist | ||
from app.services.hashers import hasher | ||
from app.services.security import OAuth2PasswordRequestJson | ||
|
||
DEFAULT_JWT_EXPIRATION_TIME: int = 15 * 60 | ||
|
||
|
||
def generate_jwt_signature( | ||
payload: dict, | ||
/, | ||
*, | ||
expiration_time: int = DEFAULT_JWT_EXPIRATION_TIME, | ||
algorithm: str = "HS256", | ||
) -> str: | ||
cleaned_payload: dict = deepcopy(payload) | ||
|
||
cleaned_payload.update( | ||
{ | ||
"exp": datetime.now() + timedelta(seconds=expiration_time), | ||
} | ||
) | ||
|
||
return jwt.encode(cleaned_payload, settings.secret_key, algorithm=algorithm) | ||
|
||
|
||
class SignatureErrorBase(Exception): | ||
"""Base JWT Error""" | ||
|
||
|
||
class FatalSignatureError(SignatureErrorBase): | ||
"""Fatal Signature Error""" | ||
|
||
|
||
class SignatureExpiredError(SignatureErrorBase): | ||
"""Signature Expired Error""" | ||
|
||
|
||
def decode_jwt_signature( | ||
token: str, | ||
/, | ||
*, | ||
algorithms: List[str] = None, | ||
): | ||
if algorithms is None: | ||
algorithms = ["HS256"] | ||
|
||
try: | ||
return jwt.decode(token, settings.secret_key, algorithms=algorithms) | ||
except (exceptions.JWSError, exceptions.JWSSignatureError): | ||
raise FatalSignatureError() | ||
except exceptions.ExpiredSignatureError: | ||
raise SignatureExpiredError() | ||
|
||
|
||
class Token(BaseModel): | ||
access_token: str = Field(alias="accessToken") | ||
|
||
model_config = ConfigDict( | ||
from_attributes=True, | ||
populate_by_name=True, | ||
) | ||
|
||
|
||
class TokenData(BaseModel): | ||
uuid: str | ||
|
||
|
||
async def process_token_auth_user( | ||
session: AsyncSession, | ||
data: OAuth2PasswordRequestJson, | ||
/, | ||
) -> Token: | ||
try: | ||
user: UserModel = await UserModel.get( | ||
session, | ||
data.username, | ||
field=UserModel.username, | ||
) | ||
except UserDoesNotExist: | ||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED) | ||
if not hasher.verify(data.password, user.password): | ||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED) | ||
|
||
return Token( | ||
access_token=generate_jwt_signature( | ||
TokenData(uuid=str(user.uuid)).model_dump(by_alias=True) | ||
) | ||
) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters