61 lines
1.9 KiB
Dart
61 lines
1.9 KiB
Dart
import 'dart:async';
|
||
import 'dart:convert';
|
||
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
|
||
import 'package:http/http.dart' as http;
|
||
|
||
class TokenStorage {
|
||
final _storage = const FlutterSecureStorage();
|
||
final String baseUrl;
|
||
TokenStorage(this.baseUrl);
|
||
|
||
Future<void> save(String access, String refresh) async {
|
||
await _storage.write(key: 'access', value: access);
|
||
await _storage.write(key: 'refresh', value: refresh);
|
||
}
|
||
|
||
Future<String?> get access async => await _storage.read(key: 'access');
|
||
Future<String?> get refresh async => await _storage.read(key: 'refresh');
|
||
Future<void> clear() async {
|
||
await _storage.deleteAll();
|
||
}
|
||
|
||
/// Einfache Auto‑Refresh Logik
|
||
Future<String?> getValidAccessToken() async {
|
||
final token = await access;
|
||
// (Optional) hier exp prüfen. Für Kürze direkt refresh call beim 401 außerhalb.
|
||
return token;
|
||
}
|
||
|
||
Future<void> refreshAccess() async {
|
||
final r = await refresh;
|
||
if (r == null) return;
|
||
final res = await http.post(Uri.parse('$baseUrl/auth/refresh'),
|
||
headers: {'Content-Type': 'application/json'},
|
||
body: jsonEncode({'refresh_token': r}));
|
||
if (res.statusCode == 200) {
|
||
final m = jsonDecode(res.body) as Map<String, dynamic>;
|
||
await _storage.write(key: 'access', value: m['access_token'] as String);
|
||
} else {
|
||
await clear();
|
||
}
|
||
}
|
||
|
||
Future<bool> hasValidAccessToken() async {
|
||
final a = await access;
|
||
if (a == null || a.isEmpty) return false;
|
||
try {
|
||
final parts = a.split('.');
|
||
if (parts.length != 3) return false;
|
||
final payload = jsonDecode(
|
||
utf8.decode(base64Url.decode(base64Url.normalize(parts[1]))))
|
||
as Map<String, dynamic>;
|
||
final exp = (payload['exp'] as num?)?.toInt();
|
||
if (exp == null) return true;
|
||
final now = DateTime.now().millisecondsSinceEpoch ~/ 1000;
|
||
return now < exp - 15;
|
||
} catch (_) {
|
||
return false;
|
||
}
|
||
}
|
||
}
|