110 lines
2.9 KiB
Dart
110 lines
2.9 KiB
Dart
import 'package:flutter/material.dart';
|
|
import 'package:get/get.dart';
|
|
import 'package:firebase_auth/firebase_auth.dart';
|
|
import '../../../routes/app_pages.dart';
|
|
|
|
class LoginController extends GetxController {
|
|
final emailController = TextEditingController();
|
|
final passwordController = TextEditingController();
|
|
|
|
final isPasswordVisible = false.obs;
|
|
final isLoading = false.obs;
|
|
|
|
final _auth = FirebaseAuth.instance;
|
|
|
|
@override
|
|
void onClose() {
|
|
emailController.dispose();
|
|
passwordController.dispose();
|
|
super.onClose();
|
|
}
|
|
|
|
void togglePasswordVisibility() =>
|
|
isPasswordVisible.value = !isPasswordVisible.value;
|
|
|
|
Future<void> login() async {
|
|
if (emailController.text.isEmpty || passwordController.text.isEmpty) {
|
|
Get.snackbar(
|
|
'Perhatian',
|
|
'Email dan password harus diisi!',
|
|
snackPosition: SnackPosition.TOP,
|
|
backgroundColor: Colors.red.shade100,
|
|
);
|
|
return;
|
|
}
|
|
|
|
try {
|
|
isLoading.value = true;
|
|
|
|
await _auth.signInWithEmailAndPassword(
|
|
email: emailController.text.trim(),
|
|
password: passwordController.text.trim(),
|
|
);
|
|
|
|
Get.offAllNamed(Routes.NAVBAR);
|
|
} on FirebaseAuthException catch (e) {
|
|
String message = 'Login gagal, coba lagi.';
|
|
if (e.code == 'user-not-found') {
|
|
message = 'Email tidak terdaftar.';
|
|
} else if (e.code == 'wrong-password') {
|
|
message = 'Password salah.';
|
|
} else if (e.code == 'invalid-email') {
|
|
message = 'Format email tidak valid.';
|
|
} else if (e.code == 'user-disabled') {
|
|
message = 'Akun dinonaktifkan.';
|
|
}
|
|
|
|
Get.snackbar(
|
|
'Login Gagal',
|
|
message,
|
|
snackPosition: SnackPosition.TOP,
|
|
backgroundColor: Colors.red.shade100,
|
|
);
|
|
} finally {
|
|
isLoading.value = false;
|
|
}
|
|
}
|
|
|
|
Future<void> lupaPassword() async {
|
|
if (emailController.text.isEmpty) {
|
|
Get.snackbar(
|
|
'Perhatian',
|
|
'Masukkan email terlebih dahulu!',
|
|
snackPosition: SnackPosition.TOP,
|
|
backgroundColor: Colors.orange.shade100,
|
|
);
|
|
return;
|
|
}
|
|
|
|
try {
|
|
await _auth.sendPasswordResetEmail(email: emailController.text.trim());
|
|
|
|
Get.snackbar(
|
|
'Berhasil',
|
|
'Link reset password telah dikirim ke ${emailController.text.trim()}',
|
|
snackPosition: SnackPosition.TOP,
|
|
backgroundColor: Colors.green.shade100,
|
|
duration: const Duration(seconds: 4),
|
|
);
|
|
} on FirebaseAuthException catch (e) {
|
|
String message = 'Gagal mengirim email reset.';
|
|
if (e.code == 'user-not-found') {
|
|
message = 'Email tidak terdaftar.';
|
|
} else if (e.code == 'invalid-email') {
|
|
message = 'Format email tidak valid.';
|
|
}
|
|
|
|
Get.snackbar(
|
|
'Gagal',
|
|
message,
|
|
snackPosition: SnackPosition.TOP,
|
|
backgroundColor: Colors.red.shade100,
|
|
);
|
|
}
|
|
}
|
|
|
|
void goToRegister() {
|
|
Get.toNamed(Routes.REGISTER);
|
|
}
|
|
}
|