class AuthController extends Controller (View source)

Handles user authentication, registration, and JWT token lifecycle operations.

This controller provides endpoints for login, logout, token refresh, and user self-identification, all returning JSON-based API responses.

Traits

Trait JsonResponseTrait.

AuthorizesRequests
DispatchesJobs
ValidatesRequests

Trait JsonResponseTrait.

Provides standardized and safe error logging with UTF-8 encoding, sensitive data masking, and controlled stack traces.

Constants

private DUMMY_HASH

A static hash used to prevent timing attacks when the user does not exist.

private MAX_LOGIN_ATTEMPTS

Maximum allowed login attempts before temporary lockout.

private DECAY_SECONDS

Number of seconds before login attempt counter resets.

Methods

JsonResponse
successResponse(array $data = [])

Return a 200 OK JSON response.

JsonResponse
createdResponse(array $data = [])

Return a 201 Created JSON response.

JsonResponse
acceptedResponse()

Return a 202 Accepted JSON response (request accepted for processing).

JsonResponse
noContentResponse()

Return a 204 No Content JSON response.

JsonResponse
resetContentResponse()

Return a 205 Reset Content JSON response.

JsonResponse
badRequestResponse(array $errors)

Return a 400 Bad Request JSON response.

JsonResponse
unauthorizedResponse(string $message = 'Não autorizado.')

Return a 401 Unauthorized JSON response.

JsonResponse
forbiddenResponse(string $message = 'Acesso negado.')

Return a 403 Forbidden JSON response.

JsonResponse
notFoundResponse(string $message = 'Recurso não encontrado.')

Return a 404 Not Found JSON response.

JsonResponse
conflictResponse(array $errors)

Return a 409 Conflict JSON response.

JsonResponse
validationErrorResponse(array $errors)

Return a 422 Unprocessable Entity JSON response for validation errors.

JsonResponse
tooManyRequestsResponse(string $message = 'Muitas requisições. Tente novamente mais tarde.')

Return a 429 Too Many Requests JSON response.

JsonResponse
internalErrorResponse(Throwable $e, string $message = 'Erro interno.')

Return a 500 Internal Server Error JSON response.

void
logError(string $message, Throwable $exception, array $context = [], string|null $channel = null)

Logs an error with consistent formatting and context.

array
sanitizeSensitiveData(array $data)

Masks common sensitive fields (e.g., passwords, tokens) in the given context array.

array
encodeStringsUtf8(array $data)

Recursively converts all string values to UTF-8.

string
getLimitedTrace(Throwable $exception, int $maxLines = 10)

Returns a string representation of the exception trace, limited to the given number of lines.

JsonResponse
register(UserStoreRequest $request)

Registers the first user in the system.

JsonResponse
login(LoginRequest $request)

Authenticates a user and issues JWT access and refresh tokens via secure cookies.

JsonResponse
me()

Retrieves the currently authenticated user's data.

JsonResponse
logout()

Logs out the authenticated user by invalidating the current JWT and clearing authentication cookies.

JsonResponse
refresh()

Refreshes the JWT token to extend session validity.

Details

protected JsonResponse successResponse(array $data = [])

Return a 200 OK JSON response.

Parameters

array $data

response payload

Return Value

JsonResponse

protected JsonResponse createdResponse(array $data = [])

Return a 201 Created JSON response.

Parameters

array $data

newly created resource data

Return Value

JsonResponse

protected JsonResponse acceptedResponse()

Return a 202 Accepted JSON response (request accepted for processing).

Return Value

JsonResponse

protected JsonResponse noContentResponse()

Return a 204 No Content JSON response.

Return Value

JsonResponse

protected JsonResponse resetContentResponse()

Return a 205 Reset Content JSON response.

Return Value

JsonResponse

protected JsonResponse badRequestResponse(array $errors)

Return a 400 Bad Request JSON response.

Parameters

array $errors

validation or request errors

Return Value

JsonResponse

protected JsonResponse unauthorizedResponse(string $message = 'Não autorizado.')

Return a 401 Unauthorized JSON response.

Parameters

string $message

optional error message

Return Value

JsonResponse

protected JsonResponse forbiddenResponse(string $message = 'Acesso negado.')

Return a 403 Forbidden JSON response.

Parameters

string $message

optional error message

Return Value

JsonResponse

protected JsonResponse notFoundResponse(string $message = 'Recurso não encontrado.')

Return a 404 Not Found JSON response.

Parameters

string $message

optional error message

Return Value

JsonResponse

protected JsonResponse conflictResponse(array $errors)

Return a 409 Conflict JSON response.

Parameters

array $errors

conflict details

Return Value

JsonResponse

protected JsonResponse validationErrorResponse(array $errors)

Return a 422 Unprocessable Entity JSON response for validation errors.

Parameters

array $errors

validation error details

Return Value

JsonResponse

protected JsonResponse tooManyRequestsResponse(string $message = 'Muitas requisições. Tente novamente mais tarde.')

Return a 429 Too Many Requests JSON response.

Parameters

string $message

optional rate limit message

Return Value

JsonResponse

protected JsonResponse internalErrorResponse(Throwable $e, string $message = 'Erro interno.')

Return a 500 Internal Server Error JSON response.

Logs the exception and returns a standardized JSON error message.

Parameters

Throwable $e

the thrown exception

string $message

optional user-friendly message

Return Value

JsonResponse

protected void logError(string $message, Throwable $exception, array $context = [], string|null $channel = null)

Logs an error with consistent formatting and context.

Parameters

string $message

descriptive error message

Throwable $exception

the thrown exception

array $context

additional context to include in the log

string|null $channel

Optional log channel (e.g., 'classes').

Return Value

void

protected array sanitizeSensitiveData(array $data)

Masks common sensitive fields (e.g., passwords, tokens) in the given context array.

Parameters

array $data

Return Value

array

protected array encodeStringsUtf8(array $data)

Recursively converts all string values to UTF-8.

Parameters

array $data

Return Value

array

protected string getLimitedTrace(Throwable $exception, int $maxLines = 10)

Returns a string representation of the exception trace, limited to the given number of lines.

Parameters

Throwable $exception
int $maxLines

Return Value

string

JsonResponse register(UserStoreRequest $request)

Registers the first user in the system.

This method allows registration only if there are no users yet. It ensures that the first admin or root account is securely created.

Parameters

UserStoreRequest $request

validated data containing name, email, and password

Return Value

JsonResponse

HTTP 201 response with redirect or 403 if registration is disabled

See also

User::create

JsonResponse login(LoginRequest $request)

Authenticates a user and issues JWT access and refresh tokens via secure cookies.

Validates email and password, enforces rate limiting, and returns a JSON response with basic user information and secure cookies for access and refresh tokens.

Security features:

  • Access and refresh cookies are HttpOnly and Secure in non-local environments.
  • SameSite=Strict is used to mitigate CSRF attacks.

Parameters

LoginRequest $request

Validated login credentials

Return Value

JsonResponse

HTTP 200 response with user info and secure JWT cookies, or an error response if authentication fails or rate limit is exceeded

See also

\App\Http\Controllers\API\Auth\self::tooManyAttempts()
\App\Http\Controllers\API\Auth\self::validateCredentials()
\PHPOpenSourceSaver\JWTAuth\Facades\JWTAuth::fromUser()
\App\Http\Controllers\API\Auth\self::makeAccessCookie()
\App\Http\Controllers\API\Auth\self::makeRefreshCookie()

JsonResponse me()

Retrieves the currently authenticated user's data.

Parses the JWT token and returns the associated user's basic information.

Return Value

JsonResponse

HTTP 200 with user data or 401 if authentication fails

See also

\PHPOpenSourceSaver\JWTAuth\Facades\JWTAuth::parseToken()

JsonResponse logout()

Logs out the authenticated user by invalidating the current JWT and clearing authentication cookies.

The access and refresh cookies are removed to prevent further authenticated requests.

Return Value

JsonResponse

HTTP 200 response with cleared cookies

See also

\PHPOpenSourceSaver\JWTAuth\Facades\JWTAuth::invalidate()
cookie()->forget()

JsonResponse refresh()

Refreshes the JWT token to extend session validity.

Return Value

JsonResponse

HTTP 200 with new token cookie or 401 on failure

See also

\PHPOpenSourceSaver\JWTAuth\Facades\JWTAuth::refresh()