Authentication and Authorization Domain

Overview

This frontend auth domain handles three distinct browser-facing authentication paths: a lightweight guest/session issuance route, an Auth0-backed login and callback handshake, and a backend token proxy used by the rest of the app. It also centralizes session state in frontend/lib/auth.tsx, so pages can consume the same token and user.role values through useAuth().

The Auth0 flow is cookie-driven on the server and localStorage-driven on the client. The callback route creates the browser session cookies, AuthProvider restores client state from accessToken and authUser, and page components such as frontend/app/applicants/page.tsx and frontend/app/corporate-overview/page.tsx read the same authorization context to branch UI and navigation logic.

A separate Auth0 Management integration is used for registration and role lookup. That integration is also where the frontend normalizes Auth0 user creation, duplicate-email checks, and management-token acquisition before delegating to Auth0’s Management API.

Architecture Overview

flowchart TB
    subgraph BrowserAndPages [Browser and Pages]
        LoginFlow[Login and Signup]
        PostLoginPage[Post Login Redirect]
        ApplicantsPage[Applicants Page]
        CorporateOverviewPage[Corporate Overview Page]
    end

    subgraph FrontendAuthRoutes [Frontend Auth Routes]
        LoginRoute[api auth login]
        RegisterRoute[api auth register]
        TokenRoute[api auth token]
        Auth0Route[api auth auth0 dispatcher]
    end

    subgraph ClientSession [Client Session State]
        AuthProvider[AuthProvider]
        LocalStorage[LocalStorage keys]
        AuthCookie[auth cookie]
        Auth0SessionCookie[auth0_session cookie]
    end

    subgraph Auth0Management [Auth0 Management Service]
        Auth0ManagementLib[auth0-management.ts]
    end

    subgraph ExternalSystems [External Systems]
        Auth0Tenant[Auth0 tenant]
        BackendAuthAPI[Backend auth api]
    end

    LoginFlow --> LoginRoute
    LoginFlow --> RegisterRoute
    LoginFlow --> TokenRoute
    LoginFlow --> Auth0Route
    Auth0Route --> Auth0Tenant
    RegisterRoute --> Auth0ManagementLib
    Auth0ManagementLib --> Auth0Tenant
    TokenRoute --> BackendAuthAPI
    Auth0Route --> Auth0SessionCookie
    Auth0SessionCookie --> AuthProvider
    AuthProvider --> LocalStorage
    AuthProvider --> AuthCookie
    AuthProvider --> ApplicantsPage
    AuthProvider --> CorporateOverviewPage
    PostLoginPage --> ApplicantsPage

Component Structure

1. Frontend Authentication Routes

[!NOTE] frontend/app/api/auth/login/route.ts returns user.application_id, while frontend/lib/auth.tsx stores and consumes AuthUser.applicationId. Any code that moves the login response directly into AuthProvider must normalize that field first. [!NOTE] AuthProvider.logout() clears only the client cookie named auth, while frontend/app/api/auth/auth0/[auth0]/route.ts clears auth, auth0_session, and auth0_oauth_state. Client-only logout leaves the httpOnly Auth0 session cookie in place until the server-side logout route is used.

These routes live under frontend/app/api/auth/ and are responsible for issuing guest tokens, forwarding credential exchanges, and mediating Auth0 browser handoffs. They are the only auth endpoints in this section that directly return application-facing JSON or redirects.

frontend/app/api/auth/login/route.ts

This route issues a guest-style access token and a small user payload from the incoming identifier. It derives username, email, and role from the submitted identifier and sets the auth cookie with the generated token.

Request Model
Property Type Description
identifier string Optional login identifier used to derive the guest identity.
Response Model
Property Type Description
token string Generated token in the form guest-token-<timestamp>.
user.id number Timestamp used as the synthetic user identifier.
user.username string Username derived from the identifier before @.
user.email string Normalized email, or a synthesized @example.com address.
user.role string admin for the configured admin emails, otherwise applicant.
user.application_id null Always returned as null by this route.

Create Guest Session

{
    "title": "Create Guest Session",
    "description": "Issues a guest token and user payload, then writes the auth cookie",
    "method": "POST",
    "baseUrl": "<FrontendBaseUrl>",
    "endpoint": "/api/auth/login",
    "headers": [],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "json",
    "requestBody": "{\n    \"identifier\": \"[email protected]\"\n}",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Guest session created",
            "body": "{\n    \"token\": \"guest-token-1700000000000\",\n    \"user\": {\n        \"id\": 1700000000000,\n        \"username\": \"tobias\",\n        \"email\": \"[email protected]\",\n        \"role\": \"admin\",\n        \"application_id\": null\n    }\n}"
        }
    }
}

frontend/app/api/auth/register/route.ts

This route creates a new Auth0 database user after checking for an existing email address. It depends on frontend/lib/auth0-management.ts for Auth0 Management API access and only returns a user_id on success.

Request Model
Property Type Description
email string Email used for the Auth0 user lookup and creation request.
password string Password passed to Auth0 during user creation.
username string Username stored in Auth0 and used as a fallback display name.
Response Model
Property Type Description
user_id string Auth0 user identifier returned by the management API.

Register Auth0 User

{
    "title": "Register Auth0 User",
    "description": "Checks for an existing Auth0 user by email and creates a new database user when none is found",
    "method": "POST",
    "baseUrl": "<FrontendBaseUrl>",
    "endpoint": "/api/auth/register",
    "headers": [],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "json",
    "requestBody": "{\n    \"email\": \"[email protected]\",\n    \"password\": \"Str0ngP@ssw0rd!\",\n    \"username\": \"new.applicant\"\n}",
    "formData": [],
    "rawBody": "",
    "responses": {
        "201": {
            "description": "Auth0 user created",
            "body": "{\n    \"user_id\": \"auth0|665f9e3a7e0a3d6a1b123456\"\n}"
        },
        "409": {
            "description": "An account with this email already exists",
            "body": "{\n    \"error\": \"An account with this email already exists.\"\n}"
        }
    }
}

frontend/app/api/auth/token/route.ts

This route proxies credential exchange to the backend authentication service. It accepts either JSON or form-encoded input, resolves a safe backend URL, then forwards the request as application/x-www-form-urlencoded while preserving the backend status code and response body.

Request Model
Property Type Description
username string Username field used by the backend auth service.
password string Password field used by the backend auth service.
identifier string Alternate identifier accepted as a username fallback.
Response Model

This route forwards the backend body verbatim, so the response shape is whatever the backend authentication service returns.

Proxy Backend Token Exchange

{
    "title": "Proxy Backend Token Exchange",
    "description": "Forwards login credentials to the backend auth service and returns the backend response without reshaping it",
    "method": "POST",
    "baseUrl": "<FrontendBaseUrl>",
    "endpoint": "/api/auth/token",
    "headers": [],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "json",
    "requestBody": "{\n    \"username\": \"tobias\",\n    \"password\": \"P@ssw0rd123\"\n}",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Backend auth response forwarded by the proxy",
            "body": "[]"
        }
    }
}

frontend/app/api/auth/auth0/[auth0]/route.ts

This dynamic route multiplexes four Auth0 handoff behaviors under a single handler: login, callback, logout, and me. It uses AUTH0_STATE_COOKIE_NAME to protect the login handshake, writes AUTH0_SESSION_COOKIE_NAME on successful callback exchange, and clears cookies on logout.

Route Dispatcher Functions
Function Description
GET Dispatches the request to handleLogin, handleCallback, handleLogout, or handleMe based on the dynamic auth0 segment.
handleLogin Builds the Auth0 authorize URL and stores a state cookie.
handleCallback Validates state, exchanges the code for tokens, decodes the ID token, and writes the session cookies.
handleLogout Redirects to Auth0 logout when configured and clears auth cookies.
handleMe Reads and decodes the session cookie and returns the token plus user payload.
getAuth0Config Reads and normalizes Auth0 tenant credentials from environment variables.
resolveAppBaseUrl Chooses the browser return origin from Auth0 base URL settings or the request origin.
decodeJwtPayload Decodes the ID token payload without signature verification.
buildUser Maps decoded profile data into the frontend Auth0User shape and applies role tagging.
encodeSession Base64url-encodes the session payload for auth0_session.
normalizeDomain Removes protocol and trailing slash from the Auth0 domain value.
Module Constants
Constant Value Purpose
AUTH0_SCOPE openid profile email Scope requested during authorize redirect.
AUTH0_ORGANIZATION_ID Env-derived Optional organization override for authorize redirects.
Auth0 Session Model
Property Type Description
token string Auth0 access token returned by the code exchange.
user.id number Synthetic client-side identifier based on the callback timestamp.
user.username string Username selected from preferred_username, nickname, name, or email prefix.
user.email string Lowercased email from the ID token profile.
user.role string admin for configured admin emails, otherwise applicant.
user.applicationId `number \ null`

Start Auth0 Login

{
    "title": "Start Auth0 Login",
    "description": "Redirects the browser to the Auth0 authorize endpoint and stores an oauth state cookie",
    "method": "GET",
    "baseUrl": "<FrontendBaseUrl>",
    "endpoint": "/api/auth/auth0/login",
    "headers": [],
    "queryParams": [
        {
            "key": "screen_hint",
            "required": false,
            "description": "If set to signup, the authorize request includes the signup screen hint."
        },
        {
            "key": "organization",
            "required": false,
            "description": "Optional organization id override for the Auth0 authorize request."
        }
    ],
    "pathParams": [],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "302": {
            "description": "Redirects to Auth0 authorize",
            "body": "[]"
        },
        "500": {
            "description": "Auth0 configuration is missing",
            "body": "{\n    \"error\": \"Auth0 is not configured. Set AUTH0_DOMAIN, AUTH0_CLIENT_ID, and AUTH0_CLIENT_SECRET.\"\n}"
        }
    }
}

Handle Auth0 Callback

{
    "title": "Handle Auth0 Callback",
    "description": "Exchanges the Auth0 authorization code for tokens, decodes the ID token, and stores the browser session",
    "method": "GET",
    "baseUrl": "<FrontendBaseUrl>",
    "endpoint": "/api/auth/auth0/callback",
    "headers": [
        {
            "key": "Cookie",
            "value": "auth0_oauth_state=<state>",
            "required": true
        }
    ],
    "queryParams": [
        {
            "key": "code",
            "required": true,
            "description": "Authorization code returned by Auth0."
        },
        {
            "key": "state",
            "required": true,
            "description": "OAuth state value that must match the `auth0_oauth_state` cookie."
        },
        {
            "key": "error",
            "required": false,
            "description": "Auth0 error returned in a failed redirect."
        },
        {
            "key": "error_description",
            "required": false,
            "description": "Optional Auth0 error description."
        }
    ],
    "pathParams": [],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "302": {
            "description": "Redirects to login success or login error state",
            "body": "[]"
        },
        "500": {
            "description": "Auth0 configuration is missing",
            "body": "{\n    \"error\": \"Auth0 is not configured. Set AUTH0_DOMAIN, AUTH0_CLIENT_ID, and AUTH0_CLIENT_SECRET.\"\n}"
        }
    }
}

Logout Auth0 Session

{
    "title": "Logout Auth0 Session",
    "description": "Redirects to Auth0 logout when configured and clears the auth cookies",
    "method": "GET",
    "baseUrl": "<FrontendBaseUrl>",
    "endpoint": "/api/auth/auth0/logout",
    "headers": [],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "302": {
            "description": "Redirects to the Auth0 logout endpoint or back to /login",
            "body": "[]"
        }
    }
}

Fetch Auth0 Session

{
    "title": "Fetch Auth0 Session",
    "description": "Returns the decoded Auth0 session token and user payload from the session cookie",
    "method": "GET",
    "baseUrl": "<FrontendBaseUrl>",
    "endpoint": "/api/auth/auth0/me",
    "headers": [
        {
            "key": "Cookie",
            "value": "auth0_session=<base64url-session>",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Decoded session payload",
            "body": "{\n    \"token\": \"eyJhbGciOi...\",\n    \"user\": {\n        \"id\": 1700000000000,\n        \"username\": \"tobias\",\n        \"email\": \"[email protected]\",\n        \"role\": \"admin\",\n        \"applicationId\": null\n    }\n}"
        },
        "401": {
            "description": "Session cookie missing or invalid",
            "body": "{\n    \"error\": \"Invalid Auth0 session cookie.\"\n}"
        }
    }
}

frontend/app/auth/post-login/page.tsx

This page performs a hard redirect to /applicants. It does not render a post-login UI state, so the browser immediately transitions into the applicants area once the route is entered.

Exported Function
Function Description
PostLoginPage Redirects the browser to /applicants.

2. Frontend Auth Context

frontend/lib/auth.tsx is the client-side authority for session state, token persistence, and user propagation. It bridges localStorage, browser cookies, and page components through a single React context.

frontend/lib/auth.tsx

Exported Types
Type Properties
AuthUser id, username, email, role, applicationId
AuthContextType isAuthenticated, token, user, login, logout, refreshAccessToken
AuthUser Properties
Property Type Description
id number Numeric user identifier stored in client state.
username string Display username carried through the app.
email string Email address used for role checks and user identity.
role string Role string carried into page authorization logic.
applicationId `number \ null`
AuthContextType Properties
Property Type Description
isAuthenticated boolean Current client-side authentication state.
token `string \ null`
user `AuthUser \ null`
login (auth: { token: string; user: AuthUser }) => void Persists a session into localStorage and the auth cookie.
logout () => void Clears the client-side session and routes the browser to /login.
refreshAccessToken () => Promise<void> Uses the stored refresh token to attempt access-token renewal.
Module Constants
Constant Value Purpose
ACCESS_TOKEN_KEY accessToken localStorage key for the access token.
USER_DATA_KEY authUser localStorage key for the serialized user.
REFRESH_TOKEN_KEY refreshToken localStorage key for the refresh token.
Public Exports
Export Description
AuthProvider Wraps the app, restores session state, and exposes auth context to children.
useAuth Reads the AuthContextType value and throws if used outside AuthProvider.
Client Session Flow
  • AuthProvider initializes with isInitialized = false.
  • On the client, it reads accessToken and authUser from localStorage.
  • Parsed user data is normalized so role falls back to admin and applicationId falls back to null.
  • If a token exists, the provider marks the session authenticated and calls fetchCurrentUser().
  • fetchCurrentUser() currently persists the provided token together with either the stored user or a fallback guest user object.
  • persistSession() writes localStorage values and sets the auth cookie for browser-side access.
  • clearSession() removes localStorage state and expires the auth cookie.
  • refreshAccessToken() posts refresh_token to /api/auth/refresh, then re-runs fetchCurrentUser() with the returned token value.
Client State Machine
stateDiagram-v2
    [*] --> Uninitialized
    Uninitialized --> Anonymous: no token in storage
    Uninitialized --> RestoringSession: token in storage
    RestoringSession --> Authenticated: persist session
    RestoringSession --> Anonymous: restore fails and clear session
    Anonymous --> Authenticated: login
    Authenticated --> Anonymous: logout
    Authenticated --> Authenticated: refresh access token
Session Restoration Sequence
sequenceDiagram
    participant B as Browser
    participant AP as AuthProvider
    participant LS as LocalStorage
    participant P as Page Consumer

    B->>AP: mount
    AP->>LS: read accessToken and authUser
    LS-->>AP: stored values
    AP->>AP: normalize user and set state
    AP->>AP: fetchCurrentUser
    AP->>LS: write token and user
    AP-->>P: provide token and user

3. Auth0 Management Service

[!NOTE] fetchCurrentUser() does not fetch a backend user profile. It only reuses the token and either the restored user or a fallback guest user object before calling persistSession() again.

frontend/lib/auth0-management.ts wraps the Auth0 Management API used during registration and role lookup. It obtains a client-credentials token on demand, then reuses that token for user and role requests.

frontend/lib/auth0-management.ts

Type
Type Description
Auth0ConfigurationError Custom Error used when management credentials are incomplete.
Module Constants
Constant Source Purpose
AUTH0_DOMAIN AUTH0_DOMAIN or AUTH0_ISSUER_BASE_URL Normalized tenant domain used for management requests.
AUTH0_MANAGEMENT_AUDIENCE AUTH0_MANAGEMENT_AUDIENCE or derived from domain Audience used when requesting the management token.
AUTH0_MANAGEMENT_CLIENT_ID AUTH0_MANAGEMENT_CLIENT_ID Client ID for the management token request.
AUTH0_MANAGEMENT_CLIENT_SECRET AUTH0_MANAGEMENT_CLIENT_SECRET Client secret for the management token request.
Public Functions
Method Description
findAuth0UserByEmail Looks up an Auth0 user by normalized email address.
createAuth0User Creates a database connection user in Auth0.
getAuth0UserRoles Fetches the Auth0 roles for a user and returns the normalized role names.
Internal Flow
  • assertManagementConfig() throws Auth0ConfigurationError if any required management env var is missing.
  • getManagementAccessToken() posts grant_type=client_credentials to https://<AUTH0_DOMAIN>/oauth/token.
  • auth0Fetch() attaches Authorization: Bearer <token> and Content-Type: application/json to each management API request.
  • The helper parses JSON error bodies when available and turns them into thrown Error instances.
Auth0 Management Sequence
sequenceDiagram
    participant R as Register Route
    participant M as auth0-management.ts
    participant T as Auth0 Token Endpoint
    participant A as Auth0 Management API

    R->>M: findAuth0UserByEmail or createAuth0User
    M->>T: POST oauth token client credentials
    T-->>M: access token
    M->>A: management request with bearer token
    A-->>M: user or role data
    M-->>R: normalized result

Auth0 Management Token

{
    "title": "Request Auth0 Management Token",
    "description": "Obtains a client credentials token for the Auth0 Management API",
    "method": "POST",
    "baseUrl": "<Auth0TenantBaseUrl>",
    "endpoint": "/oauth/token",
    "headers": [
        {
            "key": "Content-Type",
            "value": "application/json",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "json",
    "requestBody": "{\n    \"client_id\": \"mgmt_client_id\",\n    \"client_secret\": \"mgmt_client_secret\",\n    \"audience\": \"https://dev-tenant.us.auth0.com/api/v2/\",\n    \"grant_type\": \"client_credentials\"\n}",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Management token issued",
            "body": "{\n    \"access_token\": \"eyJhbGciOi...\",\n    \"token_type\": \"Bearer\",\n    \"expires_in\": 86400\n}"
        }
    }
}

Find Auth0 User by Email

{
    "title": "Find Auth0 User by Email",
    "description": "Looks up Auth0 users by normalized email address for duplicate-account detection",
    "method": "GET",
    "baseUrl": "<Auth0TenantBaseUrl>",
    "endpoint": "/api/v2/users-by-email",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <management_access_token>",
            "required": true
        },
        {
            "key": "Content-Type",
            "value": "application/json",
            "required": true
        }
    ],
    "queryParams": [
        {
            "key": "email",
            "required": true,
            "description": "Lowercased email address encoded into the query string."
        }
    ],
    "pathParams": [],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Matching Auth0 users",
            "body": "[\n    {\n        \"user_id\": \"auth0|665f9e3a7e0a3d6a1b123456\"\n    }\n]"
        }
    }
}

Create Auth0 User

{
    "title": "Create Auth0 User",
    "description": "Creates a new database connection user in Auth0",
    "method": "POST",
    "baseUrl": "<Auth0TenantBaseUrl>",
    "endpoint": "/api/v2/users",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <management_access_token>",
            "required": true
        },
        {
            "key": "Content-Type",
            "value": "application/json",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "json",
    "requestBody": "{\n    \"connection\": \"Username-Password-Authentication\",\n    \"email\": \"[email protected]\",\n    \"password\": \"Str0ngP@ssw0rd!\",\n    \"username\": \"new.applicant\",\n    \"name\": \"New Applicant\",\n    \"given_name\": \"New\",\n    \"family_name\": \"Applicant\",\n    \"verify_email\": false,\n    \"email_verified\": true\n}",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Auth0 user created",
            "body": "{\n    \"user_id\": \"auth0|665f9e3a7e0a3d6a1b123456\"\n}"
        }
    }
}

Get Auth0 User Roles

{
    "title": "Get Auth0 User Roles",
    "description": "Returns the normalized role names assigned to a user",
    "method": "GET",
    "baseUrl": "<Auth0TenantBaseUrl>",
    "endpoint": "/api/v2/users/{userId}/roles",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <management_access_token>",
            "required": true
        },
        {
            "key": "Content-Type",
            "value": "application/json",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [
        {
            "key": "userId",
            "required": true,
            "description": "Auth0 user identifier encoded into the path."
        }
    ],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Role assignments",
            "body": "[\n    {\n        \"name\": \"admin\"\n    }\n]"
        }
    }
}

Auth0 Authorize Redirect

{
    "title": "Auth0 Authorize Redirect",
    "description": "Browser redirect target used by the frontend login route",
    "method": "GET",
    "baseUrl": "<Auth0TenantBaseUrl>",
    "endpoint": "/authorize",
    "headers": [],
    "queryParams": [
        {
            "key": "response_type",
            "required": true,
            "description": "Always set to code."
        },
        {
            "key": "client_id",
            "required": true,
            "description": "Auth0 application client id."
        },
        {
            "key": "redirect_uri",
            "required": true,
            "description": "Frontend callback URL ending in /api/auth/auth0/callback."
        },
        {
            "key": "scope",
            "required": true,
            "description": "Always set to openid profile email."
        },
        {
            "key": "state",
            "required": true,
            "description": "Random state value mirrored in the auth0_oauth_state cookie."
        },
        {
            "key": "screen_hint",
            "required": false,
            "description": "Included only when the frontend request asks for signup."
        },
        {
            "key": "organization",
            "required": false,
            "description": "Optional organization id used for organization-aware login."
        }
    ],
    "pathParams": [],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "302": {
            "description": "Redirects into the Auth0 hosted login or signup screen",
            "body": "[]"
        }
    }
}

Auth0 Logout Redirect

{
    "title": "Auth0 Logout Redirect",
    "description": "Browser redirect target used by the frontend logout route",
    "method": "GET",
    "baseUrl": "<Auth0TenantBaseUrl>",
    "endpoint": "/v2/logout",
    "headers": [],
    "queryParams": [
        {
            "key": "client_id",
            "required": true,
            "description": "Auth0 application client id."
        },
        {
            "key": "returnTo",
            "required": true,
            "description": "Frontend login URL used after logout."
        }
    ],
    "pathParams": [],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "302": {
            "description": "Redirects back to the frontend login page",
            "body": "[]"
        }
    }
}

4. Session Constants and Role Propagation

frontend/lib/auth-constants.ts

[!NOTE] createAuth0User() sends verify_email: false and email_verified: true in the same Auth0 request body. The created account is treated as verified immediately.

This module centralizes the shared cookie names and session lifetime used by the frontend auth routes. The same names are read by the Auth0 callback route, the logout route, the session reader, and the browser-side auth context.

Constant Value Used By
AUTH0_SESSION_COOKIE_NAME auth0_session Auth0 callback, Auth0 session reader, Auth0 logout
AUTH0_STATE_COOKIE_NAME auth0_oauth_state Auth0 login and callback
AUTH_COOKIE_NAME auth Guest login, Auth0 callback, AuthProvider, logout
AUTH_TOKEN_TTL_SECONDS 60 * 60 Cookie lifetimes on server-side auth routes

Authorization Context Consumers

The authenticated role travels through AuthContextType.user.role and is then consumed by page-level logic.

File Observed Consumption
frontend/app/applicants/page.tsx Imports useAuth and isReviewerRole to branch reviewer-facing behavior from the current role.
frontend/app/corporate-overview/page.tsx Imports useAuth so dashboard-style data views can read the current token and user context.
frontend/app/auth/post-login/page.tsx Redirects immediately into /applicants after a login handoff.

frontend/lib/roles.ts

The role helper module is consumed by frontend/app/applicants/page.tsx through isReviewerRole. That page uses the role string from AuthUser to branch reviewer-oriented behavior, so the role value produced by login, buildUser, and AuthProvider is the input to that page-level authorization logic.

frontend/lib/profile-locale.ts

The locale helper module is consumed by frontend/app/corporate-overview/page.tsx through normalizeProfileLocale, persistProfileLocale, and readProfileLocaleFromStorage. That page combines the authenticated user context with browser-stored locale preferences to keep the dashboard experience aligned with the user profile.

Feature Flows

1. Auth0 Login and Callback Handoff

sequenceDiagram
    participant U as User
    participant B as Browser
    participant L as Auth0 Login Route
    participant A as Auth0 Tenant
    participant C as Auth0 Callback Route
    participant P as AuthProvider
    participant AP as Applicants Page

    U->>B: click sign in
    B->>L: GET /api/auth/auth0/login
    L->>A: redirect to authorize
    A-->>B: hosted login or signup
    B->>C: GET /api/auth/auth0/callback with code and state
    C->>A: POST oauth token exchange
    A-->>C: access token and id token
    C->>C: decode ID token and build user
    C-->>B: redirect with auth cookies set
    B->>P: mount application shell
    P->>P: restore token and user state
    P-->>AP: provide token and role context

2. Auth0 Registration Flow

sequenceDiagram
    participant U as User
    participant R as Register Route
    participant M as auth0-management.ts
    participant T as Auth0 Token Endpoint
    participant A as Auth0 Management API

    U->>R: POST email password username
    R->>M: findAuth0UserByEmail
    M->>T: request management token
    T-->>M: access token
    M->>A: GET users by email
    A-->>M: duplicate or empty list
    alt no existing user
        R->>M: createAuth0User
        M->>T: request management token
        T-->>M: access token
        M->>A: POST new user
        A-->>M: user_id
        M-->>R: user_id
        R-->>U: 201 created
    else existing user
        R-->>U: 409 conflict
    end

3. Client Session Restore and Logout

sequenceDiagram
    participant B as Browser
    participant P as AuthProvider
    participant L as LocalStorage
    participant C as Cookie Store
    participant V as View

    B->>P: mount
    P->>L: read accessToken and authUser
    P->>P: normalize stored user
    P->>P: set isAuthenticated true if token exists
    P->>C: write auth cookie during persistSession
    P-->>V: provide auth context
    B->>P: logout
    P->>L: remove accessToken authUser refreshToken
    P->>C: clear auth cookie
    P-->>B: push /login

State Management

Auth Provider State

State Field Type Description
isAuthenticated boolean Tracks whether a token is present in client state.
isInitialized boolean Prevents rendering until browser session restoration finishes.
token `string \ null`
user `AuthUser \ null`

Browser Storage

Storage Key Type Used For
accessToken localStorage Stores the current access token.
authUser localStorage Stores the serialized AuthUser.
refreshToken localStorage Used only by refreshAccessToken().
auth cookie Browser-visible auth token used by client routes.
auth0_session httpOnly cookie Server-readable encoded Auth0 session.
auth0_oauth_state httpOnly cookie OAuth state guard for the Auth0 callback.

State Transitions

  • AuthProvider starts uninitialized and returns null until initialization completes.
  • When localStorage contains a token, the provider marks the session authenticated before calling fetchCurrentUser().
  • login() persists the supplied token and user into localStorage and the auth cookie.
  • logout() clears the client session and navigates to /login.
  • The Auth0 callback path stores the server-readable session cookies independently of client localStorage.

Integration Points

  • frontend/app/applicants/page.tsx reads useAuth() and uses role predicates from frontend/lib/roles.ts.
  • frontend/app/corporate-overview/page.tsx reads useAuth() and pairs it with locale persistence helpers from frontend/lib/profile-locale.ts.
  • frontend/app/auth/post-login/page.tsx sends the browser into the applicants flow immediately after login handoff.
  • frontend/app/api/auth/token/route.ts delegates credential verification to the backend authentication service.
  • frontend/lib/auth0-management.ts delegates user creation and role lookup to Auth0 Management API endpoints.

Error Handling

File or Route Error Condition Behavior
frontend/app/api/auth/login/route.ts Missing or empty identifier Falls back to guest.
frontend/app/api/auth/register/route.ts Invalid JSON body Returns 400 with Invalid JSON body.
frontend/app/api/auth/register/route.ts Missing email, password, or username Returns 400.
frontend/app/api/auth/register/route.ts Existing Auth0 user Returns 409.
frontend/app/api/auth/register/route.ts Missing Auth0 management config Returns 500.
frontend/app/api/auth/register/route.ts Other Auth0 errors Returns 502.
frontend/app/api/auth/token/route.ts Missing parsed credentials Returns 400.
frontend/app/api/auth/token/route.ts No safe backend URL Returns 503.
frontend/app/api/auth/token/route.ts Network failure to backend Returns 503.
frontend/app/api/auth/auth0/[auth0]/route.ts Missing Auth0 config Returns 500.
frontend/app/api/auth/auth0/[auth0]/route.ts Auth0 error query params present Redirects to /login with auth0_error details and clears the state cookie.
frontend/app/api/auth/auth0/[auth0]/route.ts Invalid state on callback Redirects to /login?auth0_error=invalid_state.
frontend/app/api/auth/auth0/[auth0]/route.ts Token exchange fails Redirects to /login?auth0_error=token_exchange_failed.
frontend/app/api/auth/auth0/[auth0]/route.ts Missing tokens Redirects to /login?auth0_error=missing_tokens.
frontend/app/api/auth/auth0/[auth0]/route.ts Invalid ID token payload Redirects to /login?auth0_error=invalid_id_token.
frontend/app/api/auth/auth0/[auth0]/route.ts Invalid or missing session cookie on me Returns 401.
frontend/lib/auth.tsx useAuth() called outside provider Throws useAuth must be used within an AuthProvider.
frontend/lib/auth0-management.ts Missing management env vars Throws Auth0ConfigurationError.

Dependencies

  • next/server and next/navigation route handlers for redirects and JSON responses.
  • Browser localStorage and document.cookie for client-side auth persistence.
  • Auth0 tenant endpoints for authorize, logout, user creation, role lookup, and management token acquisition.
  • The backend auth service reached through frontend/app/api/auth/token/route.ts.
  • Page consumers that read useAuth() and role helpers in frontend/app/applicants/page.tsx and frontend/app/corporate-overview/page.tsx.
  • Shared auth constants from frontend/lib/auth-constants.ts.

Testing Considerations

  • Verify that /api/auth/auth0/login sets auth0_oauth_state and redirects with the expected authorize parameters.
  • Verify that /api/auth/auth0/callback rejects mismatched state values and accepts the state cookie path after a successful exchange.
  • Verify that /api/auth/auth0/me returns 401 for missing or malformed auth0_session.
  • Verify that frontend/lib/auth.tsx restores state from localStorage, normalizes missing role to admin, and keeps applicationId as null when absent.
  • Verify that frontend/app/api/auth/register/route.ts returns 409 when Auth0 already has the email.
  • Verify that frontend/app/api/auth/token/route.ts forwards backend responses unchanged and preserves response content-type.
  • Verify that frontend/app/auth/post-login/page.tsx always redirects to /applicants.

Key Classes Reference

Class Responsibility
route.ts Issues guest sessions through /api/auth/login.
route.ts Registers new Auth0 users through /api/auth/register.
route.ts Proxies backend login token exchange through /api/auth/token.
route.ts Handles Auth0 login, callback, logout, and session reads under /api/auth/auth0/[auth0].
page.tsx Redirects post-login traffic to /applicants.
auth.tsx Provides client auth state, localStorage persistence, and the useAuth() hook.
auth0-management.ts Wraps Auth0 Management API token acquisition, user lookup, user creation, and role retrieval.
auth-constants.ts Centralizes shared cookie names and token lifetime.
roles.ts Supplies role helpers consumed by page-level authorization checks.
profile-locale.ts Supplies persisted locale helpers consumed by dashboard-style pages.