Add functional login page

This commit is contained in:
2024-12-20 23:30:05 +01:00
parent f530a52e9d
commit d5d5bc6e5d
13 changed files with 356 additions and 144 deletions

View File

@@ -1,24 +1,21 @@
import 'dart:convert';
import 'dart:developer';
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:http/http.dart' as http;
import 'package:path_provider/path_provider.dart'; // For cache storage
import 'package:file/memory.dart';
import 'sheet.dart';
class ApiClient {
final String baseUrl =
'http://localhost:8080/api'; // Replace with your API base URL
String? _token; // Holds the JWT token after login
final String baseUrl;
String? token;
/// Checks if the user is authenticated
bool get isAuthenticated => _token != null;
ApiClient({required this.baseUrl, this.token});
/// Login and store the JWT token
Future<bool> login(String username, String password) async {
print("Logging in...");
log("Logging in...");
try {
final url = '$baseUrl/login';
final response = await http.post(
@@ -31,22 +28,22 @@ class ApiClient {
);
if (response.statusCode == 200) {
_token = jsonDecode(response.body);
print('Login successful, token: $_token');
token = jsonDecode(response.body);
log('Login successful');
return true;
} else {
print('Login failed: ${response.statusCode}, ${response.body}');
log('Login failed: ${response.statusCode}, ${response.body}');
}
} catch (e) {
print('Error during login: $e');
log('Error during login: $e');
}
return false;
}
/// Logout and clear the token
void logout() {
_token = null;
print('Logged out successfully.');
token = null;
log('Logged out successfully.');
}
/// Make a GET request
@@ -54,7 +51,7 @@ class ApiClient {
try {
final url = '$baseUrl$endpoint';
final headers = {
'Authorization': 'Bearer $_token',
'Authorization': 'Bearer $token',
if (!isBinary) 'Content-Type': 'application/json',
};
@@ -63,10 +60,10 @@ class ApiClient {
if (response.statusCode == 200) {
return response;
} else {
print('GET request failed: ${response.statusCode} ${response.body}');
log('GET request failed: ${response.statusCode} ${response.body}');
}
} catch (e) {
print('Error during GET request: $e');
log('Error during GET request: $e');
}
return null;
}
@@ -77,7 +74,7 @@ class ApiClient {
try {
final url = '$baseUrl$endpoint';
final headers = {
'Authorization': 'Bearer $_token',
'Authorization': 'Bearer $token',
'Content-Type': 'application/json',
};
@@ -90,10 +87,10 @@ class ApiClient {
if (response.statusCode == 200 || response.statusCode == 201) {
return response;
} else {
print('POST request failed: ${response.statusCode} ${response.body}');
log('POST request failed: ${response.statusCode} ${response.body}');
}
} catch (e) {
print('Error during POST request: $e');
log('Error during POST request: $e');
}
return null;
}
@@ -103,7 +100,7 @@ class ApiClient {
try {
final url = '$baseUrl$endpoint';
final headers = {
'Authorization': 'Bearer $_token',
'Authorization': 'Bearer $token',
'Content-Type': 'application/x-www-form-urlencoded',
};
@@ -116,11 +113,10 @@ class ApiClient {
if (response.statusCode == 200 || response.statusCode == 201) {
return response;
} else {
print(
'POST Form Data request failed: ${response.statusCode} ${response.body}');
log('POST Form Data request failed: ${response.statusCode} ${response.body}');
}
} catch (e) {
print('Error during POST Form Data request: $e');
log('Error during POST Form Data request: $e');
}
return null;
}
@@ -133,27 +129,24 @@ class ApiClient {
"sort_by": sortBy,
};
print("doing post...");
final response = await postFormData("/sheets", jsonEncode(bodyFormData));
print("got response...");
if (response == null) {
print("Empty reponse");
return List.empty();
}
if (response.statusCode == 200) {
final data = jsonDecode(response.body);
print("Data: $data");
log("Data: $data");
return (data['rows'] as List<dynamic>)
.map((sheet) => Sheet.fromJson(sheet as Map<String, dynamic>))
.toList();
} else {
print('Failed to fetch sheets with status: ${response.statusCode}');
print('Response: ${response.body}');
log('Failed to fetch sheets with status: ${response.statusCode}');
log('Response: ${response.body}');
}
} catch (e) {
print('Error during fetching sheets: $e');
log('Error during fetching sheets: $e');
}
return List.empty();
@@ -163,42 +156,35 @@ class ApiClient {
try {
// Get the cache directory
print("Creating cache dir...");
// final cacheDir = kIsWeb
// ? await MemoryFileSystem().systemTempDirectory.createTemp('cache')
// : await getTemporaryDirectory();
final cacheDir = await getTemporaryDirectory();
final cachedPdfPath = '${cacheDir.path}/$sheetUuid.pdf';
print("cache dir created");
// Check if the file already exists in the cache
final cachedFile = File(cachedPdfPath);
print("file created: $cachedFile");
if (await cachedFile.exists()) {
print("PDF found in cache: $cachedPdfPath");
log("PDF found in cache: $cachedPdfPath");
return cachedFile;
}
// Make the authenticated API call
print("getting response");
final response = await this.get('/sheet/pdf/$sheetUuid', isBinary: true);
print("got response");
if (response != null && response.statusCode == 200) {
// Save the fetched file to the cache
//
print("writing file...: $cachedFile");
await cachedFile.writeAsBytes(response.bodyBytes);
print("PDF downloaded and cached at: $cachedPdfPath");
log("PDF downloaded and cached at: $cachedPdfPath");
return cachedFile;
} else {
print("Failed to fetch PDF from API. Status: ${response?.statusCode}");
log("Failed to fetch PDF from API. Status: ${response?.statusCode}");
}
} catch (e) {
print("Error fetching PDF: $e");
log("Error fetching PDF: $e");
}
return null;