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-18 16:23:10 +01:00
|
|
|
import 'package:simplecloudnotifier/api/api_client.dart';
|
2024-05-25 22:06:43 +02:00
|
|
|
import 'package:simplecloudnotifier/models/key_token_auth.dart';
|
|
|
|
import 'package:simplecloudnotifier/models/user.dart';
|
2024-05-26 18:34:42 +02:00
|
|
|
import 'package:simplecloudnotifier/state/globals.dart';
|
2024-02-11 01:08:51 +01:00
|
|
|
|
|
|
|
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
|
|
|
|
2024-05-26 18:34:42 +02:00
|
|
|
void load() {
|
|
|
|
final uid = Globals().sharedPrefs.getString('auth.userid');
|
|
|
|
final tok = Globals().sharedPrefs.getString('auth.token');
|
2024-02-11 02:20:48 +01:00
|
|
|
|
|
|
|
if (uid != null && tok != null) {
|
|
|
|
setToken(KeyTokenAuth(userId: uid, token: tok));
|
|
|
|
} else {
|
|
|
|
clearToken();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-05-25 21:36:05 +02:00
|
|
|
Future<void> save() async {
|
2024-02-11 02:20:48 +01:00
|
|
|
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-18 16:23:10 +01:00
|
|
|
|
2024-05-25 21:36:05 +02:00
|
|
|
Future<User> loadUser(bool force) async {
|
2024-02-18 16:23:10 +01:00
|
|
|
if (!force && _user != null) {
|
2024-05-25 21:36:05 +02:00
|
|
|
return _user!;
|
2024-02-18 16:23:10 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
if (_auth == null) {
|
|
|
|
throw Exception('Not authenticated');
|
|
|
|
}
|
|
|
|
|
2024-05-25 18:09:39 +02:00
|
|
|
final user = await APIClient.getUser(_auth!, _auth!.userId);
|
2024-02-18 16:23:10 +01:00
|
|
|
|
|
|
|
setUser(user);
|
|
|
|
|
|
|
|
await save();
|
|
|
|
|
|
|
|
return user;
|
|
|
|
}
|
2024-02-11 01:08:51 +01:00
|
|
|
}
|