Authentication System

The authentication system is a critical security feature of the application that manages user access, session management, and authorization. It provides a comprehensive and secure authentication solution with JWT token-based authentication, password reset capabilities, and seamless integration with the application's store management system.

Architecture

Authentication Flow

graph TD
    U[User] --> L[Login Component]
    L --> UA[useDjustAuth]
    UA --> API[Auth API]
    API --> US[User Store]
    US --> C[Cookie Storage]
    API --> SDK[Djust SDK]
    SDK --> BE[Backend Services]

The authentication system is built around a centralized composable that handles all authentication-related operations. The system maintains user state through Pinia store management while securely storing authentication tokens in HTTP-only cookies for enhanced security.

Token Management

ComponentDescriptionStorage Method
Access TokenPrimary authentication tokenHTTP-only Cookie
Refresh TokenToken renewal mechanismHTTP-only Cookie
User DataUser profile and account informationPinia Store
Account ContextCurrent active accountPinia Store
Session StateAuthentication statusPinia Store

The authentication system implements a dual-token strategy with automatic token refresh capabilities. Access tokens provide short-term authentication while refresh tokens enable seamless session extension without requiring user re-authentication.

Main Features

1. Secure Authentication

sequenceDiagram
    participant U as User
    participant C as Component
    participant A as useDjustAuth
    participant S as Store
    participant API as Auth API

    U->>C: Login credentials
    C->>A: login(email, password)
    A->>API: POST /auth/login
    API->>A: JWT tokens + user data
    A->>S: Update user state
    S->>C: Authentication success
    C->>U: Redirect to dashboard

The system provides secure user authentication with comprehensive credential validation. The login process includes automatic token storage, user state management, and optional account selection for multi-account users. All authentication requests are processed through encrypted channels with proper error handling.

2. Session Management

The session management system automatically handles token lifecycle including expiration detection, refresh token rotation, and graceful logout procedures. The system maintains persistent sessions across browser sessions while ensuring security through proper token validation and automatic cleanup on logout.

3. Password Recovery

stateDiagram-v2
    [*] --> RequestReset
    RequestReset --> EmailSent: Valid email
    RequestReset --> Error: Invalid email
    EmailSent --> TokenReceived: User clicks link
    TokenReceived --> PasswordReset: Valid token
    TokenReceived --> Expired: Token expired
    PasswordReset --> [*]: Success
    Expired --> RequestReset: Request new
    Error --> RequestReset: Retry

The password recovery system provides a secure multi-step process for users to reset forgotten passwords. The system validates email addresses, generates secure reset tokens with expiration times, and ensures password reset links are single-use and time-limited.

4. Multi-Account Support

The authentication system supports users with access to multiple accounts, providing seamless account switching capabilities. Users can maintain separate sessions for different accounts while preserving their authentication state across account switches.

Key Points

Security

Security is the paramount concern of our authentication system. All authentication tokens are stored in HTTP-only cookies to prevent XSS attacks, while JWT tokens include proper expiration times and are validated on every request. The system implements automatic logout on token expiration and provides secure password reset mechanisms with time-limited tokens.

Performance

Performance optimization is achieved through intelligent token caching and validation strategies. The system minimizes API calls by validating tokens locally when possible, implements efficient refresh token rotation, and provides optimized state management through Pinia store integration.

Flexibility

The system is designed for flexibility with support for multiple authentication flows, configurable token expiration times, and extensible user data structures. The architecture supports both email-based and username-based authentication while providing hooks for additional authentication methods.

Integration

Deep integration with the application ecosystem is achieved through seamless Pinia store synchronization, automatic route protection middleware, and comprehensive error handling integration. The authentication middleware (auth.global.ts) runs on every route navigation to enforce security policies, while the authentication composable provides programmatic access to authentication functions. The system works harmoniously with other features like cart management, user preferences, and account-specific data.

Best Practices

  1. Token Security Always use the provided authentication helpers for token management. Never store tokens in localStorage or expose them to client-side JavaScript. The system automatically handles secure token storage and retrieval.

  2. Error Handling Implement comprehensive error handling for all authentication scenarios. Handle network failures, token expiration, invalid credentials, and account access issues gracefully with appropriate user feedback.

  3. Session Validation Regularly validate authentication status before performing sensitive operations. Use the ensureAuthenticated helper to verify token validity and handle automatic refresh when necessary.

  4. Logout Procedures Always call the logout function when users explicitly log out or when authentication errors occur. This ensures proper cleanup of tokens, cookies, and user state.

Documentation Structure

This authentication documentation is organized into several specialized sections:

  • functions/ - Detailed documentation for each authentication function (login, logout, etc.)
  • middleware.md - Comprehensive guide to route protection and authentication middleware
  • types.md - TypeScript interfaces and type definitions
  • errors.md - Error handling strategies and recovery mechanisms

Conclusion

The authentication system provides a robust, secure, and user-friendly foundation for application access control. It implements industry-standard security practices while maintaining excellent user experience through features like automatic token refresh, intelligent route protection, and multi-account support. The system seamlessly integrates middleware-based route protection with composable-based authentication logic to provide comprehensive security coverage across the entire application.