53 lines
1.8 KiB
Dart
53 lines
1.8 KiB
Dart
import 'dart:convert';
|
|
import 'package:http/http.dart' as http;
|
|
import 'package:marco/helpers/services/storage/local_storage.dart';
|
|
import 'package:marco/controller/permission_controller.dart';
|
|
import 'package:get/get.dart';
|
|
|
|
class AuthService {
|
|
static bool isLoggedIn = false;
|
|
|
|
static Future<Map<String, String>?> loginUser(Map<String, dynamic> data) async {
|
|
try {
|
|
final response = await http.post(
|
|
Uri.parse('https://stageapi.marcoaiot.com/api/auth/login'),
|
|
headers: {'Content-Type': 'application/json'},
|
|
body: jsonEncode(data),
|
|
);
|
|
|
|
if (response.statusCode == 200) {
|
|
isLoggedIn = true;
|
|
|
|
// Parse the response to get the JWT and refresh tokens
|
|
final responseData = jsonDecode(response.body);
|
|
|
|
// Adjusted for the actual response structure
|
|
final jwtToken = responseData['data']['token']; // Ensure this matches your actual response
|
|
|
|
// Save the JWT token in local storage
|
|
await LocalStorage.setJwtToken(jwtToken);
|
|
print("JWT Token: $jwtToken");
|
|
|
|
// Optionally save refresh token if available
|
|
final refreshToken = responseData['data']['refreshToken'];
|
|
if (refreshToken != null) {
|
|
await LocalStorage.setRefreshToken(refreshToken);
|
|
print("Refresh Token: $refreshToken");
|
|
}
|
|
|
|
// Save the login state in local storage
|
|
await LocalStorage.setLoggedInUser(true);
|
|
Get.put(PermissionController());
|
|
// Return null to indicate success
|
|
return null;
|
|
} else if (response.statusCode == 401) {
|
|
return {"password": "Invalid email or password"};
|
|
} else {
|
|
return {"error": "Something went wrong. Please try again."};
|
|
}
|
|
} catch (e) {
|
|
return {"error": "Network error. Please check your connection."};
|
|
}
|
|
}
|
|
}
|