Files
sendico/frontend/pweb/lib/providers/account.dart

98 lines
2.5 KiB
Dart

import 'package:flutter/foundation.dart';
import 'package:pshared/api/requests/login_data.dart';
import 'package:pshared/models/account/account.dart';
import 'package:pshared/models/auth/login_outcome.dart';
import 'package:pshared/models/auth/pending_login.dart';
import 'package:pshared/models/describable.dart';
import 'package:pweb/providers/permissions.dart';
import 'package:pweb/services/accounts.dart';
class AccountProvider extends ChangeNotifier {
final AccountsService _accountsService;
final PermissionsProvider _permissionsProvider;
AccountProvider({
required AccountsService accountsService,
required PermissionsProvider permissionsProvider,
}) : _accountsService = accountsService,
_permissionsProvider = permissionsProvider;
Account? _account;
bool _isLoading = false;
Object? _error;
Account? get account => _account;
bool get isLoading => _isLoading;
Object? get error => _error;
bool get isLoggedIn => _account != null;
PendingLogin? get pendingLogin => null;
Future<LoginOutcome> login({
required String email,
required String password,
required String locale,
}) async {
_setLoading(true);
try {
final result = await _accountsService.login(email, password, locale: locale);
_account = result.account;
_error = null;
await _permissionsProvider.loadForAccount(result.account.id);
return LoginOutcome.completed(result.account);
} catch (e) {
_error = e;
rethrow;
} finally {
_setLoading(false);
}
}
void completePendingLogin(Account account) {
_account = account;
_permissionsProvider.loadForAccount(account.id);
notifyListeners();
}
Future<Account?> restore() async {
_setLoading(true);
_account = null;
_permissionsProvider.clear();
_error = Exception('Сохраненная сессия отсутствует');
_setLoading(false);
return null;
}
Future<void> signup({
required AccountData account,
required Describable organization,
required String timezone,
required Describable ownerRole,
}) async {
_setLoading(true);
_error = null;
try {
await _accountsService.signup(account);
} catch (e) {
_error = e;
rethrow;
} finally {
_setLoading(false);
}
}
Future<void> logout() async {
_account = null;
_error = null;
_permissionsProvider.clear();
notifyListeners();
}
void _setLoading(bool value) {
_isLoading = value;
notifyListeners();
}
}