File size: 8,592 Bytes
25f22bf |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 |
# 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. |