Skip to content

Commit 06f3e2d

Browse files
authored
Merge pull request #39 from PythonFloripa/fix/#14-tests
fix/#14- auth endpoint
2 parents eda96ef + 3dc183b commit 06f3e2d

File tree

5 files changed

+36
-40
lines changed

5 files changed

+36
-40
lines changed

app/routers/authentication.py

Lines changed: 11 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -7,21 +7,22 @@
77
from app.services import auth
88
from app.schemas import Token, TokenPayload, Community
99
from app.services.database.models import Community as DBCommunity
10-
from services.database.orm.community import get_community_by_username
10+
from app.services.database.orm.community import get_community_by_username
1111

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

1414
def setup():
1515
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-
found_community = await get_community_by_username(
19-
username=username,
20-
session=request.app.db_session_factory
21-
)
22-
if not found_community or not auth.verify_password(password, found_community.password):
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):
2324
return None
24-
return found_community
25+
return found_community
2526

2627

2728
#### Teste
@@ -41,7 +42,7 @@ async def create_community(request: Request ):
4142
@router.post("/token", response_model=Token)
4243
async def login_for_access_token(request: Request , form_data: OAuth2PasswordRequestForm = Depends() ) :
4344
# Rota de login: valida credenciais e retorna token JWT
44-
community = await authenticate_community(form_data.username, form_data.password, request.app.db_session_factory)
45+
community = await authenticate_community( request, form_data.username, form_data.password)
4546
if not community:
4647
raise HTTPException(
4748
status_code=status.HTTP_401_UNAUTHORIZED,

app/services/auth.py

Lines changed: 22 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
from passlib.context import CryptContext
1+
#from passlib.context import CryptContext
2+
import bcrypt
23
from datetime import datetime, timedelta, timezone
34
from app.schemas import TokenPayload
45
import jwt
@@ -8,15 +9,31 @@
89
ALGORITHM = os.getenv("ALGORITHM", "HS256")
910
ACCESS_TOKEN_EXPIRE_MINUTES = int(os.getenv("ACCESS_TOKEN_EXPIRE_MINUTES", 20))
1011

11-
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
12-
1312
def verify_password(plain, hashed):
1413
# Verifica se a senha passada bate com a hash da comunidade
15-
return pwd_context.verify(plain, hashed)
14+
return bcrypt.checkpw(
15+
bytes(plain, encoding="utf-8"),
16+
hashed,
17+
)
1618

1719
def hash_password(password):
1820
# Retorna a senha em hash para salvar no banco de dados
19-
return pwd_context.hash(password)
21+
return bcrypt.hashpw(
22+
bytes(password, encoding="utf-8"),
23+
bcrypt.gensalt(),
24+
)
25+
26+
27+
28+
#pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
29+
30+
#def verify_password(plain, hashed):
31+
# # Verifica se a senha passada bate com a hash da comunidade
32+
# return pwd_context.verify(plain, hashed)
33+
#
34+
#def hash_password(password):
35+
# # Retorna a senha em hash para salvar no banco de dados
36+
# return pwd_context.hash(password)
2037

2138
def create_access_token(data: TokenPayload, expires_delta: timedelta | None = None):
2239
"""

app/services/database/orm/community.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,7 @@
66

77
async def get_community_by_username(
88
username: str,
9-
session: AsyncSession,
10-
) -> Optional[Community]:
9+
session: AsyncSession,) -> Optional[Community]:
1110
"""
1211
Busca e retorna um membro da comunidade pelo nome de usuário.
1312
Retorna None se o usuário não for encontrado.

poetry.lock

Lines changed: 1 addition & 22 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

pyproject.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,9 +17,9 @@ httpx = "^0.28.1"
1717
sqlmodel = "^0.0.24"
1818
aiosqlite = "^0.21.0"
1919
pre-commit = "^4.2.0"
20-
passlib = {extras = ["bcrypt"], version = "^1.7.4"}
2120
python-multipart = "^0.0.20"
2221
pyjwt = "^2.10.1"
22+
bcrypt = "^4.3.0"
2323

2424
[tool.poetry.group.dev.dependencies]
2525
pytest = "^8.3.2"

0 commit comments

Comments
 (0)