add logout button + logout function

This commit is contained in:
Valentin CZERYBA 2024-12-30 23:33:51 +01:00
parent 8adcd80306
commit ef87a8bfe2
2 changed files with 76 additions and 1 deletions

View File

@ -1,7 +1,75 @@
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:http/http.dart' as http;
import 'dart:io';
import 'alert.dart';
import '../variable/globals.dart' as globals;
import '../main.dart';
class MyDrawer extends StatelessWidget with ShowAlertDialog {
Future<void> logout(BuildContext context) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
var accessToken = prefs.getString("access_token") ?? "";
if (accessToken.isNotEmpty) {
var url = Uri.parse("${globals.api}/token");
try {
var response = await http.delete(url, headers: {
"Content-Type": "application/json",
HttpHeaders.cookieHeader: "access_token=${accessToken}"
});
print("Status code logout ${response.statusCode}");
if (response.statusCode == 200) {
await prefs.setString("access_token", ""); // Clear the token
Navigator.pushReplacement(
context, MaterialPageRoute(builder: (_) => LoginDemo()));
} else {
switch (response.statusCode) {
case 400:
print("Bad Request: Please check your input.");
showAlertDialog(
context, "Bad Request", "Please check your input.");
break;
case 401:
print("Unauthorized: Invalid credentials.");
showAlertDialog(context, "Unauthorized", "Invalid credentials.");
break;
case 403:
print("Forbidden: You don't have permission.");
showAlertDialog(context, "Forbidden",
"You don't have permission to access this.");
break;
case 404:
print("Not Found: The resource was not found.");
showAlertDialog(
context, "Not Found", "The resource was not found.");
break;
case 500:
print("Server Error: Something went wrong on the server.");
showAlertDialog(context, "Server Error",
"Something went wrong on the server.");
break;
default:
print("Unexpected Error: ${response.statusCode}");
showAlertDialog(context, "Error", "Unexpected Error occurred.");
break;
}
}
} catch (e) {
print("Error: $e");
showAlertDialog(
context, "Error", "An error occurred. Please try again.");
}
} else {
showAlertDialog(context, "Error", "Token invalide.");
}
}
@override
Widget build(BuildContext context) {
return Drawer(
@ -44,6 +112,14 @@ class MyDrawer extends StatelessWidget with ShowAlertDialog {
context, 'About', "Version 0.0.1"); // Close the drawer
},
),
ListTile(
leading: Icon(Icons.logout),
title: Text('Log out'),
onTap: () async {
logout(context);
// Close the drawer
},
),
],
),
);

View File

@ -15,7 +15,6 @@ import '../variable/globals.dart' as globals;
import 'package:permission_handler/permission_handler.dart';
import "Camera.dart";
import 'package:camera/camera.dart';
import 'package:textfield_tags/textfield_tags.dart';
void main() {
initializeDateFormatting("fr_FR", null).then((_) => runApp(const MyApp()));