signupUser->execute(new SignupUserRequest( email: $input->string('email'), )); } catch (BadRequestException $exception) { return new JsonResponse( ['error' => $exception->getMessage()], 400, ); } catch (DomainException $exception) { return new JsonResponse( ['error' => $exception->getMessage()], 409, ); } return new JsonResponse(null, 201); } public function confirmEmail(Request $request): JsonResponse { $input = new RequestInput($request); try { $user = $this->confirmUserEmail->execute( new ConfirmUserEmailRequest( token: $input->string('token'), password: $input->string('password'), ), ); } catch (BadRequestException $exception) { return new JsonResponse( ['error' => $exception->getMessage()], 400, ); } catch (DomainException $exception) { return new JsonResponse( ['error' => $exception->getMessage()], 409, ); } return $this->authenticatedResponse($user); } 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 ); } return $this->authenticatedResponse($user); } public function me(Request $request): JsonResponse { /** @var User $user */ $user = $request->attributes->get('user'); return new JsonResponse([ 'user' => $this->userPayload($user), ]); } public function logout(Request $request): JsonResponse { $token = $request->cookie(AuthMiddleware::COOKIE_NAME); if (is_string($token) && $token !== '') { $this->logout->execute($token); } $response = new JsonResponse(null, 204); return $response->withCookie(Cookie::create( name: AuthMiddleware::COOKIE_NAME, value: '', expire: 1, path: '/', domain: null, secure: false, httpOnly: true, raw: false, sameSite: Cookie::SAMESITE_LAX, )); } /** * @return array{id: int, email: string} */ private function userPayload(User $user): array { return [ 'id' => $user->getId(), 'email' => $user->getEmail()->value(), ]; } private function authenticatedResponse(User $user): JsonResponse { $session = $this->createSession->execute($user); $response = new JsonResponse([ 'user' => $this->userPayload($user), ]); 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, )); } }