auth_provider.dart 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. import 'package:flutter_riverpod/flutter_riverpod.dart';
  2. import '../../core/constants.dart';
  3. import '../../database/database.dart';
  4. import 'database_provider.dart';
  5. import '../../services/auth_service.dart';
  6. import 'sync_provider.dart';
  7. class AuthState {
  8. final Agente? agente;
  9. final bool isLoading;
  10. final bool isInitialized;
  11. final String? error;
  12. const AuthState({this.agente, this.isLoading = false, this.isInitialized = false, this.error});
  13. bool get isLoggedIn => agente != null;
  14. }
  15. final authServiceProvider = Provider<AuthService>((ref) {
  16. return AuthService(
  17. ref.read(agentiDaoProvider),
  18. ref.read(apiServiceProvider),
  19. ref.read(parametriDaoProvider),
  20. );
  21. });
  22. class AuthNotifier extends Notifier<AuthState> {
  23. @override
  24. AuthState build() {
  25. _checkInitialized();
  26. return const AuthState();
  27. }
  28. Future<void> _checkInitialized() async {
  29. final authService = ref.read(authServiceProvider);
  30. final initialized = await authService.isInitialized();
  31. state = AuthState(isInitialized: initialized);
  32. }
  33. Future<void> login(String code, String password, String url) async {
  34. state = const AuthState(isLoading: true);
  35. try {
  36. await ref.read(parametriDaoProvider).set(AppConstants.kUrlParam, url);
  37. final authService = ref.read(authServiceProvider);
  38. final agente = await authService.login(code, password);
  39. if (agente != null) {
  40. state = AuthState(agente: agente, isInitialized: true);
  41. } else {
  42. state = const AuthState(error: 'Codice agente o password errati', isInitialized: true);
  43. }
  44. } catch (e) {
  45. state = AuthState(error: e.toString(), isInitialized: true);
  46. }
  47. }
  48. Future<void> initialize({
  49. required String codAgente,
  50. required String password,
  51. String? ragioneSociale,
  52. required String url,
  53. }) async {
  54. state = const AuthState(isLoading: true);
  55. try {
  56. final authService = ref.read(authServiceProvider);
  57. await authService.initializeAgent(
  58. codAgente: codAgente,
  59. pwd: password,
  60. ragioneSociale: ragioneSociale,
  61. url: url,
  62. );
  63. final agente = await authService.login(codAgente, password);
  64. state = AuthState(agente: agente, isInitialized: true);
  65. } catch (e) {
  66. state = AuthState(error: e.toString(), isInitialized: true);
  67. }
  68. }
  69. void logout() {
  70. state = const AuthState(isInitialized: true);
  71. }
  72. void resetToInit() {
  73. state = const AuthState(isInitialized: false);
  74. }
  75. }
  76. final authProvider = NotifierProvider<AuthNotifier, AuthState>(AuthNotifier.new);