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:flutter_secure_storage/flutter_secure_storage.dart';
|
|
|
|
import 'package:provider/provider.dart';
|
|
|
|
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
|
|
|
late final FlutterSecureStorage _storage = FlutterSecureStorage();
|
|
|
|
|
2024-11-14 16:24:46 +00:00
|
|
|
Future<String?> get atk => _storage.read(key: kAtkStoreKey);
|
|
|
|
|
2024-11-09 10:28:45 +00:00
|
|
|
UserProvider(BuildContext context) {
|
2024-11-09 11:32:21 +00:00
|
|
|
_sn = context.read<SnNetworkProvider>();
|
2024-11-09 10:28:45 +00:00
|
|
|
|
|
|
|
_storage.read(key: kAtkStoreKey).then((value) {
|
|
|
|
isAuthorized = value != null;
|
|
|
|
notifyListeners();
|
|
|
|
refreshUser().then((value) {
|
|
|
|
if (value != null) {
|
|
|
|
log('Logged in as @${value.name}');
|
|
|
|
}
|
|
|
|
});
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
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-09 13:47:40 +00:00
|
|
|
await _sn.clearTokenPair();
|
2024-11-09 11:32:21 +00:00
|
|
|
isAuthorized = false;
|
|
|
|
user = null;
|
|
|
|
notifyListeners();
|
|
|
|
}
|
2024-11-09 10:28:45 +00:00
|
|
|
}
|