Skip to content

Authentication System ​

File Information ​

  • Path: app/stores/auth.ts, app/middleware/auth.global.ts, app/plugins/01.auth-init.ts
  • Purpose: Secure authentication system with HTTP-only cookie support

Overview ​

The Authentication System provides production-ready authentication with industry-best security practices. It implements HTTP-only cookie storage for JWT tokens, preventing XSS token theft, and includes automatic session management, token-based login, and SSR compatibility.

Architecture ​

System Components ​

  1. Auth Store: Centralized authentication state management (Pinia)
  2. Auth Middleware: Global route protection and authentication validation
  3. Auth Plugin: Early initialization and cookie hydration
  4. Server API Routes: Secure token management via HTTP-only cookies
  5. Redirect Middleware: Prevents authenticated users from accessing auth pages

Key Features ​

  • JWT tokens stored in HTTP-only cookies
  • Tokens cannot be accessed via document.cookie
  • XSS protection - tokens completely inaccessible to JavaScript
  • Secure flag enabled in production (HTTPS only)
  • SameSite=lax for CSRF protection

2. Server-Side Token Management ​

  • All token operations handled by server API routes
  • Token never exposed to client JavaScript
  • Automatic token injection in API requests
  • Token validation on each protected route access

3. Multiple Login Methods ​

  • Email/Password Login: Standard authentication with workspace selection
  • Token-Based Login: One-time token access for password-less login
  • Password Recovery: Forgot password and reset password flows
  • Password Generation: Generate password for new accounts

4. Automatic Session Management ​

  • Auto token refresh on page refresh
  • User data fetching when needed
  • Session persistence across page navigations
  • Automatic cleanup on logout

5. Protected Routes ​

  • Automatic redirection for unauthenticated users
  • Public routes support (shared assets, login pages)
  • Token-based route access
  • Workspace validation

File Structure ​

Core Files ​

Stores ​

  • app/stores/auth.ts - Authentication store
    • User state management
    • Login/logout actions
    • Token-based login
    • Session management
    • User data fetching

Middleware ​

  • app/middleware/auth.global.ts - Global authentication middleware

    • Runs on ALL pages
    • Server-side cookie hydration
    • Client-side authentication validation
    • Protected route enforcement
    • Automatic redirects
  • app/middleware/auth.ts - Per-route authentication middleware

    • Optional per-route authentication check
    • Custom authentication logic
  • app/middleware/redirect-if-logged-in.ts - Redirect middleware

    • Prevents authenticated users from accessing auth pages
    • Automatic redirect to dashboard
  • app/middleware/check-url.ts - URL validation middleware

    • Validates brand name in route
    • Ensures brand exists in user's accessible workspaces

Plugins ​

  • app/plugins/01.auth-init.ts - Auth initialization plugin
    • Runs early in Nuxt lifecycle (prefix 01)
    • Initial auth state hydration from cookies
    • Automatic user data fetching if token exists
    • Cookie-store synchronization

Server API Routes ​

  • server/api/auth/set-session.post.ts - Set HTTP-only auth cookie
  • server/api/auth/clear-session.post.ts - Clear HTTP-only auth cookie (logout)
  • server/api/auth/session.get.ts - Get session status (no token exposed)
  • server/api/auth/refresh-user.post.ts - Fetch user data using HTTP-only token

Composables ​

  • app/composables/api/useAuthApi.ts - Authentication API operations

    • Login/logout API calls
    • Token-based login
    • Password recovery
    • User data fetching
  • app/composables/auth/useAuth.ts - Authentication utilities

    • Login/logout functionality
    • Secure token storage
  • app/composables/auth/useCookieHelper.ts - Cookie helper utilities

Authentication Flow ​

Login Flow ​

  1. User submits credentials (email, password, workspaceId)
  2. Client calls authStore.login(email, password, workspaceId)
  3. Backend API validates credentials and returns JWT token
  4. Client calls /api/auth/set-session with token
  5. Server stores token in HTTP-only cookie (not accessible to JS)
  6. User data stored in separate non-httpOnly cookie for UI
  7. Full user object stored in localStorage for complete data
  8. User data fetched via authStore.getUser()
  9. Redirect to dashboard

Token-Based Login Flow ​

  1. User navigates to /{brand_name}/{token} route
  2. Page component calls authStore.loginWithToken(token, url)
  3. Backend API validates token and returns JWT
  4. Token stored in HTTP-only cookie
  5. User data fetched and stored
  6. Redirect to dashboard

Logout Flow ​

  1. User clicks logout
  2. Client calls authStore.logout()
  3. Server API route /api/auth/clear-session called
  4. Server removes HTTP-only cookie
  5. Client clears localStorage
  6. Client state cleared
  7. Redirect to login page

Protected Route Flow ​

  1. User navigates to protected route
  2. Global auth middleware (auth.global.ts) runs
  3. Checks if route is public → Allow access
  4. Checks if user is authenticated → Allow access
  5. If not authenticated → Redirect to login
  6. If authenticated but no user data → Fetch user data
typescript
// HTTP-Only Auth Token Cookie (set by server only)
{
  httpOnly: true,              // Cannot be accessed by JavaScript
  secure: true (in production), // HTTPS only in production
  sameSite: 'lax',             // CSRF protection
  path: '/',                   // Available site-wide
  maxAge: 60 * 60 * 24 * 7     // 7 days
}

// User Data Cookie (accessible by client for UI)
{
  httpOnly: false,             // Client needs access for UI
  secure: true (in production),
  sameSite: 'lax',
  path: '/',
  maxAge: 60 * 60 * 24 * 7
}

Hybrid Storage for Large Data ​

Cookies have a 4096 character limit. To preserve ALL user fields:

  • Cookie: Stores minimal user data (essential auth info + current workspace instance only) for SSR
  • localStorage: Stores the FULL user object (key: auth_full_user) with ALL fields from getUser()
  • localStorage: Also stores accessibleInstances and settings for backwards compatibility

Security Features ​

  1. HTTP-Only Cookies: Auth tokens stored securely
  2. XSS Protection: Tokens completely inaccessible to JavaScript
  3. Server-Side Token Management: All token operations on server
  4. HTTPS Only: Secure flag enabled in production
  5. CSRF Protection: SameSite=lax cookie attribute
  6. Auto Logout: 401 responses trigger automatic logout
  7. Token Validation: Tokens validated on each protected route access
  8. Secure WebSocket Auth: Pusher authentication proxied through server

Usage Examples ​

Login ​

typescript
const authStore = useAuthStore()

const result = await authStore.login(email, password, workspaceId)

if (result.success) {
  await authStore.getUser()
  await navigateTo(`/${brandName}`)
}

Token-Based Login ​

typescript
const authStore = useAuthStore()

const result = await authStore.loginWithToken(token, hostname)

if (result.success && authStore.user) {
  await navigateTo(`/${brandName}`)
}

Check Authentication ​

typescript
const authStore = useAuthStore()

if (authStore.isAuthenticated) {
  const user = authStore.user
  // User is logged in
}

Logout ​

typescript
const authStore = useAuthStore()

await authStore.logout() // Automatically redirects to login