|
1 |
| -from fastapi import APIRouter, Depends, HTTPException, status, Request |
2 |
| -from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm |
3 |
| -from sqlmodel.ext.asyncio.session import AsyncSession |
| 1 | +from typing import Annotated |
| 2 | + |
4 | 3 | import jwt
|
| 4 | +from fastapi import APIRouter, Depends, HTTPException, Request, status |
| 5 | +from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm |
5 | 6 | from jwt.exceptions import InvalidTokenError
|
| 7 | +from sqlmodel.ext.asyncio.session import AsyncSession |
6 | 8 |
|
| 9 | +from app.schemas import Community, Token, TokenPayload |
7 | 10 | from app.services import auth
|
8 |
| -from app.schemas import Token, TokenPayload, Community |
9 | 11 | from app.services.database.models import Community as DBCommunity
|
10 | 12 | from app.services.database.orm.community import get_community_by_username
|
11 | 13 |
|
12 | 14 | oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/authentication/token")
|
13 | 15 |
|
| 16 | + |
14 | 17 | def setup():
|
15 |
| - router = APIRouter(prefix='/authentication', tags=['authentication']) |
16 |
| - async def authenticate_community( request: Request , username: str, password: str): |
17 |
| - # Valida se o usuário existe e se a senha está correta |
18 |
| - session: AsyncSession = request.app.db_session_factory |
19 |
| - found_community = await get_community_by_username( |
20 |
| - username=username, |
21 |
| - session= session |
22 |
| - ) |
23 |
| - if not found_community or not auth.verify_password(password, found_community.password): |
| 18 | + router = APIRouter(prefix="/authentication", tags=["authentication"]) |
| 19 | + |
| 20 | + async def authenticate_community( |
| 21 | + request: Request, username: str, password: str |
| 22 | + ): |
| 23 | + # Valida se o usuário existe e se a senha está correta |
| 24 | + session: AsyncSession = request.app.db_session_factory |
| 25 | + found_community = await get_community_by_username( |
| 26 | + username=username, session=session |
| 27 | + ) |
| 28 | + if not found_community or not auth.verify_password( |
| 29 | + password, found_community.password |
| 30 | + ): |
24 | 31 | return None
|
25 |
| - return found_community |
| 32 | + return found_community |
26 | 33 |
|
| 34 | + async def get_current_community( |
| 35 | + request: Request, |
| 36 | + token: Annotated[str, Depends(oauth2_scheme)], |
| 37 | + ) -> DBCommunity: |
| 38 | + credentials_exception = HTTPException( |
| 39 | + status_code=status.HTTP_401_UNAUTHORIZED, |
| 40 | + detail="Could not validate credentials", |
| 41 | + headers={"WWW-Authenticate": "Bearer"}, |
| 42 | + ) |
27 | 43 |
|
28 |
| - #### Teste |
| 44 | + try: |
| 45 | + payload = jwt.decode( |
| 46 | + token, auth.SECRET_KEY, algorithms=[auth.ALGORITHM] |
| 47 | + ) |
| 48 | + username = payload.get("sub") |
| 49 | + if username is None: |
| 50 | + raise credentials_exception |
| 51 | + token_data = TokenPayload(username=username) |
| 52 | + except InvalidTokenError: |
| 53 | + raise credentials_exception |
| 54 | + session: AsyncSession = request.app.db_session_factory |
| 55 | + community = await get_community_by_username( |
| 56 | + session=session, username=token_data.username |
| 57 | + ) |
| 58 | + if community is None: |
| 59 | + raise credentials_exception |
| 60 | + |
| 61 | + return community |
| 62 | + |
| 63 | + async def get_current_active_community( |
| 64 | + current_user: Annotated[DBCommunity, Depends(get_current_community)], |
| 65 | + ) -> DBCommunity: |
| 66 | + # A função simplesmente retorna o usuário. |
| 67 | + # Pode ser estendido futuramente para verificar um status "ativo". |
| 68 | + return current_user |
| 69 | + |
| 70 | + # Teste |
29 | 71 |
|
30 | 72 | @router.post("/create_commumity")
|
31 |
| - async def create_community(request: Request ): |
| 73 | + async def create_community(request: Request): |
32 | 74 | password = "123Asd!@#"
|
33 |
| - hashed_password=auth.hash_password(password) |
34 |
| - community = DBCommunity( username="username", email="[email protected]", password=hashed_password) |
| 75 | + hashed_password = auth.hash_password(password) |
| 76 | + community = DBCommunity( |
| 77 | + username="username", |
| 78 | + |
| 79 | + password=hashed_password, |
| 80 | + ) |
35 | 81 | session: AsyncSession = request.app.db_session_factory
|
36 | 82 | session.add(community)
|
37 | 83 | await session.commit()
|
38 | 84 | await session.refresh(community)
|
39 |
| - return {'msg':'succes? '} |
40 |
| - #### Teste |
| 85 | + return {"msg": "succes? "} |
| 86 | + |
| 87 | + # Teste |
41 | 88 |
|
42 | 89 | @router.post("/token", response_model=Token)
|
43 |
| - async def login_for_access_token(request: Request , form_data: OAuth2PasswordRequestForm = Depends() ) : |
| 90 | + async def login_for_access_token( |
| 91 | + request: Request, form_data: OAuth2PasswordRequestForm = Depends() |
| 92 | + ): |
44 | 93 | # Rota de login: valida credenciais e retorna token JWT
|
45 |
| - community = await authenticate_community( request, form_data.username, form_data.password) |
| 94 | + community = await authenticate_community( |
| 95 | + request, form_data.username, form_data.password |
| 96 | + ) |
46 | 97 | if not community:
|
47 | 98 | raise HTTPException(
|
48 | 99 | status_code=status.HTTP_401_UNAUTHORIZED,
|
49 |
| - detail="Credenciais inválidas" |
| 100 | + detail="Credenciais inválidas", |
50 | 101 | )
|
51 | 102 | payload = TokenPayload(username=community.username)
|
52 | 103 | token, expires_in = auth.create_access_token(data=payload)
|
53 | 104 | return {
|
54 | 105 | "access_token": token,
|
55 | 106 | "token_type": "Bearer",
|
56 |
| - "expires_in": expires_in |
| 107 | + "expires_in": expires_in, |
57 | 108 | }
|
58 |
| - return router # Retorna o router configurado com as rotas de autenticação |
| 109 | + |
| 110 | + @router.get("/me", response_model=Community) |
| 111 | + async def read_community_me( |
| 112 | + current_community: Annotated[ |
| 113 | + DBCommunity, Depends(get_current_active_community) |
| 114 | + ], |
| 115 | + ): |
| 116 | + # Rota para obter informações do usuário autenticado |
| 117 | + return current_community |
| 118 | + |
| 119 | + return router # Retorna o router configurado com as rotas de autenticação |
0 commit comments