96 lines
2.6 KiB
Dart
96 lines
2.6 KiB
Dart
import 'package:flutter/material.dart';
|
|
|
|
import 'package:logging/logging.dart';
|
|
|
|
import 'package:pshared/models/auth/pending_login.dart';
|
|
import 'package:pshared/provider/account.dart';
|
|
import 'package:pshared/service/verification.dart';
|
|
|
|
|
|
class TwoFactorProvider extends ChangeNotifier {
|
|
static final _logger = Logger('provider.two_factor');
|
|
late AccountProvider _accountProvider;
|
|
|
|
TwoFactorProvider();
|
|
|
|
bool _isSubmitting = false;
|
|
bool _hasError = false;
|
|
bool _verificationSuccess = false;
|
|
String? _errorMessage;
|
|
String? _currentPendingToken;
|
|
|
|
bool get isSubmitting => _isSubmitting;
|
|
bool get hasError => _hasError;
|
|
bool get verificationSuccess => _verificationSuccess;
|
|
String? get errorMessage => _errorMessage;
|
|
PendingLogin? get pendingLogin => _accountProvider.pendingLogin;
|
|
|
|
void update(AccountProvider accountProvider) {
|
|
_accountProvider = accountProvider;
|
|
final pending = accountProvider.pendingLogin;
|
|
final token = pending?.pendingToken.token;
|
|
if (token != _currentPendingToken || accountProvider.account == null) {
|
|
_resetState();
|
|
_currentPendingToken = token;
|
|
}
|
|
}
|
|
|
|
Future<void> submitCode(String code) async {
|
|
_isSubmitting = true;
|
|
_hasError = false;
|
|
_errorMessage = null;
|
|
_verificationSuccess = false;
|
|
notifyListeners();
|
|
|
|
try {
|
|
final pending = _accountProvider.pendingLogin;
|
|
if (pending == null) {
|
|
throw Exception('No pending login available');
|
|
}
|
|
final account = await VerificationService.confirmLoginCode(
|
|
pending: pending,
|
|
code: code,
|
|
);
|
|
_accountProvider.completePendingLogin(account);
|
|
_verificationSuccess = true;
|
|
_currentPendingToken = null;
|
|
} catch (e) {
|
|
_hasError = true;
|
|
_errorMessage = e.toString();
|
|
_logger.warning('Failed to verify code: ${e.toString()}', e);
|
|
} finally {
|
|
_isSubmitting = false;
|
|
notifyListeners();
|
|
}
|
|
}
|
|
|
|
Future<void> resendCode() async {
|
|
final pending = _accountProvider.pendingLogin;
|
|
if (pending == null) {
|
|
_logger.warning('No pending login to resend code for');
|
|
return;
|
|
}
|
|
try {
|
|
await VerificationService.resendLoginCode(pending);
|
|
} catch (e) {
|
|
_logger.warning('Failed to resend login code', e);
|
|
_hasError = true;
|
|
_errorMessage = e.toString();
|
|
notifyListeners();
|
|
}
|
|
}
|
|
|
|
void reset() {
|
|
_resetState();
|
|
_currentPendingToken = null;
|
|
}
|
|
|
|
void _resetState() {
|
|
_isSubmitting = false;
|
|
_hasError = false;
|
|
_errorMessage = null;
|
|
_verificationSuccess = false;
|
|
notifyListeners();
|
|
}
|
|
}
|