import 'dart:convert'; import 'package:http/http.dart' as http; import 'package:shared_preferences/shared_preferences.dart'; import '../config/api_config.dart'; class AuthService { static const String _tokenKey = 'auth_token'; static const String _expiresKey = 'token_expires'; static const String _usernameKey = 'username'; String? _token; DateTime? _expiresAt; String? _username; String? get token => _token; String? get username => _username; bool get isAuthenticated => _token != null && !isExpired; bool get isExpired => _expiresAt != null && DateTime.now().isAfter(_expiresAt!); Future loadStoredAuth() async { final prefs = await SharedPreferences.getInstance(); _token = prefs.getString(_tokenKey); _username = prefs.getString(_usernameKey); final expiresStr = prefs.getString(_expiresKey); if (expiresStr != null) { _expiresAt = DateTime.tryParse(expiresStr); } } String? lastError; Future login(String username, String password) async { lastError = null; try { final response = await http.post( Uri.parse('${ApiConfig.baseUrl}/auth/login'), headers: {'Content-Type': 'application/json'}, body: jsonEncode({'username': username, 'password': password}), ).timeout(ApiConfig.connectionTimeout); if (response.statusCode == 200) { final data = jsonDecode(response.body); _token = data['token']; _expiresAt = DateTime.parse(data['expires_at']); _username = username; // Save to storage final prefs = await SharedPreferences.getInstance(); await prefs.setString(_tokenKey, _token!); await prefs.setString(_expiresKey, _expiresAt!.toIso8601String()); await prefs.setString(_usernameKey, _username!); return true; } lastError = 'Invalid credentials (${response.statusCode})'; return false; } catch (e) { lastError = 'Connection error: $e'; return false; } } Future logout() async { _token = null; _expiresAt = null; _username = null; final prefs = await SharedPreferences.getInstance(); await prefs.remove(_tokenKey); await prefs.remove(_expiresKey); await prefs.remove(_usernameKey); } }