60 lines
1.6 KiB
Dart
60 lines
1.6 KiB
Dart
import 'package:flutter/foundation.dart';
|
|
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
|
|
import 'package:local_auth/local_auth.dart';
|
|
import 'package:device_info_plus/device_info_plus.dart';
|
|
|
|
class AuthToken {
|
|
static final AuthToken _instance = AuthToken._internal();
|
|
static AuthToken get instance => _instance;
|
|
AuthToken._internal();
|
|
|
|
final _storage = const FlutterSecureStorage();
|
|
String? _token;
|
|
|
|
String? get token => _token;
|
|
|
|
Future<bool> isMobilePlatform() async {
|
|
if (kIsWeb) return false;
|
|
final deviceInfo = DeviceInfoPlugin();
|
|
if (defaultTargetPlatform == TargetPlatform.android) return true;
|
|
if (defaultTargetPlatform == TargetPlatform.iOS) return true;
|
|
return false;
|
|
}
|
|
|
|
Future<void> saveToken(String token) async {
|
|
_token = token;
|
|
if (await isMobilePlatform()) {
|
|
await _storage.write(key: 'AuthToken', value: token);
|
|
}
|
|
}
|
|
|
|
Future<bool> loadTokenWithBiometric() async {
|
|
if (!await isMobilePlatform()) return false;
|
|
|
|
final auth = LocalAuthentication();
|
|
final canAuth =
|
|
await auth.canCheckBiometrics || await auth.isDeviceSupported();
|
|
if (!canAuth) return false;
|
|
|
|
final authenticated = await auth.authenticate(
|
|
localizedReason: 'Autenticati per accedere',
|
|
options: const AuthenticationOptions(biometricOnly: true),
|
|
);
|
|
|
|
if (authenticated) {
|
|
final stored = await _storage.read(key: 'AuthToken');
|
|
_token = stored;
|
|
return stored != null;
|
|
}
|
|
|
|
return false;
|
|
}
|
|
|
|
Future<void> clear() async {
|
|
_token = null;
|
|
if (await isMobilePlatform()) {
|
|
await _storage.delete(key: 'AuthToken');
|
|
}
|
|
}
|
|
}
|