Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 11 additions & 10 deletions app/routers/authentication.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,21 +7,22 @@
from app.services import auth
from app.schemas import Token, TokenPayload, Community
from app.services.database.models import Community as DBCommunity
from services.database.orm.community import get_community_by_username
from app.services.database.orm.community import get_community_by_username

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/authentication/token")

def setup():
router = APIRouter(prefix='/authentication', tags=['authentication'])
async def authenticate_community(request: Request , username: str, password: str):
# Valida se o usuário existe e se a senha está correta
found_community = await get_community_by_username(
username=username,
session=request.app.db_session_factory
)
if not found_community or not auth.verify_password(password, found_community.password):
async def authenticate_community( request: Request , username: str, password: str):
# Valida se o usuário existe e se a senha está correta
session: AsyncSession = request.app.db_session_factory
found_community = await get_community_by_username(
username=username,
session= session
)
if not found_community or not auth.verify_password(password, found_community.password):
return None
return found_community
return found_community


#### Teste
Expand All @@ -41,7 +42,7 @@ async def create_community(request: Request ):
@router.post("/token", response_model=Token)
async def login_for_access_token(request: Request , form_data: OAuth2PasswordRequestForm = Depends() ) :
# Rota de login: valida credenciais e retorna token JWT
community = await authenticate_community(form_data.username, form_data.password, request.app.db_session_factory)
community = await authenticate_community( request, form_data.username, form_data.password)
if not community:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
Expand Down
27 changes: 22 additions & 5 deletions app/services/auth.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from passlib.context import CryptContext
#from passlib.context import CryptContext
import bcrypt
from datetime import datetime, timedelta, timezone
from app.schemas import TokenPayload
import jwt
Expand All @@ -8,15 +9,31 @@
ALGORITHM = os.getenv("ALGORITHM", "HS256")
ACCESS_TOKEN_EXPIRE_MINUTES = int(os.getenv("ACCESS_TOKEN_EXPIRE_MINUTES", 20))

pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")

def verify_password(plain, hashed):
# Verifica se a senha passada bate com a hash da comunidade
return pwd_context.verify(plain, hashed)
return bcrypt.checkpw(
bytes(plain, encoding="utf-8"),
hashed,
)

def hash_password(password):
# Retorna a senha em hash para salvar no banco de dados
return pwd_context.hash(password)
return bcrypt.hashpw(
bytes(password, encoding="utf-8"),
bcrypt.gensalt(),
)



#pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")

#def verify_password(plain, hashed):
# # Verifica se a senha passada bate com a hash da comunidade
# return pwd_context.verify(plain, hashed)
#
#def hash_password(password):
# # Retorna a senha em hash para salvar no banco de dados
# return pwd_context.hash(password)

def create_access_token(data: TokenPayload, expires_delta: timedelta | None = None):
"""
Expand Down
3 changes: 1 addition & 2 deletions app/services/database/orm/community.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,7 @@

async def get_community_by_username(
username: str,
session: AsyncSession,
) -> Optional[Community]:
session: AsyncSession,) -> Optional[Community]:
"""
Busca e retorna um membro da comunidade pelo nome de usuário.
Retorna None se o usuário não for encontrado.
Expand Down
23 changes: 1 addition & 22 deletions poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,9 @@ httpx = "^0.28.1"
sqlmodel = "^0.0.24"
aiosqlite = "^0.21.0"
pre-commit = "^4.2.0"
passlib = {extras = ["bcrypt"], version = "^1.7.4"}
python-multipart = "^0.0.20"
pyjwt = "^2.10.1"
bcrypt = "^4.3.0"

[tool.poetry.group.dev.dependencies]
pytest = "^8.3.2"
Expand Down