SimpleCloudNotifier/flutter/lib/state/user_account.dart

64 lines
1.3 KiB
Dart
Raw Normal View History

2024-02-11 01:08:51 +01:00
import 'package:flutter/foundation.dart';
2024-02-11 02:20:48 +01:00
import 'package:shared_preferences/shared_preferences.dart';
2024-02-11 01:08:51 +01:00
import '../models/key_token_auth.dart';
import '../models/user.dart';
class UserAccount extends ChangeNotifier {
User? _user;
User? get user => _user;
KeyTokenAuth? _auth;
KeyTokenAuth? get auth => _auth;
2024-02-11 02:20:48 +01:00
UserAccount() {
load();
}
2024-02-11 01:08:51 +01:00
void setToken(KeyTokenAuth auth) {
_auth = auth;
2024-02-11 02:20:48 +01:00
_user = null;
notifyListeners();
}
void clearToken() {
_auth = null;
_user = null;
2024-02-11 01:08:51 +01:00
notifyListeners();
}
void setUser(User user) {
_user = user;
notifyListeners();
}
void clearUser() {
_user = null;
notifyListeners();
}
2024-02-11 02:20:48 +01:00
load() async {
final prefs = await SharedPreferences.getInstance();
final uid = prefs.getString('auth.userid');
final tok = prefs.getString('auth.token');
if (uid != null && tok != null) {
setToken(KeyTokenAuth(userId: uid, token: tok));
} else {
clearToken();
}
}
save() async {
final prefs = await SharedPreferences.getInstance();
if (_auth == null) {
await prefs.remove('auth.userid');
await prefs.remove('auth.token');
} else {
await prefs.setString('auth.userid', _auth!.userId);
await prefs.setString('auth.token', _auth!.token);
}
}
2024-02-11 01:08:51 +01:00
}