58 lines
2.2 KiB
Python
58 lines
2.2 KiB
Python
from fastapi import HTTPException, status
|
|
from actions.jwt.create_token import CreateToken
|
|
from packages.v1.administrativo.schemas.usuario_schema import UsuarioAuthenticateSchema
|
|
from packages.v1.administrativo.actions.usuario.usuario_get_by_authenticate_action import (
|
|
GetByAuthenticateAction,
|
|
)
|
|
import json
|
|
from actions.security.security import Security
|
|
|
|
|
|
class AuthenticateService:
|
|
|
|
def execute(self, user_authenticate_schema: UsuarioAuthenticateSchema):
|
|
|
|
# Instância da action de autenticação
|
|
get_by_authenticate_action = GetByAuthenticateAction()
|
|
get_by_authenticate_result = get_by_authenticate_action.execute(
|
|
user_authenticate_schema
|
|
)
|
|
|
|
# Verifica se o usuário existe
|
|
if not get_by_authenticate_result:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="Usuário não encontrado ou credenciais inválidas",
|
|
)
|
|
|
|
# Verifica se a senha armazenada é um hash válido
|
|
if not Security.is_hash(get_by_authenticate_result.password):
|
|
raise HTTPException(
|
|
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
|
detail="A senha armazenada é inválida",
|
|
)
|
|
|
|
# Verifica se a senha informada confere
|
|
if not Security.verify_password(
|
|
user_authenticate_schema.password, get_by_authenticate_result.password
|
|
):
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED, detail="Senha incorreta"
|
|
)
|
|
|
|
# Verifica se o usuário está ativo
|
|
if get_by_authenticate_result.status != "A":
|
|
raise HTTPException(
|
|
status_code=status.HTTP_403_FORBIDDEN,
|
|
detail="O usuário encontra-se desativado",
|
|
)
|
|
|
|
# Gera o token de acesso
|
|
create_token = CreateToken()
|
|
jwtUser = {
|
|
"usuario_id": int(get_by_authenticate_result.usuario_id),
|
|
"nome": str(get_by_authenticate_result.nome),
|
|
"email": str(get_by_authenticate_result.email),
|
|
}
|
|
|
|
return create_token.execute("access-token", json.dumps(jwtUser))
|