- Flutter app with chat and terminal screens - WebSocket integration for real-time chat - xterm integration for screen sessions - Markdown rendering with code blocks - JWT authentication Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
62 lines
1.4 KiB
Dart
62 lines
1.4 KiB
Dart
import 'dart:convert';
|
|
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
|
|
import '../models/user.dart';
|
|
import 'api_service.dart';
|
|
|
|
class AuthService {
|
|
final ApiService _apiService;
|
|
final FlutterSecureStorage _storage = const FlutterSecureStorage();
|
|
|
|
static const String _userKey = 'captain_user';
|
|
|
|
AuthService(this._apiService);
|
|
|
|
Future<User?> login(String username, String password) async {
|
|
try {
|
|
final response = await _apiService.login(username, password);
|
|
final user = User(
|
|
username: username,
|
|
token: response['token'],
|
|
expiresAt: DateTime.parse(response['expires_at']),
|
|
);
|
|
|
|
await _saveUser(user);
|
|
_apiService.setToken(user.token);
|
|
|
|
return user;
|
|
} catch (e) {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
Future<User?> getStoredUser() async {
|
|
try {
|
|
final data = await _storage.read(key: _userKey);
|
|
if (data == null) return null;
|
|
|
|
final user = User.fromJson(jsonDecode(data));
|
|
if (user.isExpired) {
|
|
await logout();
|
|
return null;
|
|
}
|
|
|
|
_apiService.setToken(user.token);
|
|
return user;
|
|
} catch (e) {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
Future<void> _saveUser(User user) async {
|
|
await _storage.write(
|
|
key: _userKey,
|
|
value: jsonEncode(user.toJson()),
|
|
);
|
|
}
|
|
|
|
Future<void> logout() async {
|
|
await _storage.delete(key: _userKey);
|
|
_apiService.setToken(null);
|
|
}
|
|
}
|