data4autos_mobile_app/lib/data/repositories/token_repository.dart

58 lines
1.5 KiB
Dart

import 'package:autos/core/constants/api_endpoints.dart';
import 'package:autos/data/sources/remote/api_service.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
class TokenRepository {
final ApiService apiService;
final _storage = const FlutterSecureStorage();
TokenRepository(this.apiService);
static const _tokenKey = "turn14_token";
static const _tokenTimeKey = "turn14_token_time";
/// ✅ Get Valid Token (Auto Refresh If Expired)
Future<String> getValidToken(String userId) async {
final token = await _storage.read(key: _tokenKey);
final time = await _storage.read(key: _tokenTimeKey);
if (token != null && time != null) {
final savedTime = DateTime.parse(time);
final diff = DateTime.now().difference(savedTime);
/// ✅ Token Valid for 50 minutes
if (diff.inMinutes < 50) {
return token;
}
}
/// 🔄 Token Expired → Refresh
return await _refreshToken(userId);
}
/// 🔄 Refresh Token API
Future<String> _refreshToken(String userId) async {
final response = await apiService.post(
ApiEndpoints.getToken,
{"userid": userId},
);
final data = response.data;
if (data["code"] != "TOKEN_UPDATED") {
throw Exception(data["message"]);
}
final token = data["access_token"];
/// ✅ Save New Token + Timestamp
await _storage.write(key: _tokenKey, value: token);
await _storage.write(
key: _tokenTimeKey,
value: DateTime.now().toIso8601String(),
);
return token;
}
}