84 lines
2.2 KiB
Dart
84 lines
2.2 KiB
Dart
import 'dart:convert';
|
|
import 'package:http/http.dart' as http;
|
|
|
|
import '../../core/api/api.dart';
|
|
import '../model/user_model.dart';
|
|
|
|
class AuthApi {
|
|
Future<UserModel> login({
|
|
required String email,
|
|
required String password,
|
|
required String deviceId,
|
|
}) async {
|
|
final url = Uri.parse('${Apiconfig.baseUrl}/api/mobile/login');
|
|
|
|
print("FULL URL: $url");
|
|
|
|
final response = await http.post(
|
|
url,
|
|
headers: {
|
|
'Accept': 'application/json',
|
|
'Content-Type': 'application/x-www-form-urlencoded',
|
|
},
|
|
body: {
|
|
'email': email,
|
|
'password': password,
|
|
'device_id': deviceId,
|
|
},
|
|
);
|
|
|
|
print("STATUS CODE: ${response.statusCode}");
|
|
print("RAW BODY: ${response.body}");
|
|
|
|
// 🔥 Antisipasi server mati / tidak merespon JSON
|
|
if (response.body.isEmpty) {
|
|
throw Exception("Server tidak merespon");
|
|
}
|
|
|
|
// 🔥 Cegah error HTML (route salah / 500 Laravel)
|
|
if (response.body.startsWith('<!DOCTYPE html>')) {
|
|
throw Exception(
|
|
"Server mengembalikan HTML. Cek URL atau route Laravel.");
|
|
}
|
|
|
|
final data = jsonDecode(response.body);
|
|
|
|
// ✅ SUKSES
|
|
if (response.statusCode == 200 && data['ok'] == true) {
|
|
final userJson = data['data'];
|
|
|
|
// 🔥 inject token ke user model (penting!)
|
|
userJson['token'] = data['token'];
|
|
|
|
// 🔥 Fix URL foto
|
|
if (userJson['url_photo'] != null &&
|
|
userJson['url_photo'].toString().isNotEmpty &&
|
|
!userJson['url_photo'].toString().startsWith('http')) {
|
|
userJson['url_photo'] =
|
|
"${Apiconfig.baseUrl}/storage/${userJson['url_photo']}";
|
|
}
|
|
|
|
print("FINAL PHOTO URL: ${userJson['url_photo']}");
|
|
print("TOKEN: ${data['token']}");
|
|
|
|
return UserModel.fromJson(userJson);
|
|
}
|
|
|
|
// ❌ HANDLE ERROR LEBIH SPESIFIK
|
|
if (response.statusCode == 401) {
|
|
throw Exception("Email atau password salah");
|
|
}
|
|
|
|
if (response.statusCode == 403) {
|
|
throw Exception(data['message'] ??
|
|
"Akun sudah digunakan di device lain");
|
|
}
|
|
|
|
if (response.statusCode == 422) {
|
|
throw Exception("Validasi gagal");
|
|
}
|
|
|
|
// fallback
|
|
throw Exception(data['message'] ?? 'Login gagal');
|
|
}
|
|
} |