2025-01-22 23:33:09 +01:00

261 lines
7.7 KiB
Dart

import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'dart:io';
//import 'MyHomePage.dart';
import 'pages/ListItemMenu.dart';
import 'pages/AddProfile.dart';
import 'classes/alert.dart';
import 'variable/globals.dart' as globals;
import 'package:permission_handler/permission_handler.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: LoginDemo(),
);
}
}
class LoginDemo extends StatefulWidget {
@override
_LoginDemoState createState() => _LoginDemoState();
}
class _LoginDemoState extends State<LoginDemo> with ShowAlertDialog {
TextEditingController inputPseudo = TextEditingController();
TextEditingController inputPassword = TextEditingController();
Future<void> _login(BuildContext context) async {
final url = Uri.parse("${globals.api}/token");
final pseudo = inputPseudo.text;
final password = inputPassword.text;
print("Attempting login");
if (pseudo.isEmpty || password.isEmpty) {
showAlertDialog(context, "Erreur", "Champ vide");
return;
}
print("Request URL: $url");
try {
final response = await http.post(
url,
headers: {
'accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
},
body: {
"username": pseudo,
"password": password,
},
);
print("Response status code: ${response.statusCode}");
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]);
}
}
}
Navigator.push(
context,
MaterialPageRoute(builder: (_) => ListItemMenu()),
);
} else {
_handleErrorResponse(context, response.statusCode);
}
} catch (e) {
showAlertDialog(context, "Erreur", e.toString());
}
}
void _handleErrorResponse(BuildContext context, int statusCode) {
final errorMessages = {
400: "Requête mal construite",
406: "Mot de passe incorrect",
404: "Utilisateur inconnu",
403: "Utilisateur désactivé",
410: "Token invalide",
500: "Problème interne du serveur",
};
final errorMessage =
errorMessages[statusCode] ?? "Problème d'authentification inconnu";
showAlertDialog(context, "Erreur serveur", errorMessage);
}
void start() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
var access_token = prefs.getString("access_token") ?? "";
print("Get access token");
if (access_token.isNotEmpty) {
print("Appel HTTP");
var urlToken = Uri.parse("${globals.api}/token");
var responseToken = await http.get(urlToken,
headers: {HttpHeaders.cookieHeader: 'access_token: ${access_token}'});
print(responseToken.statusCode);
if (responseToken.statusCode == 200) {
print("route to item list");
Navigator.push(
context, MaterialPageRoute(builder: (_) => ListItemMenu()));
} else {
prefs.remove("access_token");
}
}
}
@override
void initState() {
_checkLocationPermission();
start();
super.initState();
}
Future<void> _checkLocationPermission() async {
PermissionStatus status = await Permission.location.status;
if (status.isGranted) {
print("Location permission granted");
} else if (status.isDenied) {
print("Location permission denied");
_requestLocationPermission();
} else if (status.isPermanentlyDenied) {
print("Location permission permanently denied");
openAppSettings();
}
}
// Request location permission
Future<void> _requestLocationPermission() async {
PermissionStatus status = await Permission.location.request();
if (status.isGranted) {
print("Location permission granted");
} else if (status.isDenied) {
print("Location permission denied");
} else if (status.isPermanentlyDenied) {
print("Location permission permanently denied");
openAppSettings();
}
}
// Open app settings to allow user to grant permission manually
Future<void> _openAppSettings() async {
bool opened = await openAppSettings();
if (opened) {
print("App settings opened");
} else {
print("Failed to open app settings");
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
title: Text("Login Page"),
backgroundColor: Colors.blue,
foregroundColor: Colors.white,
),
body: SingleChildScrollView(
child: Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.only(top: 60.0),
child: Center(
child: Container(
width: 200,
height: 150,
decoration: BoxDecoration(
color: Colors.red,
borderRadius: BorderRadius.circular(50.0)),
child: Image.asset('./images/flutter.png')),
),
),
Padding(
//padding: const EdgeInsets.only(left:15.0,right: 15.0,top:0,bottom: 0),
padding: EdgeInsets.symmetric(horizontal: 15),
child: TextField(
controller: inputPseudo,
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Pseudo',
hintText: 'Enter pseudo existent'),
),
),
Padding(
padding: const EdgeInsets.only(
left: 15.0, right: 15.0, top: 15, bottom: 0),
//padding: EdgeInsets.symmetric(horizontal: 15),
child: TextField(
controller: inputPassword,
obscureText: true,
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Password',
hintText: 'Enter secure password'),
),
),
TextButton(
onPressed: () {
//TODO FORGOT PASSWORD SCREEN GOES HERE
},
child: Text(
'Forgot Password',
style: TextStyle(color: Colors.blue, fontSize: 15),
),
),
Container(
height: 50,
width: 250,
decoration: BoxDecoration(
color: Colors.blue, borderRadius: BorderRadius.circular(20)),
child: TextButton(
onPressed: () {
_login(context);
},
child: Text(
'Login',
style: TextStyle(color: Colors.white, fontSize: 25),
),
),
),
SizedBox(
height: 130,
),
InkWell(
child: Text('New User? Create Account'),
onTap: () {
Navigator.push(
context, MaterialPageRoute(builder: (_) => AddProfile()));
})
],
),
),
);
}
}