| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687 |
- import 'package:flutter_riverpod/flutter_riverpod.dart';
- import '../../core/constants.dart';
- import '../../database/database.dart';
- import 'database_provider.dart';
- import '../../services/auth_service.dart';
- import 'sync_provider.dart';
- class AuthState {
- final Agente? agente;
- final bool isLoading;
- final bool isInitialized;
- final String? error;
- const AuthState({this.agente, this.isLoading = false, this.isInitialized = false, this.error});
- bool get isLoggedIn => agente != null;
- }
- final authServiceProvider = Provider<AuthService>((ref) {
- return AuthService(
- ref.read(agentiDaoProvider),
- ref.read(apiServiceProvider),
- ref.read(parametriDaoProvider),
- );
- });
- class AuthNotifier extends Notifier<AuthState> {
- @override
- AuthState build() {
- _checkInitialized();
- return const AuthState();
- }
- Future<void> _checkInitialized() async {
- final authService = ref.read(authServiceProvider);
- final initialized = await authService.isInitialized();
- state = AuthState(isInitialized: initialized);
- }
- Future<void> login(String code, String password, String url) async {
- state = const AuthState(isLoading: true);
- try {
- await ref.read(parametriDaoProvider).set(AppConstants.kUrlParam, url);
- final authService = ref.read(authServiceProvider);
- final agente = await authService.login(code, password);
- if (agente != null) {
- state = AuthState(agente: agente, isInitialized: true);
- } else {
- state = const AuthState(error: 'Codice agente o password errati', isInitialized: true);
- }
- } catch (e) {
- state = AuthState(error: e.toString(), isInitialized: true);
- }
- }
- Future<void> initialize({
- required String codAgente,
- required String password,
- String? ragioneSociale,
- required String url,
- }) async {
- state = const AuthState(isLoading: true);
- try {
- final authService = ref.read(authServiceProvider);
- await authService.initializeAgent(
- codAgente: codAgente,
- pwd: password,
- ragioneSociale: ragioneSociale,
- url: url,
- );
- final agente = await authService.login(codAgente, password);
- state = AuthState(agente: agente, isInitialized: true);
- } catch (e) {
- state = AuthState(error: e.toString(), isInitialized: true);
- }
- }
- void logout() {
- state = const AuthState(isInitialized: true);
- }
- void resetToInit() {
- state = const AuthState(isInitialized: false);
- }
- }
- final authProvider = NotifierProvider<AuthNotifier, AuthState>(AuthNotifier.new);
|