|
# Cache System Documentation |
|
|
|
## Overview |
|
|
|
This document describes the cache system implementation for the "Remember Me" functionality in the Lin application. The cache system allows users to stay logged in across browser sessions when they check the "Remember Me" option during login. |
|
|
|
## Architecture |
|
|
|
### Frontend Components |
|
|
|
1. **CacheService** (`frontend/src/services/cacheService.js`) |
|
- Handles all cache operations using localForage |
|
- Provides secure token storage with TTL (Time To Live) |
|
- Manages user authentication cache |
|
- Implements device fingerprinting for security |
|
|
|
2. **AuthSlice** (`frontend/src/store/reducers/authSlice.js`) |
|
- Redux slice for authentication state management |
|
- Integrates with cache service for persistent authentication |
|
- Handles login/logout with remember me functionality |
|
|
|
3. **AuthService** (`frontend/src/services/authService.js`) |
|
- API service for authentication requests |
|
- Passes remember me flag to backend |
|
- Handles token storage and validation |
|
|
|
4. **Login Component** (`frontend/src/pages/Login.jsx`) |
|
- UI component with remember me checkbox |
|
- Manages remember me state |
|
- Submits remember me flag with login credentials |
|
|
|
### Backend Components |
|
|
|
1. **Auth API** (`backend/api/auth.py`) |
|
- Handles login requests with remember me parameter |
|
- Returns appropriate token expiration based on remember me flag |
|
|
|
2. **Auth Service** (`backend/services/auth_service.py`) |
|
- Business logic for authentication |
|
- Creates JWT tokens with different expiration times |
|
- Adds remember me claims to tokens |
|
|
|
## Features |
|
|
|
### 1. Secure Token Storage |
|
- Uses localForage for reliable storage |
|
- Implements TTL-based token expiration |
|
- Supports both session and remember me tokens |
|
|
|
### 2. Device Fingerprinting |
|
- Generates unique device identifiers |
|
- Validates device fingerprint on cache retrieval |
|
- Prevents unauthorized access from different devices |
|
|
|
### 3. Token Management |
|
- **Session Tokens**: 1 hour expiration |
|
- **Remember Me Tokens**: 7 days expiration |
|
- Automatic token refresh when possible |
|
- Secure token invalidation on logout |
|
|
|
### 4. Cache Operations |
|
- `set(key, data, ttl)`: Store data with TTL |
|
- `get(key)`: Retrieve data if not expired |
|
- `remove(key)`: Remove specific cache item |
|
- `clear()`: Clear all cached data |
|
- `exists(key)`: Check if cache exists and is valid |
|
|
|
### 5. Authentication Cache |
|
- `setAuthCache(authData, rememberMe)`: Store authentication data |
|
- `getAuthCache()`: Retrieve authentication data |
|
- `clearAuthCache()`: Clear authentication data |
|
|
|
## Implementation Details |
|
|
|
### Frontend Implementation |
|
|
|
#### Cache Service |
|
```javascript |
|
// Set authentication cache with remember me |
|
await cacheService.setAuthCache({ |
|
token: result.token, |
|
user: result.user |
|
}, rememberMe); |
|
|
|
// Get authentication cache |
|
const authCache = await cacheService.getAuthCache(); |
|
if (authCache) { |
|
// User is authenticated |
|
} |
|
``` |
|
|
|
#### Redux Integration |
|
```javascript |
|
// Login with remember me |
|
dispatch(loginUser({ |
|
email: credentials.email, |
|
password: credentials.password, |
|
rememberMe: true |
|
})); |
|
|
|
// Check cached authentication on app start |
|
dispatch(checkCachedAuth()); |
|
``` |
|
|
|
#### Login Component |
|
```javascript |
|
const handleSubmit = async (e) => { |
|
e.preventDefault(); |
|
|
|
try { |
|
const result = await dispatch(loginUser({ |
|
...formData, |
|
rememberMe: rememberMe |
|
})).unwrap(); |
|
|
|
navigate('/dashboard'); |
|
} catch (err) { |
|
console.error('Login failed:', err); |
|
} |
|
}; |
|
``` |
|
|
|
### Backend Implementation |
|
|
|
#### Login API |
|
```python |
|
def login(): |
|
data = request.get_json() |
|
email = data['email'] |
|
password = data['password'] |
|
remember_me = data.get('remember_me', False) |
|
|
|
result = login_user(email, password, remember_me) |
|
|
|
if result['success']: |
|
return jsonify(result), 200 |
|
else: |
|
return jsonify(result), 401 |
|
``` |
|
|
|
#### Auth Service |
|
```python |
|
def login_user(email: str, password: str, remember_me: bool = False) -> dict: |
|
if remember_me: |
|
# Extended token expiration (7 days) |
|
expires_delta = timedelta(days=7) |
|
token_type = "remember" |
|
else: |
|
# Standard token expiration (1 hour) |
|
expires_delta = timedelta(hours=1) |
|
token_type = "session" |
|
|
|
access_token = create_access_token( |
|
identity=response.user.id, |
|
additional_claims={ |
|
'remember_me': remember_me, |
|
'token_type': token_type |
|
}, |
|
expires_delta=expires_delta |
|
) |
|
|
|
return { |
|
'success': True, |
|
'token': access_token, |
|
'user': user.to_dict(), |
|
'rememberMe': remember_me, |
|
'expiresAt': (datetime.now() + expires_delta).isoformat(), |
|
'tokenType': token_type |
|
} |
|
``` |
|
|
|
## Security Considerations |
|
|
|
### 1. Token Security |
|
- JWT tokens with proper expiration |
|
- Secure storage using localForage |
|
- Token invalidation on logout |
|
|
|
### 2. Device Fingerprinting |
|
- Unique device identification |
|
- Prevents session hijacking |
|
- Detects unauthorized access attempts |
|
|
|
### 3. Cache Security |
|
- Encrypted storage where possible |
|
- TTL-based automatic cleanup |
|
- Secure cache clearing on logout |
|
|
|
### 4. Input Validation |
|
- Backend validation of remember me flag |
|
- Frontend state management |
|
- Secure API communication |
|
|
|
## Usage Examples |
|
|
|
### Basic Login with Remember Me |
|
```javascript |
|
// User checks "Remember Me" and logs in |
|
const credentials = { |
|
email: '[email protected]', |
|
password: 'password123', |
|
rememberMe: true |
|
}; |
|
|
|
const result = await authService.login(credentials); |
|
// User will stay logged in for 7 days |
|
``` |
|
|
|
### Automatic Login on App Start |
|
```javascript |
|
// Check for cached authentication on app initialization |
|
const cachedAuth = await cacheService.getAuthCache(); |
|
if (cachedAuth) { |
|
// Auto-login user |
|
dispatch(setUser(cachedAuth.user)); |
|
setIsAuthenticated(true); |
|
} |
|
``` |
|
|
|
### Logout |
|
```javascript |
|
// Clear all authentication data |
|
await cacheService.clearAuthCache(); |
|
dispatch(logoutUser()); |
|
``` |
|
|
|
## Configuration |
|
|
|
### Cache TTL Settings |
|
- **Session Tokens**: 1 hour (3,600,000 ms) |
|
- **Remember Me Tokens**: 7 days (604,800,000 ms) |
|
- **User Preferences**: 30 days (2,592,000,000 ms) |
|
- **API Responses**: 5 minutes (300,000 ms) |
|
|
|
### Storage Configuration |
|
- **Storage Driver**: localForage (IndexedDB > WebSQL > localStorage) |
|
- **Storage Name**: 'LinAppCache' |
|
- **Store Name**: 'authCache' |
|
|
|
## Error Handling |
|
|
|
### Common Scenarios |
|
1. **Expired Tokens**: Automatically cleared from cache |
|
2. **Invalid Tokens**: Removed from storage, user redirected to login |
|
3. **Storage Errors**: Fallback to localStorage, clear cache |
|
4. **Network Issues**: Offline mode with cached data |
|
|
|
### Error Recovery |
|
- Automatic token refresh when possible |
|
- Graceful degradation to localStorage |
|
- Clear error messages for users |
|
|
|
## Performance Considerations |
|
|
|
### Optimization |
|
- Asynchronous cache operations |
|
- Efficient storage usage |
|
- Minimal memory footprint |
|
- Background cache cleanup |
|
|
|
### Monitoring |
|
- Cache hit/miss logging |
|
- Storage usage tracking |
|
- Performance metrics collection |
|
|
|
## Future Enhancements |
|
|
|
### Planned Features |
|
1. **Biometric Authentication**: Integration with device biometrics |
|
2. **Multi-device Support**: Sync authentication across devices |
|
3. **Advanced Security**: Two-factor authentication integration |
|
4. **Offline Mode**: Full offline functionality with cached data |
|
|
|
### Scalability |
|
- Distributed caching support |
|
- Cache sharding for large datasets |
|
- Performance optimization for high traffic |
|
|
|
## Testing |
|
|
|
### Unit Tests |
|
- Cache service functionality |
|
- Authentication flow testing |
|
- Error handling scenarios |
|
|
|
### Integration Tests |
|
- Frontend-backend integration |
|
- Cache persistence testing |
|
- Security validation |
|
|
|
### End-to-End Tests |
|
- Complete authentication flow |
|
- Remember me functionality |
|
- Logout and session cleanup |
|
|
|
## Troubleshooting |
|
|
|
### Common Issues |
|
1. **Cache Not Working**: Check localForage availability |
|
2. **Token Expiration**: Verify TTL settings |
|
3. **Storage Errors**: Clear browser cache and data |
|
4. **Authentication Issues**: Verify backend configuration |
|
|
|
### Debug Mode |
|
Enable development logging for detailed debugging: |
|
```javascript |
|
// In development mode |
|
if (import.meta.env.VITE_NODE_ENV === 'development') { |
|
console.log('🗃️ [Cache]', cacheOperation); |
|
} |
|
``` |
|
|
|
## Conclusion |
|
|
|
The cache system implementation provides a robust, secure, and user-friendly authentication experience with the "Remember Me" functionality. It combines modern web technologies with best practices to ensure both security and usability. |
|
|
|
For questions or issues, please refer to the troubleshooting section or contact the development team. |