bio login

This commit is contained in:
usbe committed 2025-07-11 15:07:36 +02:00
1 parent 6acec998bc
commit 0ba83858fe
12 files changed
+522 -80

No files matched your search

+50 -17
View File
@@ -1,26 +1,59 @@
class auth_token {
// Istanza privata statica
static final auth_token _instance = auth_token._internal();
import 'package:flutter/foundation.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:local_auth/local_auth.dart';
import 'package:device_info_plus/device_info_plus.dart';
// Variabile per salvare il token
class AuthToken {
static final AuthToken _instance = AuthToken._internal();
static AuthToken get instance => _instance;
AuthToken._internal();
final _storage = const FlutterSecureStorage();
String? _token;
// Costruttore privato
auth_token._internal();
// Factory per ritornare sempre la stessa istanza
factory auth_token() {
return _instance;
}
// Getter e setter per il token
String? get token => _token;
set token(String? value) {
_token = value;
Future<bool> isMobilePlatform() async {
if (kIsWeb) return false;
final deviceInfo = DeviceInfoPlugin();
if (defaultTargetPlatform == TargetPlatform.android) return true;
if (defaultTargetPlatform == TargetPlatform.iOS) return true;
return false;
}
// Metodo per cancellare il token (es. logout)
void clear() {
Future<void> saveToken(String token) async {
_token = token;
if (await isMobilePlatform()) {
await _storage.write(key: 'AuthToken', value: token);
}
}
Future<bool> loadTokenWithBiometric() async {
if (!await isMobilePlatform()) return false;
final auth = LocalAuthentication();
final canAuth =
await auth.canCheckBiometrics || await auth.isDeviceSupported();
if (!canAuth) return false;
final authenticated = await auth.authenticate(
localizedReason: 'Autenticati per accedere',
options: const AuthenticationOptions(biometricOnly: true),
);
if (authenticated) {
final stored = await _storage.read(key: 'AuthToken');
_token = stored;
return stored != null;
}
return false;
}
Future<void> clear() async {
_token = null;
if (await isMobilePlatform()) {
await _storage.delete(key: 'AuthToken');
}
}
}
+15 -6
View File
@@ -1,21 +1,30 @@
import 'package:flutter/material.dart';
import 'pages/login_page.dart';
import 'entities/auth_token.dart';
import 'pages/dashboard_page.dart';
void main() {
runApp(const MyApp());
void main() async {
WidgetsFlutterBinding.ensureInitialized();
final authToken = AuthToken.instance;
final isLoggedIn = await authToken.loadTokenWithBiometric();
//runApp(const MyApp());
runApp(MyApp(startInDashboard: isLoggedIn));
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
final bool startInDashboard;
const MyApp({super.key, required this.startInDashboard});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Login App',
title: 'Gestione Vigne',
theme: ThemeData(
primarySwatch: Colors.deepPurple,
colorScheme: ColorScheme.fromSeed(seedColor: Colors.green),
useMaterial3: true,
),
home: const LoginPage(),
home: startInDashboard ? const DashboardPage() : const LoginPage(),
);
}
}
+139 -39
View File
@@ -1,7 +1,9 @@
import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart' show defaultTargetPlatform, kIsWeb;
import 'package:shared_preferences/shared_preferences.dart';
import '../services/api_service.dart';
import 'dashboard_page.dart';
import '../entities/auth_token.dart';
import 'dashboard_page.dart';
class LoginPage extends StatefulWidget {
const LoginPage({super.key});
@@ -14,33 +16,65 @@ class _LoginPageState extends State<LoginPage> {
final _emailController = TextEditingController();
final _passwordController = TextEditingController();
bool _loading = false;
bool _rememberMe = false;
String? _error;
void _login() async {
bool get isMobile {
final platform = defaultTargetPlatform;
return platform == TargetPlatform.android ||
platform == TargetPlatform.iOS ||
(kIsWeb && MediaQuery.of(context).size.width < 600);
}
@override
void initState() {
super.initState();
_checkRememberedUser();
}
Future<void> _checkRememberedUser() async {
final prefs = await SharedPreferences.getInstance();
final token = prefs.getString('token');
if (token != null && prefs.getBool('rememberMe') == true) {
AuthToken.instance.saveToken(token);
if (mounted) {
Navigator.pushReplacement(
context,
MaterialPageRoute(builder: (_) => const DashboardPage()),
);
}
}
}
Future<void> _login() async {
setState(() {
_loading = true;
_error = null;
});
final email = _emailController.text.trim();
final password = _passwordController.text;
try {
final token = await ApiService.login(email, password);
auth_token().token = token;
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Login riuscito! Token: $token')),
final token = await ApiService.login(
_emailController.text.trim(),
_passwordController.text,
);
await AuthToken.instance.saveToken(token);
final prefs = await SharedPreferences.getInstance();
if (_rememberMe) {
await prefs.setString('token', token);
await prefs.setBool('rememberMe', true);
} else {
await prefs.remove('token');
await prefs.setBool('rememberMe', false);
}
if (!mounted) return;
Navigator.of(context).pushReplacement(
Navigator.pushReplacement(
context,
MaterialPageRoute(builder: (_) => const DashboardPage()),
);
} catch (e) {
setState(() {
_error = e.toString();
});
} finally {
setState(() {
_loading = false;
});
}
@@ -48,36 +82,102 @@ class _LoginPageState extends State<LoginPage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Login')),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
final content = Column(
mainAxisSize: MainAxisSize.min,
children: [
const Icon(Icons.eco, size: 64, color: Color(0xFF388E3C)),
const SizedBox(height: 12),
const Text(
'Gestione Vigna',
style: TextStyle(
fontSize: 26,
fontWeight: FontWeight.bold,
color: Color(0xFF2E7D32)),
),
const SizedBox(height: 24),
TextField(
controller: _emailController,
decoration: const InputDecoration(
labelText: 'Email o Username',
border: OutlineInputBorder(),
prefixIcon: Icon(Icons.person),
),
),
const SizedBox(height: 16),
TextField(
controller: _passwordController,
obscureText: true,
decoration: const InputDecoration(
labelText: 'Password',
border: OutlineInputBorder(),
prefixIcon: Icon(Icons.lock),
),
),
const SizedBox(height: 12),
Row(
children: [
TextField(
controller: _emailController,
decoration: const InputDecoration(labelText: 'Email'),
Checkbox(
value: _rememberMe,
activeColor: const Color(0xFF43A047),
onChanged: (value) {
setState(() {
_rememberMe = value ?? false;
});
},
),
const SizedBox(height: 12),
TextField(
controller: _passwordController,
obscureText: true,
decoration: const InputDecoration(labelText: 'Password'),
),
const SizedBox(height: 24),
if (_error != null)
Text(
_error!,
style: const TextStyle(color: Colors.red),
),
_loading
? const CircularProgressIndicator()
: ElevatedButton(
onPressed: _login,
child: const Text('Login'),
),
const Text("Ricorda accesso"),
],
),
if (_error != null)
Text(
_error!,
style: const TextStyle(color: Colors.red),
),
const SizedBox(height: 10),
_loading
? const CircularProgressIndicator()
: SizedBox(
width: double.infinity,
child: ElevatedButton.icon(
icon: const Icon(Icons.login),
style: ElevatedButton.styleFrom(
backgroundColor: const Color(0xFF43A047),
padding: const EdgeInsets.symmetric(vertical: 14),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8)),
),
label: const Text('Login', style: TextStyle(fontSize: 18)),
onPressed: _login,
),
),
],
);
return Scaffold(
backgroundColor: Colors.white,
body: LayoutBuilder(
builder: (context, constraints) {
return Center(
child: SingleChildScrollView(
padding: const EdgeInsets.all(24),
child: ConstrainedBox(
constraints: BoxConstraints(
maxWidth: isMobile ? double.infinity : 400,
),
child: Card(
elevation: isMobile ? 0 : 8,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16)),
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 24, vertical: 32),
child: content,
),
),
),
),
);
},
),
);
}
+3 -2
View File
@@ -29,7 +29,8 @@ class ApiService {
if (response.statusCode == 200) {
final data = jsonDecode(response.body);
_token = data['access_token']; // salva il token in memoria
return _token!;
AuthToken.instance.saveToken(_token!);
return '${response.statusCode}';
} else {
throw Exception(
'Login fallito: ${response.statusCode} - ${response.body}');
@@ -37,7 +38,7 @@ class ApiService {
}
static Future<dynamic> checkLogin() async {
final token = auth_token().token;
final token = AuthToken.instance.token;
if (token == null) {
throw Exception('Token non disponibile. Effettua il login prima.');
}