65 lines
1.8 KiB
Dart
65 lines
1.8 KiB
Dart
import 'dart:convert';
|
|
import 'package:http/http.dart' as http;
|
|
import 'package:uwine_portal/entities/auth_token.dart';
|
|
|
|
class ApiService {
|
|
static const String baseUrl = 'http://192.168.0.11:5000'; // cambia qui
|
|
|
|
// Token memorizzato in memoria (per sessione)
|
|
static String? _token;
|
|
|
|
static String? get token => _token;
|
|
|
|
// Login con Basic Auth e salvataggio token
|
|
static Future<String> login(String username, String password) async {
|
|
final url = Uri.parse('$baseUrl/User/login');
|
|
|
|
// Header con Basic Auth
|
|
String basicAuth =
|
|
'Basic ' + base64Encode(utf8.encode('$username:$password'));
|
|
|
|
final response = await http.get(
|
|
url,
|
|
headers: {
|
|
'Authorization': basicAuth,
|
|
'Accept': 'application/json',
|
|
},
|
|
);
|
|
|
|
if (response.statusCode == 200) {
|
|
final data = jsonDecode(response.body);
|
|
_token = data['access_token']; // salva il token in memoria
|
|
AuthToken.instance.saveToken(_token!);
|
|
return '${response.statusCode}';
|
|
} else {
|
|
throw Exception(
|
|
'Login fallito: ${response.statusCode} - ${response.body}');
|
|
}
|
|
}
|
|
|
|
static Future<dynamic> checkLogin() async {
|
|
final token = AuthToken.instance.token;
|
|
if (token == null) {
|
|
throw Exception('Token non disponibile. Effettua il login prima.');
|
|
}
|
|
|
|
final url = Uri.parse('$baseUrl/Test/cklogin');
|
|
final response = await http.get(
|
|
url,
|
|
headers: {
|
|
'Authorization': 'Bearer $token',
|
|
'Accept': 'application/json',
|
|
},
|
|
);
|
|
|
|
if (response.statusCode == 200) {
|
|
final object = jsonDecode(response.body);
|
|
print('Risposta cklogin: $object'); // stampa in console
|
|
return object;
|
|
} else {
|
|
throw Exception(
|
|
'Errore checkLogin: ${response.statusCode} - ${response.body}');
|
|
}
|
|
}
|
|
}
|