# Frontend Authentication Architecture - ECM Platform

## Status: ✅ COMPLETE

Authentication architecture has been successfully implemented for the ECM MT5 Investment Platform frontend.

## Overview
Production-grade authentication system using Laravel Sanctum with role-based access control (RBAC).

## Architecture Components

### 1. Auth Store (`src/stores/auth.js`)
**Purpose:** Centralized authentication state management using Pinia.

**State:**
- `user` - Current user data
- `token` - Sanctum authentication token
- `role` - User role (investor/admin)
- `tokenExpiresAt` - Token expiration timestamp

**Getters:**
- `isAuthenticated` - Checks if user is authenticated and token is valid
- `isInvestor` - Checks if user has investor role
- `isAdmin` - Checks if user has admin role
- `hasRole(role)` - Checks if user has specific role

**Actions:**
- `login(userData, token, role, expiresIn)` - Authenticate user
- `logout()` - Clear authentication state
- `refreshToken(newToken, expiresIn)` - Update token
- `checkSession()` - Validate session
- `getSessionInfo()` - Get current session info

**Features:**
- Automatic token expiration checking
- Session persistence via localStorage
- Automatic logout on expired tokens

---

### 2. Auth Middleware (`src/middleware/auth.js`)
**Purpose:** Route guards for protecting routes based on authentication and roles.

**Guards:**
- `authGuard` - Protects routes requiring authentication
- `guestGuard` - Protects routes for non-authenticated users
- `roleGuard(requiredRole)` - Protects routes requiring specific role
- `investorGuard` - Protects investor-only routes
- `adminGuard` - Protects admin-only routes

**Usage in Router:**
```javascript
{
  path: '/investor/dashboard',
  beforeEnter: investorGuard
}
```

**Features:**
- Redirect to login with return URL
- Session expiration detection
- Role-based access control
- Automatic redirection based on user role

---

### 3. Auth Composable (`src/composables/useAuth.js`)
**Purpose:** Reusable authentication logic for components.

**Methods:**
- `login(credentials)` - Handle login flow
- `register(userData)` - Handle registration flow
- `logout()` - Handle logout flow
- `refreshToken()` - Refresh authentication token
- `checkSession()` - Check session validity
- `hasRole(requiredRole)` - Check user role
- `canAccess(route)` - Check route access

**Usage in Components:**
```javascript
const { login, logout, isAuthenticated, isInvestor } = useAuth()
```

**Features:**
- Automatic redirect after login
- Error handling
- Token refresh integration
- Session validation

---

### 4. Axios Interceptor (`src/services/api.js`)
**Purpose:** Automatic token injection and refresh for API requests.

**Request Interceptor:**
- Adds Authorization header with Bearer token
- Adds timestamp for cache busting

**Response Interceptor:**
- Handles 401 Unauthorized (token refresh attempt)
- Handles 403 Forbidden
- Handles 419 Session Expired
- Handles 429 Rate Limit
- Handles 500 Server Errors

**Token Refresh Flow:**
1. Detect 401 response
2. Attempt token refresh via API
3. Retry original request with new token
4. If refresh fails, logout user

**Features:**
- Automatic token injection
- Token refresh on 401
- User-friendly error notifications
- Automatic logout on critical errors

---

### 5. Auth Utilities (`src/utils/auth.js`)
**Purpose:** Helper functions for authentication operations.

**Functions:**
- `isTokenExpired(expiresAt)` - Check token expiration
- `getToken()` - Get token from localStorage
- `getRole()` - Get role from localStorage
- `setToken(token)` - Set token in localStorage
- `setRole(role)` - Set role in localStorage
- `clearAuthData()` - Clear all auth data
- `hasRole(requiredRole)` - Check user role
- `getAuthHeaders()` - Get headers with auth token
- `parseJwt(token)` - Parse JWT token (if using JWT)
- `getTimeUntilExpiration(expiresAt)` - Get seconds until expiration
- `formatTimeRemaining(seconds)` - Format time as string
- `isValidEmail(email)` - Validate email format
- `isStrongPassword(password)` - Validate password strength

---

### 6. Router Configuration (`src/router/index.js`)
**Purpose:** Route definitions with authentication guards.

**Route Structure:**
- Public routes (login, register) - Protected by `guestGuard`
- Investor routes - Protected by `investorGuard`
- Admin routes - Protected by `adminGuard`

**Global Guard:**
- Checks `requiresAuth` meta field
- Applies `authGuard` for protected routes

---

## Authentication Flow

### Login Flow
```
User enters credentials
    ↓
Component calls useAuth().login()
    ↓
authService.login() API call
    ↓
Backend validates credentials
    ↓
Backend returns token, user, role, expires_in
    ↓
authStore.login() saves to state + localStorage
    ↓
Redirect to dashboard (investor or admin)
```

### Protected Route Access
```
User navigates to protected route
    ↓
Router calls beforeEnter guard
    ↓
Guard checks authStore.isAuthenticated
    ↓
If authenticated → Allow access
If not authenticated → Redirect to /login?redirect=...
```

### API Request Flow
```
Component makes API call
    ↓
Axios request interceptor adds Authorization header
    ↓
API request sent
    ↓
If 401 response → Attempt token refresh
    ↓
If refresh succeeds → Retry original request
If refresh fails → Logout and redirect to login
```

### Logout Flow
```
User clicks logout
    ↓
Component calls useAuth().logout()
    ↓
authService.logout() API call (optional)
    ↓
authStore.logout() clears state + localStorage
    ↓
Redirect to /login
```

## Session Management

### Token Storage
- Stored in localStorage
- Key: `token`
- Format: Bearer token from Laravel Sanctum

### Role Storage
- Stored in localStorage
- Key: `role`
- Values: `investor` or `admin`

### Expiration Tracking
- Stored in localStorage
- Key: `tokenExpiresAt`
- Format: ISO 8601 timestamp
- Auto-checked on route navigation and API calls

### Session Validation
- Checked on every route navigation
- Checked before every API request
- Automatic logout on expiration

## Security Best Practices

### 1. Token Security
- Tokens stored in localStorage (consider secure cookies for production)
- HTTPS required in production
- Token refresh mechanism
- Automatic logout on expiration

### 2. Route Protection
- All protected routes use guards
- Role-based access control
- Redirect to login with return URL
- Session validation on navigation

### 3. API Security
- All API calls include auth token
- Token refresh on 401
- Automatic logout on critical errors
- Request timestamp for cache busting

### 4. Input Validation
- Email format validation
- Password strength validation
- Backend validation required

### 5. Error Handling
- User-friendly error messages
- Automatic logout on auth errors
- Notification system integration

## Role-Based Access Control

### Investor Role
- Access to investor dashboard
- Access to investor pages (profile, balance, profit history, etc.)
- Cannot access admin pages

### Admin Role
- Access to admin dashboard
- Access to admin pages (investors, distributions, reconciliation, etc.)
- Cannot access investor pages

### Role Enforcement
- Enforced at route level (middleware)
- Enforced at API level (backend Sanctum)
- Automatic redirection based on role

## Integration with Backend

### Laravel Sanctum
- Uses Sanctum token authentication
- Token-based API access
- Role-based middleware on backend

### API Endpoints
```
POST /api/v1/auth/login
POST /api/v1/auth/register
POST /api/v1/auth/logout
POST /api/v1/auth/refresh
GET  /api/v1/auth/me
```

### Response Format
```json
{
  "success": true,
  "message": "Login successful",
  "data": {
    "user": { ... },
    "token": "1|xxxxx",
    "role": "investor",
    "expires_in": 3600
  }
}
```

## Usage Examples

### Login Component
```javascript
import { useAuth } from '@/composables/useAuth'

const { login, isAuthenticated } = useAuth()

async function handleLogin() {
  const result = await login({
    email: form.value.email,
    password: form.value.password
  })
  
  if (result.success) {
    // Redirected automatically
  } else {
    // Show error
  }
}
```

### Protected Component
```javascript
import { useAuth } from '@/composables/useAuth'

const { isAuthenticated, logout } = useAuth()

// Component is only accessible if authenticated
// Router guard enforces this
```

### API Call with Auth
```javascript
import investorService from '@/services/investor.service'

// Token automatically added by interceptor
const data = await investorService.getDashboard()
```

## File Structure
```
src/
├── middleware/
│   └── auth.js              # Route guards
├── stores/
│   └── auth.js              # Auth state management
├── composables/
│   └── useAuth.js           # Auth composable
├── services/
│   ├── api.js               # Axios with auth interceptor
│   └── auth.service.js      # Auth API calls
├── utils/
│   └── auth.js              # Auth utility functions
└── router/
    └── index.js             # Route configuration
```

## Configuration

### Environment Variables
```
VITE_API_BASE_URL=http://localhost:8000/api/v1
VITE_API_TIMEOUT=30000
```

### Token Expiration
- Default: 1 hour (3600 seconds)
- Configurable via backend response
- Auto-refresh on API 401

## Testing Checklist

- [ ] Login with valid credentials
- [ ] Login with invalid credentials
- [ ] Registration flow
- [ ] Logout clears localStorage
- [ ] Protected routes redirect to login
- [ ] Role-based access control
- [ ] Token refresh on 401
- [ ] Session expiration handling
- [ ] Return URL after login
- [ ] Auto-logout on expired session

## Next Steps

Authentication architecture is complete and ready for:
1. Backend Sanctum integration
2. Dashboard page implementation
3. API integration with actual endpoints
4. Additional auth features (2FA, social login, etc.)
