SimpleCloudNotifier/flutter/lib/pages/account/login.dart

102 lines
2.6 KiB
Dart
Raw Normal View History

2024-02-11 01:08:51 +01:00
import 'package:flutter/material.dart';
2024-02-11 02:20:48 +01:00
import 'package:provider/provider.dart';
2024-02-11 01:08:51 +01:00
import 'package:simplecloudnotifier/api/api_client.dart';
2024-02-11 02:20:48 +01:00
import 'package:simplecloudnotifier/models/key_token_auth.dart';
import 'package:simplecloudnotifier/state/user_account.dart';
2024-02-11 01:08:51 +01:00
class AccountLoginPage extends StatefulWidget {
2024-02-11 02:20:48 +01:00
final void Function()? onLogin;
const AccountLoginPage({super.key, this.onLogin});
2024-02-11 01:08:51 +01:00
@override
State<AccountLoginPage> createState() => _AccountLoginPageState();
}
class _AccountLoginPageState extends State<AccountLoginPage> {
late TextEditingController _ctrlUserID;
late TextEditingController _ctrlToken;
@override
void initState() {
super.initState();
_ctrlUserID = TextEditingController();
_ctrlToken = TextEditingController();
}
@override
void dispose() {
_ctrlUserID.dispose();
_ctrlToken.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
SizedBox(
width: 250,
child: TextField(
controller: _ctrlUserID,
decoration: const InputDecoration(
border: OutlineInputBorder(),
labelText: 'UserID',
),
),
),
const SizedBox(height: 16),
SizedBox(
width: 250,
child: TextField(
controller: _ctrlToken,
decoration: const InputDecoration(
border: OutlineInputBorder(),
labelText: 'Token',
),
),
),
const SizedBox(height: 16),
ElevatedButton(
style: ElevatedButton.styleFrom(textStyle: const TextStyle(fontSize: 20)),
onPressed: _login,
child: const Text('Login'),
),
],
),
);
}
void _login() async {
final msgr = ScaffoldMessenger.of(context);
2024-02-11 02:20:48 +01:00
final prov = Provider.of<UserAccount>(context, listen: false);
try {
final uid = _ctrlUserID.text;
final tok = _ctrlToken.text;
2024-02-11 01:08:51 +01:00
2024-02-11 02:20:48 +01:00
final verified = await APIClient.verifyToken(uid, tok);
if (verified) {
msgr.showSnackBar(
const SnackBar(
2024-02-18 16:23:10 +01:00
content: Text('Data ok'),
2024-02-11 02:20:48 +01:00
),
);
prov.setToken(KeyTokenAuth(userId: uid, token: tok));
await prov.save();
widget.onLogin?.call();
} else {
msgr.showSnackBar(
const SnackBar(
2024-02-18 16:23:10 +01:00
content: Text('Failed to verify token'),
2024-02-11 02:20:48 +01:00
),
);
}
} catch (e) {
//TODO
2024-02-11 01:08:51 +01:00
}
}
}