63 lines
1.7 KiB
Dart
63 lines
1.7 KiB
Dart
import 'package:get/get.dart';
|
|
import 'package:sidak_desa_mobile/presentation/views/main_screen.dart';
|
|
|
|
import '../../data/fetch/auth_api.dart';
|
|
import '../../data/shared/auth_storage.dart';
|
|
import '../../utils/device_id.dart';
|
|
|
|
class LoginController extends GetxController {
|
|
final AuthApi _api = AuthApi();
|
|
final AuthStorage _storage = AuthStorage();
|
|
|
|
final isLoading = false.obs;
|
|
final errorMessage = RxnString();
|
|
|
|
Future<void> login({required String email, required String password}) async {
|
|
errorMessage.value = null;
|
|
|
|
if (email.isEmpty || password.isEmpty) {
|
|
errorMessage.value = 'Email dan password wajib diisi';
|
|
return;
|
|
}
|
|
|
|
isLoading.value = true;
|
|
|
|
try {
|
|
// ✅ Ambil device ID
|
|
final deviceId = await DeviceIdUtil.getDeviceId();
|
|
|
|
if (deviceId == null || deviceId.isEmpty) {
|
|
throw Exception('Device ID tidak ditemukan');
|
|
}
|
|
|
|
// ✅ Hit API login (pastikan kirim device_id)
|
|
final response = await _api.login(
|
|
email: email,
|
|
password: password,
|
|
deviceId: deviceId,
|
|
);
|
|
|
|
// ✅ Simpan user + token
|
|
await _storage.saveUser(response);
|
|
|
|
// ✅ Pindah ke halaman utama
|
|
Get.offAll(() => MainScreen());
|
|
} catch (e) {
|
|
final message = e.toString().replaceFirst('Exception: ', '');
|
|
|
|
errorMessage.value = message;
|
|
|
|
// 🔥 Custom handling dari backend
|
|
if (message.contains('device lain')) {
|
|
Get.snackbar('Akses Ditolak', message);
|
|
} else if (message.contains('Email atau password salah')) {
|
|
Get.snackbar('Login Gagal', message);
|
|
} else {
|
|
Get.snackbar('Error', message);
|
|
}
|
|
} finally {
|
|
isLoading.value = false;
|
|
}
|
|
}
|
|
}
|