Surface/lib/providers/userinfo.dart

53 lines
1.3 KiB
Dart
Raw Normal View History

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';
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
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-11-09 10:28:45 +00:00
SharedPreferences.getInstance().then((prefs) {
final value = prefs.getString(kAtkStoreKey);
2024-11-09 10:28:45 +00:00
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);
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 {
_sn.clearTokenPair();
2024-11-09 11:32:21 +00:00
isAuthorized = false;
user = null;
notifyListeners();
}
2024-11-09 10:28:45 +00:00
}