Skip to content

Commit

Permalink
Disallow disabled users to log in
Browse files Browse the repository at this point in the history
- handle login failures with exceptions
- fix type hinting signatures
- add docstring
  • Loading branch information
augusto-herrmann committed Oct 14, 2024
1 parent 32010f8 commit 9404ece
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 6 deletions.
14 changes: 10 additions & 4 deletions src/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -119,13 +119,19 @@ async def login_for_access_token(
status.HTTP_422_UNPROCESSABLE_ENTITY, detail=message
) from exception

user = await crud_auth.authenticate_user(db, form_data.username, form_data.password)
if not user:
try:
user = await crud_auth.authenticate_user(
db, form_data.username, form_data.password
)
except (
crud_auth.InvalidCredentialsError,
crud_auth.DisabledUserError,
) as exception:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Username ou password incorretos",
detail=exception.message,
headers={"WWW-Authenticate": "Bearer"},
)
) from exception
access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
access_token = crud_auth.create_access_token(
data={"sub": user.email}, expires_delta=access_token_expires
Expand Down
28 changes: 26 additions & 2 deletions src/crud_auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,14 +84,38 @@ async def get_user(
return None


async def authenticate_user(db, username: str, password: str):
async def authenticate_user(
db: DbContextManager, username: str, password: str
) -> schemas.UsersSchema:
"""Acessa o banco de dados e verifica se o usuário existe, não está
desabilitado e se as credenciais de acesso estão corretas. Caso tudo
esteja certo, retorna os detalhes do usuário.
Args:
db (DbContextManager): Context manager contendo as informações
necessárias para acesso ao banco de dados.
username (str): Nome do usuário.
password (str): Senha do usuário.
Raises:
InvalidCredentialsError: Caso o usuário não exista ou a senha
esteja incorreta.
DisabledUserError: Caso o usuário esteja desabilitado.
Returns:
schemas.UsersSchema: Detalhes do usuário presentes no banco de
dados.
"""
user = await get_user(db_session=db, email=username)

if not user:
return False

if not verify_password(password, user.password):
return False
raise InvalidCredentialsError("Username ou password incorretos")

if user.disabled:
raise DisabledUserError("Usuário desabilitado")

return user

Expand Down

0 comments on commit 9404ece

Please sign in to comment.