rwadurian/frontend/mobile-app/lib/features/auth/presentation/providers/auth_provider.dart

94 lines
2.5 KiB
Dart

import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../../../core/storage/secure_storage.dart';
import '../../../../core/storage/storage_keys.dart';
import '../../../../core/di/injection_container.dart';
enum AuthStatus {
initial,
checking,
authenticated,
unauthenticated,
}
class AuthState {
final AuthStatus status;
final String? walletAddress;
final bool isWalletCreated;
final String? errorMessage;
const AuthState({
this.status = AuthStatus.initial,
this.walletAddress,
this.isWalletCreated = false,
this.errorMessage,
});
AuthState copyWith({
AuthStatus? status,
String? walletAddress,
bool? isWalletCreated,
String? errorMessage,
}) {
return AuthState(
status: status ?? this.status,
walletAddress: walletAddress ?? this.walletAddress,
isWalletCreated: isWalletCreated ?? this.isWalletCreated,
errorMessage: errorMessage,
);
}
}
class AuthNotifier extends StateNotifier<AuthState> {
final SecureStorage _secureStorage;
AuthNotifier(this._secureStorage) : super(const AuthState());
Future<void> checkAuthStatus() async {
state = state.copyWith(status: AuthStatus.checking);
try {
final walletAddress = await _secureStorage.read(key: StorageKeys.walletAddress);
final isWalletCreated = walletAddress != null && walletAddress.isNotEmpty;
if (isWalletCreated) {
state = state.copyWith(
status: AuthStatus.authenticated,
walletAddress: walletAddress,
isWalletCreated: true,
);
} else {
state = state.copyWith(
status: AuthStatus.unauthenticated,
isWalletCreated: false,
);
}
} catch (e) {
state = state.copyWith(
status: AuthStatus.unauthenticated,
errorMessage: e.toString(),
);
}
}
Future<void> saveWallet(String walletAddress, String privateKey) async {
await _secureStorage.write(key: StorageKeys.walletAddress, value: walletAddress);
await _secureStorage.write(key: StorageKeys.privateKey, value: privateKey);
state = state.copyWith(
status: AuthStatus.authenticated,
walletAddress: walletAddress,
isWalletCreated: true,
);
}
Future<void> logout() async {
await _secureStorage.deleteAll();
state = const AuthState(status: AuthStatus.unauthenticated);
}
}
final authProvider = StateNotifierProvider<AuthNotifier, AuthState>((ref) {
final secureStorage = ref.watch(secureStorageProvider);
return AuthNotifier(secureStorage);
});