trcr/lib/password_service.dart

67 lines
2.3 KiB
Dart
Raw Normal View History

2025-06-28 14:57:56 -07:00
import 'package:flutter/material.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:traccar_client/l10n/app_localizations.dart';
2026-02-01 15:17:33 -08:00
import 'package:traccar_client/preferences.dart';
2025-06-28 14:57:56 -07:00
class PasswordService {
static final FlutterSecureStorage _secureStorage = const FlutterSecureStorage();
static const String _passwordKey = 'password';
2026-02-01 15:17:33 -08:00
static Future<void> migrate() async {
final oldPassword = await _secureStorage.read(key: _passwordKey);
if (oldPassword == null) return;
await Preferences.instance.setString(_passwordKey, oldPassword);
await _secureStorage.delete(key: _passwordKey);
}
2025-06-28 14:57:56 -07:00
static Future<bool> authenticate(BuildContext context) async {
2026-02-01 15:17:33 -08:00
final storedPassword = Preferences.instance.getString(_passwordKey);
if (storedPassword == null || storedPassword.isEmpty) return true;
2025-06-28 14:57:56 -07:00
final controller = TextEditingController();
bool? result;
if (context.mounted) {
result = await showDialog<bool>(
context: context,
builder: (context) => AlertDialog(
2025-07-10 20:16:21 -07:00
scrollable: true,
2025-06-28 14:57:56 -07:00
content: TextField(
controller: controller,
autofocus: true,
obscureText: true,
decoration: InputDecoration(labelText: AppLocalizations.of(context)!.passwordLabel),
),
actions: [
TextButton(
onPressed: () => Navigator.pop(context, false),
child: Text(AppLocalizations.of(context)!.cancelButton),
),
TextButton(
onPressed: () async {
if (context.mounted) {
2026-02-01 15:17:33 -08:00
Navigator.pop(context, storedPassword == controller.text);
2025-06-28 14:57:56 -07:00
}
},
child: Text(AppLocalizations.of(context)!.okButton),
),
],
),
);
}
if (result != true && context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(AppLocalizations.of(context)!.passwordError)),
);
return false;
}
return result == true;
}
static Future<void> setPassword(String password) async {
if (password.isNotEmpty) {
2026-02-01 15:17:33 -08:00
await Preferences.instance.setString(_passwordKey, password);
2025-06-28 14:57:56 -07:00
} else {
2026-02-01 15:17:33 -08:00
await Preferences.instance.remove(_passwordKey);
2025-06-28 14:57:56 -07:00
}
}
}