2024-11-09 10:28:45 +00:00
|
|
|
import 'dart:developer';
|
2024-11-08 16:09:46 +00:00
|
|
|
|
2024-11-09 10:28:45 +00:00
|
|
|
import 'package:flutter/material.dart';
|
|
|
|
import 'package:provider/provider.dart';
|
2024-11-23 11:54:38 +00:00
|
|
|
import 'package:shared_preferences/shared_preferences.dart';
|
2024-11-09 10:28:45 +00:00
|
|
|
import 'package:surface/providers/sn_network.dart';
|
|
|
|
import 'package:surface/types/account.dart';
|
|
|
|
|
|
|
|
class UserProvider extends ChangeNotifier {
|
|
|
|
bool isAuthorized = false;
|
|
|
|
SnAccount? user;
|
|
|
|
|
2024-11-09 11:32:21 +00:00
|
|
|
late final SnNetworkProvider _sn;
|
2024-11-09 10:28:45 +00:00
|
|
|
|
2024-11-23 11:54:38 +00:00
|
|
|
Future<String?> get atk async {
|
|
|
|
final prefs = await SharedPreferences.getInstance();
|
|
|
|
return prefs.getString(kAtkStoreKey);
|
|
|
|
}
|
2024-11-14 16:24:46 +00:00
|
|
|
|
2024-11-09 10:28:45 +00:00
|
|
|
UserProvider(BuildContext context) {
|
2024-11-09 11:32:21 +00:00
|
|
|
_sn = context.read<SnNetworkProvider>();
|
2024-12-13 17:32:13 +00:00
|
|
|
}
|
2024-11-09 10:28:45 +00:00
|
|
|
|
2024-12-13 17:32:13 +00:00
|
|
|
Future<void> initialize() async {
|
|
|
|
final prefs = await SharedPreferences.getInstance();
|
|
|
|
final value = prefs.getString(kAtkStoreKey);
|
|
|
|
isAuthorized = value != null;
|
|
|
|
notifyListeners();
|
|
|
|
refreshUser().then((value) {
|
|
|
|
if (value != null) {
|
|
|
|
log('Logged in as @${value.name}');
|
|
|
|
}
|
2024-11-09 10:28:45 +00:00
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
Future<SnAccount?> refreshUser() async {
|
2024-11-09 11:32:21 +00:00
|
|
|
final resp = await _sn.client.get('/cgi/id/users/me');
|
2024-11-09 10:28:45 +00:00
|
|
|
final out = SnAccount.fromJson(resp.data);
|
|
|
|
|
2024-11-09 13:47:40 +00:00
|
|
|
isAuthorized = true;
|
2024-11-09 10:28:45 +00:00
|
|
|
user = out;
|
|
|
|
notifyListeners();
|
|
|
|
|
|
|
|
return out;
|
|
|
|
}
|
2024-11-09 11:32:21 +00:00
|
|
|
|
|
|
|
void logoutUser() async {
|
2024-11-23 11:54:38 +00:00
|
|
|
_sn.clearTokenPair();
|
2024-11-09 11:32:21 +00:00
|
|
|
isAuthorized = false;
|
|
|
|
user = null;
|
|
|
|
notifyListeners();
|
|
|
|
}
|
2024-11-09 10:28:45 +00:00
|
|
|
}
|