Attainly/backend/app/Http/Controllers/AuthController.php

84 lines
2.4 KiB
PHP

<?php
namespace App\Http\Controllers;
use App\Auth\UseCases\AuthenticateUser\AuthenticateUser;
use App\Auth\UseCases\AuthenticateUser\AuthenticateUserRequest;
use App\Auth\UseCases\CreateSession\CreateSession;
use App\Exceptions\BadRequestException;
use App\Exceptions\UnauthorizedException;
use App\Http\Middleware\AuthMiddleware;
use App\Shared\Http\RequestInput;
use App\User\User;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Cookie;
class AuthController extends Controller
{
public function __construct(
private AuthenticateUser $authenticateUser,
private CreateSession $createSession,
) {}
public function login(Request $request): JsonResponse
{
$input = new RequestInput($request);
try {
$user = $this->authenticateUser->execute(
new AuthenticateUserRequest(
email: $input->string('email'),
password: $input->string('password'),
)
);
} catch (BadRequestException $exception) {
return new JsonResponse(
['error' => $exception->getMessage()], 400
);
} catch (UnauthorizedException $exception) {
return new JsonResponse(
['error' => $exception->getMessage()], 401
);
}
$session = $this->createSession->execute($user);
$response = new JsonResponse([
'user' => $this->userPayload($user),
], 200);
return $response->withCookie(Cookie::create(
name: AuthMiddleware::COOKIE_NAME,
value: $session->getToken(),
expire: $session->getExpiresAt()->getTimestamp(),
path: '/',
domain: null,
secure: false,
httpOnly: true,
raw: false,
sameSite: Cookie::SAMESITE_LAX,
));
}
public function me(Request $request): JsonResponse
{
/** @var User $user */
$user = $request->attributes->get('user');
return new JsonResponse([
'user' => $this->userPayload($user),
]);
}
/**
* @return array{id: int, email: string}
*/
private function userPayload(User $user): array
{
return [
'id' => $user->getId(),
'email' => $user->getEmail()->value(),
];
}
}