Phase 6 - User Session Management complete

This commit is contained in:
gitea
2025-11-05 21:14:34 +01:00
parent 53d11d49ff
commit 13ec9e5a9d
8 changed files with 758 additions and 8 deletions
+60 -5
View File
@@ -42,21 +42,35 @@ class LocalStorageService {
/// Initializes the database and cache directory.
///
/// [sessionDbPath] - Optional database path for session-specific storage.
/// [sessionCacheDir] - Optional cache directory for session-specific storage.
///
/// Must be called before using any other methods.
///
/// Throws [Exception] if initialization fails.
Future<void> initialize() async {
Future<void> initialize({
String? sessionDbPath,
Directory? sessionCacheDir,
}) async {
try {
// Initialize database
final dbPath = _testDbPath ?? await _getDatabasePath();
// Close existing database if switching sessions
if (_database != null) {
await _database!.close();
_database = null;
}
// Initialize database with session-specific or default path
final dbPath = sessionDbPath ?? _testDbPath ?? await _getDatabasePath();
_database = await openDatabase(
dbPath,
version: 1,
onCreate: _onCreate,
);
// Initialize cache directory
if (_testCacheDir != null) {
// Initialize cache directory with session-specific or default path
if (sessionCacheDir != null) {
_cacheDirectory = sessionCacheDir;
} else if (_testCacheDir != null) {
_cacheDirectory = _testCacheDir;
} else {
final appDir = await getApplicationDocumentsDirectory();
@@ -66,11 +80,52 @@ class LocalStorageService {
if (!await _cacheDirectory!.exists()) {
await _cacheDirectory!.create(recursive: true);
}
// Clear in-memory cache status when switching sessions
_cacheStatus.clear();
} catch (e) {
throw Exception('Failed to initialize LocalStorageService: $e');
}
}
/// Reinitializes the service with a new database path (for session switching).
///
/// [newDbPath] - New database path to use.
/// [newCacheDir] - New cache directory to use.
///
/// Throws [Exception] if reinitialization fails.
Future<void> reinitializeForSession({
required String newDbPath,
required Directory newCacheDir,
}) async {
await initialize(
sessionDbPath: newDbPath,
sessionCacheDir: newCacheDir,
);
}
/// Clears all cached data (for session logout).
///
/// Throws [Exception] if clearing fails.
Future<void> clearAllData() async {
_ensureInitialized();
try {
// Clear all items from database
await _database!.delete('items');
// Clear cache directory
if (_cacheDirectory != null && await _cacheDirectory!.exists()) {
await _cacheDirectory!.delete(recursive: true);
await _cacheDirectory!.create(recursive: true);
}
// Clear in-memory cache status
_cacheStatus.clear();
} catch (e) {
throw Exception('Failed to clear all data: $e');
}
}
/// Creates the database schema if it doesn't exist.
Future<void> _onCreate(Database db, int version) async {
await db.execute('''
+80
View File
@@ -0,0 +1,80 @@
/// Data model representing a user session.
///
/// This model stores user identification and authentication information
/// for session management and data isolation.
class User {
/// Unique identifier for the user.
final String id;
/// Display name or username for the user.
final String username;
/// Optional authentication token or session token.
final String? token;
/// Timestamp when the session was created (milliseconds since epoch).
final int createdAt;
/// Creates a [User] instance.
///
/// [id] - Unique identifier for the user.
/// [username] - Display name or username.
/// [token] - Optional authentication token.
/// [createdAt] - Session creation timestamp (defaults to current time).
User({
required this.id,
required this.username,
this.token,
int? createdAt,
}) : createdAt = createdAt ?? DateTime.now().millisecondsSinceEpoch;
/// Creates a [User] from a Map (e.g., from database or JSON).
factory User.fromMap(Map<String, dynamic> map) {
return User(
id: map['id'] as String,
username: map['username'] as String,
token: map['token'] as String?,
createdAt: map['created_at'] as int?,
);
}
/// Converts the [User] to a Map for storage.
Map<String, dynamic> toMap() {
return {
'id': id,
'username': username,
'token': token,
'created_at': createdAt,
};
}
/// Creates a copy of this [User] with updated fields.
User copyWith({
String? id,
String? username,
String? token,
int? createdAt,
}) {
return User(
id: id ?? this.id,
username: username ?? this.username,
token: token ?? this.token,
createdAt: createdAt ?? this.createdAt,
);
}
@override
String toString() {
return 'User(id: $id, username: $username, createdAt: $createdAt)';
}
@override
bool operator ==(Object other) {
if (identical(this, other)) return true;
return other is User && other.id == id;
}
@override
int get hashCode => id.hashCode;
}
+262
View File
@@ -0,0 +1,262 @@
import 'dart:io';
import 'package:path/path.dart' as path;
import 'package:path_provider/path_provider.dart';
import '../local/local_storage_service.dart';
import '../sync/sync_engine.dart';
import 'models/user.dart';
/// Exception thrown when session operations fail.
class SessionException implements Exception {
/// Error message.
final String message;
/// Creates a [SessionException] with the provided message.
SessionException(this.message);
@override
String toString() => 'SessionException: $message';
}
/// Service for managing user sessions, login, logout, and session isolation.
///
/// This service provides:
/// - User login and logout
/// - Session switching between multiple users
/// - Data isolation per user session
/// - Cache clearing on logout
/// - Integration with local storage and sync engine
///
/// The service is modular and UI-independent, designed for offline-first behavior.
class SessionService {
/// Current active user session (null if no user is logged in).
User? _currentUser;
/// Local storage service for data persistence.
final LocalStorageService _localStorage;
/// Sync engine for coordinating sync operations (optional).
final SyncEngine? _syncEngine;
/// Map of user IDs to their session storage paths.
final Map<String, String> _userDbPaths = {};
/// Map of user IDs to their cache directories.
final Map<String, Directory> _userCacheDirs = {};
/// Optional test database path for testing.
final String? _testDbPath;
/// Optional test cache directory for testing.
final Directory? _testCacheDir;
/// Creates a [SessionService] instance.
///
/// [localStorage] - Local storage service for data persistence.
/// [syncEngine] - Optional sync engine for coordinating sync operations.
/// [testDbPath] - Optional database path for testing.
/// [testCacheDir] - Optional cache directory for testing.
SessionService({
required LocalStorageService localStorage,
SyncEngine? syncEngine,
String? testDbPath,
Directory? testCacheDir,
}) : _localStorage = localStorage,
_syncEngine = syncEngine,
_testDbPath = testDbPath,
_testCacheDir = testCacheDir;
/// Gets the current active user session.
///
/// Returns the current [User] if logged in, null otherwise.
User? get currentUser => _currentUser;
/// Checks if a user is currently logged in.
bool get isLoggedIn => _currentUser != null;
/// Logs in a user and creates an isolated session.
///
/// [id] - Unique identifier for the user.
/// [username] - Display name or username.
/// [token] - Optional authentication token.
///
/// Returns the logged-in [User].
///
/// Throws [SessionException] if login fails or if user is already logged in.
Future<User> login({
required String id,
required String username,
String? token,
}) async {
if (_currentUser != null) {
throw SessionException('User already logged in. Logout first.');
}
try {
final user = User(
id: id,
username: username,
token: token,
);
// Create user-specific storage paths
await _setupUserStorage(user);
// Set as current user
_currentUser = user;
return user;
} catch (e) {
throw SessionException('Failed to login: $e');
}
}
/// Logs out the current user and clears session data.
///
/// [clearCache] - Whether to clear cached data (default: true).
///
/// Throws [SessionException] if logout fails or if no user is logged in.
Future<void> logout({bool clearCache = true}) async {
if (_currentUser == null) {
throw SessionException('No user logged in.');
}
try {
final userId = _currentUser!.id;
// Clear user-specific data if requested
if (clearCache) {
await _clearUserData(userId);
}
// Clear current user
_currentUser = null;
// Clean up user storage references
_userDbPaths.remove(userId);
_userCacheDirs.remove(userId);
} catch (e) {
throw SessionException('Failed to logout: $e');
}
}
/// Switches to a different user session.
///
/// This method logs out the current user and logs in the new user.
///
/// [id] - Unique identifier for the new user.
/// [username] - Display name or username for the new user.
/// [token] - Optional authentication token for the new user.
/// [clearCache] - Whether to clear cached data for the previous user (default: true).
///
/// Returns the new logged-in [User].
///
/// Throws [SessionException] if switch fails.
Future<User> switchSession({
required String id,
required String username,
String? token,
bool clearCache = true,
}) async {
if (_currentUser != null) {
await logout(clearCache: clearCache);
}
return await login(
id: id,
username: username,
token: token,
);
}
/// Sets up user-specific storage paths and reinitializes local storage.
///
/// [user] - The user to set up storage for.
Future<void> _setupUserStorage(User user) async {
try {
// Get user-specific database path
// In test mode, create per-user paths under the test directory
// In production, create per-user paths under app documents
String dbPath;
if (_testDbPath != null) {
// Create user-specific path under test directory
final testDir = path.dirname(_testDbPath!);
dbPath = path.join(testDir, 'user_${user.id}_storage.db');
} else {
final appDir = await getApplicationDocumentsDirectory();
dbPath = path.join(appDir.path, 'users', user.id, 'storage.db');
}
_userDbPaths[user.id] = dbPath;
// Get user-specific cache directory
Directory cacheDir;
if (_testCacheDir != null) {
// Create user-specific cache under test directory
final testCacheParent = _testCacheDir!.path;
cacheDir = Directory(path.join(testCacheParent, 'user_${user.id}'));
} else {
final appDir = await getApplicationDocumentsDirectory();
cacheDir = Directory(path.join(appDir.path, 'users', user.id, 'cache'));
}
if (!await cacheDir.exists()) {
await cacheDir.create(recursive: true);
}
_userCacheDirs[user.id] = cacheDir;
// Reinitialize local storage with user-specific paths
await _localStorage.reinitializeForSession(
newDbPath: dbPath,
newCacheDir: cacheDir,
);
} catch (e) {
throw SessionException('Failed to setup user storage: $e');
}
}
/// Clears all data for a specific user.
///
/// [userId] - The ID of the user whose data should be cleared.
Future<void> _clearUserData(String userId) async {
try {
// Clear all data from local storage if it's the current user's storage
if (_currentUser?.id == userId) {
await _localStorage.clearAllData();
}
// Clear cache directory
final cacheDir = _userCacheDirs[userId];
if (cacheDir != null && await cacheDir.exists()) {
await cacheDir.delete(recursive: true);
}
// Clear database path reference
_userDbPaths.remove(userId);
_userCacheDirs.remove(userId);
// Notify sync engine if available
if (_syncEngine != null) {
// Sync engine will handle session cleanup internally
// This is a placeholder for future sync engine integration
}
} catch (e) {
throw SessionException('Failed to clear user data: $e');
}
}
/// Gets the database path for the current user.
///
/// Returns the database path if user is logged in, null otherwise.
String? getCurrentUserDbPath() {
if (_currentUser == null) return null;
return _userDbPaths[_currentUser!.id];
}
/// Gets the cache directory for the current user.
///
/// Returns the cache directory if user is logged in, null otherwise.
Directory? getCurrentUserCacheDir() {
if (_currentUser == null) return null;
return _userCacheDirs[_currentUser!.id];
}
}