feat: implement JWT-based authentication system with repository, service, and middleware layers
This commit is contained in:
@@ -0,0 +1,74 @@
|
||||
<?php
|
||||
namespace WorkbloomERP\Module\Auth\Controller;
|
||||
|
||||
use Throwable;
|
||||
use InvalidArgumentException;
|
||||
use RuntimeException;
|
||||
use KrothiumAPI\Utils\HttpUtil;
|
||||
use WorkbloomERP\Module\Auth\DTO\LoginDTO;
|
||||
use WorkbloomERP\Module\Auth\Service\AuthService;
|
||||
use WorkbloomERP\Security\AuthContext;
|
||||
|
||||
class AuthController {
|
||||
private AuthService $authService;
|
||||
|
||||
public function __construct(?AuthService $authService = null) {
|
||||
$this->authService = $authService ?? new AuthService();
|
||||
}
|
||||
|
||||
/**
|
||||
* Endpoint de login da API.
|
||||
* POST /api/v1/auth/login
|
||||
*/
|
||||
public function login(): void {
|
||||
$input = HttpUtil::getRequestBody('POST');
|
||||
|
||||
if (empty($input) || !is_array($input)) {
|
||||
HttpUtil::error('Corpo da requisição inválido ou vazio.', 400);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
$dto = LoginDTO::fromArray($input);
|
||||
} catch (InvalidArgumentException $e) {
|
||||
$errors = json_decode($e->getMessage(), true) ?? ['login' => $e->getMessage()];
|
||||
HttpUtil::error('Dados inválidos para autenticação.', 422, ['validation_errors' => $errors]);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
$result = $this->authService->login($dto);
|
||||
HttpUtil::success($result, 'Autenticação realizada com sucesso.');
|
||||
} catch (RuntimeException $e) {
|
||||
$code = $e->getCode();
|
||||
$statusCode = ($code >= 400 && $code <= 499) ? $code : 401;
|
||||
HttpUtil::error($e->getMessage(), $statusCode);
|
||||
} catch (Throwable) {
|
||||
HttpUtil::error('Erro ao processar autenticação.', 500);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Endpoint de consulta do perfil do usuário autenticado.
|
||||
* GET /api/v1/auth/me
|
||||
*/
|
||||
public function me(): void {
|
||||
$userUuid = AuthContext::getUserUuid();
|
||||
|
||||
if ($userUuid === null) {
|
||||
HttpUtil::error('Usuário não autenticado.', 401);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
$profile = $this->authService->getProfile($userUuid);
|
||||
HttpUtil::success($profile, 'Perfil recuperado com sucesso.');
|
||||
} catch (RuntimeException $e) {
|
||||
$code = $e->getCode();
|
||||
$statusCode = ($code >= 400 && $code <= 499) ? $code : 404;
|
||||
HttpUtil::error($e->getMessage(), $statusCode);
|
||||
} catch (Throwable) {
|
||||
HttpUtil::error('Erro ao buscar perfil do usuário.', 500);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user