63 lines
1.9 KiB
Dart
63 lines
1.9 KiB
Dart
import 'package:dio/dio.dart';
|
|
import '../config/api_config.dart';
|
|
|
|
class AuthService {
|
|
final Dio _dio = Dio(BaseOptions(
|
|
baseUrl: ApiConfig.baseUrl,
|
|
connectTimeout: const Duration(seconds: 15),
|
|
receiveTimeout: const Duration(seconds: 15),
|
|
// You can add headers here if needed:
|
|
// headers: {'Accept': 'application/json'},
|
|
));
|
|
|
|
/// Calls /api/user/login with login_id and password
|
|
Future<Map<String, dynamic>> login(String loginId, String password) async {
|
|
try {
|
|
final response = await _dio.post('/user/login', data: {
|
|
'login_id': loginId,
|
|
'password': password,
|
|
});
|
|
|
|
// Ensure we return a Map<String, dynamic>
|
|
if (response.data is Map) {
|
|
return Map<String, dynamic>.from(response.data);
|
|
} else {
|
|
return {
|
|
'success': false,
|
|
'message': 'Invalid response from server',
|
|
};
|
|
}
|
|
} on DioException catch (e) {
|
|
// Try to extract message from server response
|
|
dynamic respData = e.response?.data;
|
|
String message = 'Login failed';
|
|
if (respData is Map && respData['message'] != null) {
|
|
message = respData['message'].toString();
|
|
} else if (e.message != null) {
|
|
message = e.message!;
|
|
}
|
|
return {
|
|
'success': false,
|
|
'message': message,
|
|
};
|
|
} catch (e) {
|
|
return {
|
|
'success': false,
|
|
'message': e.toString(),
|
|
};
|
|
}
|
|
}
|
|
|
|
/// Optional: logout (if you have logout endpoint)
|
|
Future<Map<String, dynamic>> logout(String token) async {
|
|
try {
|
|
final Dio dio = Dio(BaseOptions(baseUrl: ApiConfig.baseUrl));
|
|
dio.options.headers['Authorization'] = 'Bearer $token';
|
|
final response = await dio.post('/user/logout');
|
|
return Map<String, dynamic>.from(response.data ?? {'success': true});
|
|
} catch (e) {
|
|
return {'success': false, 'message': e.toString()};
|
|
}
|
|
}
|
|
}
|