97 lines
2.6 KiB
Dart
97 lines
2.6 KiB
Dart
import 'dart:convert';
|
|
import 'package:shared_preferences/shared_preferences.dart';
|
|
import 'package:http/http.dart' as http;
|
|
import '../variable/globals.dart' as globals;
|
|
import 'dart:io';
|
|
|
|
class AuthService {
|
|
// Login with username and password
|
|
Future<bool> login(String username, String password) async {
|
|
final url = Uri.parse("${globals.api}/token");
|
|
|
|
try {
|
|
final response = await http.post(
|
|
url,
|
|
headers: {
|
|
'accept': 'application/json',
|
|
'Content-Type': 'application/x-www-form-urlencoded',
|
|
},
|
|
body: {
|
|
"username": username,
|
|
"password": password,
|
|
},
|
|
);
|
|
|
|
if (response.statusCode == 200 || response.statusCode == 201) {
|
|
final prefs = await SharedPreferences.getInstance();
|
|
final cookies = response.headers["set-cookie"]?.split(";") ?? [];
|
|
|
|
for (final cookie in cookies) {
|
|
final cookieParts = cookie.split(",");
|
|
for (final part in cookieParts) {
|
|
final keyValue = part.split("=");
|
|
if (keyValue.length == 2 && keyValue[0] == "access_token") {
|
|
prefs.setString("access_token", keyValue[1]);
|
|
}
|
|
}
|
|
}
|
|
return true;
|
|
} else {
|
|
return false;
|
|
}
|
|
} catch (e) {
|
|
print("Login error: $e");
|
|
return false;
|
|
}
|
|
}
|
|
|
|
// Logout
|
|
Future<void> logout() async {
|
|
final prefs = await SharedPreferences.getInstance();
|
|
await prefs.remove("access_token");
|
|
}
|
|
|
|
Future<bool> isLoggedIn() async {
|
|
final prefs = await SharedPreferences.getInstance();
|
|
final accessToken = prefs.getString("access_token");
|
|
|
|
if (accessToken == null || accessToken.isEmpty) {
|
|
print("No access token found.");
|
|
return false;
|
|
}
|
|
|
|
print("Checking token validity...");
|
|
var url = Uri.parse("${globals.api}/token");
|
|
|
|
try {
|
|
final response = await http.get(
|
|
url,
|
|
headers: {
|
|
HttpHeaders.cookieHeader: "access_token=$accessToken",
|
|
"Content-Type": "application/json",
|
|
},
|
|
);
|
|
|
|
if (response.statusCode == 200) {
|
|
print("Token is valid.");
|
|
return true;
|
|
} else {
|
|
print("Token is invalid. Status code: ${response.statusCode}");
|
|
await prefs.remove("access_token"); // Clear invalid token
|
|
return false;
|
|
}
|
|
} catch (e) {
|
|
print("Error while checking token: $e");
|
|
return false;
|
|
}
|
|
}
|
|
|
|
// Get stored access token
|
|
Future<String?> getAccessToken() async {
|
|
final prefs = await SharedPreferences.getInstance();
|
|
return prefs.getString("access_token");
|
|
}
|
|
|
|
// Login with Google
|
|
}
|