74 lines
2.4 KiB
Dart
74 lines
2.4 KiB
Dart
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
|
import 'package:onesignal_flutter/onesignal_flutter.dart';
|
|
|
|
import '../../repositories/auth_repository.dart';
|
|
import '../../services/supabase_auth_service.dart'; // Dibutuhkan untuk DI di authRepositoryProvider
|
|
import 'auth_state.dart';
|
|
|
|
// ── Provider ────────────────────────────────────────────────────
|
|
// Provider untuk AuthRepository yang disuntik dengan SupabaseAuthService
|
|
final authRepositoryProvider = Provider<AuthRepository>(
|
|
(ref) => AuthRepository(SupabaseAuthService()),
|
|
);
|
|
|
|
final authProvider = StateNotifierProvider<AuthNotifier, AuthState>(
|
|
(ref) => AuthNotifier(ref.read(authRepositoryProvider)),
|
|
);
|
|
|
|
// ── Notifier ────────────────────────────────────────────────────
|
|
class AuthNotifier extends StateNotifier<AuthState> {
|
|
final AuthRepository _repo;
|
|
|
|
AuthNotifier(this._repo) : super(const AuthIdle());
|
|
|
|
Future<void> checkAuthStatus() async {
|
|
state = const AuthLoading();
|
|
try {
|
|
// Gunakan _repo.checkSession() lewat DI — tidak perlu buat instance baru
|
|
final user = await _repo.checkSession();
|
|
|
|
if (user != null) {
|
|
OneSignal.login(user.id);
|
|
state = AuthSuccess(user);
|
|
} else {
|
|
state = const AuthIdle();
|
|
}
|
|
} catch (e) {
|
|
state = const AuthIdle();
|
|
}
|
|
}
|
|
|
|
Future<void> login(String email, String password) async {
|
|
state = const AuthLoading();
|
|
try {
|
|
final user = await _repo.login(email, password);
|
|
OneSignal.login(user.id);
|
|
state = AuthSuccess(user);
|
|
} catch (e) {
|
|
state = AuthError(e.toString().replaceFirst('Exception: ', ''));
|
|
}
|
|
}
|
|
|
|
Future<void> register(
|
|
String name, String email, String password, String claimCode) async {
|
|
state = const AuthLoading();
|
|
try {
|
|
final user = await _repo.register(name, email, password, claimCode);
|
|
OneSignal.login(user.id);
|
|
state = AuthSuccess(user);
|
|
} catch (e) {
|
|
state = AuthError(e.toString().replaceFirst('Exception: ', ''));
|
|
}
|
|
}
|
|
|
|
Future<void> logout() async {
|
|
OneSignal.logout();
|
|
await _repo.logout();
|
|
state = const AuthIdle();
|
|
}
|
|
|
|
void resetError() {
|
|
if (state is AuthError) state = const AuthIdle();
|
|
}
|
|
}
|