Implement login

This commit is contained in:
Mike Schwörer 2024-06-01 14:00:16 +02:00
parent 16d97ad08f
commit d662a6c426
Signed by: Mikescher
GPG Key ID: D3C7172E0A70F8CF
5 changed files with 252 additions and 150 deletions

View File

@ -36,7 +36,7 @@ class APIClient {
Map<String, String>? query, Map<String, String>? query,
required T Function(Map<String, dynamic> json)? fn, required T Function(Map<String, dynamic> json)? fn,
dynamic jsonBody, dynamic jsonBody,
KeyTokenAuth? auth, String? authToken,
Map<String, String>? header, Map<String, String>? header,
}) async { }) async {
final t0 = DateTime.now(); final t0 = DateTime.now();
@ -52,8 +52,8 @@ class APIClient {
req.headers['Content-Type'] = 'application/json'; req.headers['Content-Type'] = 'application/json';
} }
if (auth != null) { if (authToken != null) {
req.headers['Authorization'] = 'SCN ${auth.tokenAdmin}'; req.headers['Authorization'] = 'SCN ${authToken}';
} }
req.headers['User-Agent'] = 'simplecloudnotifier/flutter/${Globals().platform.replaceAll(' ', '_')} ${Globals().version}+${Globals().buildNumber}'; req.headers['User-Agent'] = 'simplecloudnotifier/flutter/${Globals().platform.replaceAll(' ', '_')} ${Globals().version}+${Globals().buildNumber}';
@ -117,32 +117,17 @@ class APIClient {
// ========================================================================================================================================================== // ==========================================================================================================================================================
static Future<bool> verifyToken(String uid, String tok) async {
try {
await _request<void>(
name: 'verifyToken',
method: 'GET',
relURL: '/users/$uid',
fn: null,
auth: KeyTokenAuth(userId: uid, tokenAdmin: tok, tokenSend: ''),
);
return true;
} catch (e) {
return false;
}
}
static Future<User> getUser(KeyTokenAuth auth, String uid) async { static Future<User> getUser(KeyTokenAuth auth, String uid) async {
return await _request( return await _request(
name: 'getUser', name: 'getUser',
method: 'GET', method: 'GET',
relURL: 'users/$uid', relURL: 'users/$uid',
fn: User.fromJson, fn: User.fromJson,
auth: auth, authToken: auth.tokenAdmin,
); );
} }
static Future<Client> addClient(KeyTokenAuth? auth, String fcmToken, String agentModel, String agentVersion, String? descriptionName, String clientType) async { static Future<Client> addClient(KeyTokenAuth? auth, String fcmToken, String agentModel, String agentVersion, String? name, String clientType) async {
return await _request( return await _request(
name: 'addClient', name: 'addClient',
method: 'POST', method: 'POST',
@ -152,14 +137,14 @@ class APIClient {
'agent_model': agentModel, 'agent_model': agentModel,
'agent_version': agentVersion, 'agent_version': agentVersion,
'client_type': clientType, 'client_type': clientType,
'description_name': descriptionName, 'name': name,
}, },
fn: Client.fromJson, fn: Client.fromJson,
auth: auth, authToken: auth.tokenAdmin,
); );
} }
static Future<Client> updateClient(KeyTokenAuth? auth, String clientID, String fcmToken, String agentModel, String? descriptionName, String agentVersion) async { static Future<Client> updateClient(KeyTokenAuth? auth, String clientID, String fcmToken, String agentModel, String? name, String agentVersion) async {
return await _request( return await _request(
name: 'updateClient', name: 'updateClient',
method: 'PUT', method: 'PUT',
@ -168,10 +153,10 @@ class APIClient {
'fcm_token': fcmToken, 'fcm_token': fcmToken,
'agent_model': agentModel, 'agent_model': agentModel,
'agent_version': agentVersion, 'agent_version': agentVersion,
'description_name': descriptionName, 'name': name,
}, },
fn: Client.fromJson, fn: Client.fromJson,
auth: auth, authToken: auth.tokenAdmin,
); );
} }
@ -182,7 +167,7 @@ class APIClient {
relURL: 'users/${auth.userId}/channels', relURL: 'users/${auth.userId}/channels',
query: {'selector': sel.apiKey}, query: {'selector': sel.apiKey},
fn: (json) => ChannelWithSubscription.fromJsonArray(json['channels'] as List<dynamic>), fn: (json) => ChannelWithSubscription.fromJsonArray(json['channels'] as List<dynamic>),
auth: auth, authToken: auth.tokenAdmin,
); );
} }
@ -197,7 +182,7 @@ class APIClient {
if (channelIDs != null) 'channel_id': channelIDs.join(","), if (channelIDs != null) 'channel_id': channelIDs.join(","),
}, },
fn: (json) => Message.fromPaginatedJsonArray(json, 'messages', 'next_page_token'), fn: (json) => Message.fromPaginatedJsonArray(json, 'messages', 'next_page_token'),
auth: auth, authToken: auth.tokenAdmin,
); );
} }
@ -208,7 +193,7 @@ class APIClient {
relURL: 'messages/$msgid', relURL: 'messages/$msgid',
query: {}, query: {},
fn: Message.fromJson, fn: Message.fromJson,
auth: auth, authToken: auth.tokenAdmin,
); );
} }
@ -218,7 +203,7 @@ class APIClient {
method: 'GET', method: 'GET',
relURL: 'users/${auth.userId}/subscriptions', relURL: 'users/${auth.userId}/subscriptions',
fn: (json) => Subscription.fromJsonArray(json['subscriptions'] as List<dynamic>), fn: (json) => Subscription.fromJsonArray(json['subscriptions'] as List<dynamic>),
auth: auth, authToken: auth.tokenAdmin,
); );
} }
@ -228,7 +213,7 @@ class APIClient {
method: 'GET', method: 'GET',
relURL: 'users/${auth.userId}/clients', relURL: 'users/${auth.userId}/clients',
fn: (json) => Client.fromJsonArray(json['clients'] as List<dynamic>), fn: (json) => Client.fromJsonArray(json['clients'] as List<dynamic>),
auth: auth, authToken: auth.tokenAdmin,
); );
} }
@ -238,11 +223,11 @@ class APIClient {
method: 'GET', method: 'GET',
relURL: 'users/${auth.userId}/keys', relURL: 'users/${auth.userId}/keys',
fn: (json) => KeyToken.fromJsonArray(json['keys'] as List<dynamic>), fn: (json) => KeyToken.fromJsonArray(json['keys'] as List<dynamic>),
auth: auth, authToken: auth.tokenAdmin,
); );
} }
static Future<UserWithClientsAndKeys> createUserWithClient(String? username, String clientFcmToken, String clientAgentModel, String clientAgentVersion, String? clientDescriptionName, String clientType) async { static Future<UserWithClientsAndKeys> createUserWithClient(String? username, String clientFcmToken, String clientAgentModel, String clientAgentVersion, String? clientName, String clientType) async {
return await _request( return await _request(
name: 'createUserWithClient', name: 'createUserWithClient',
method: 'POST', method: 'POST',
@ -252,11 +237,31 @@ class APIClient {
'fcm_token': clientFcmToken, 'fcm_token': clientFcmToken,
'agent_model': clientAgentModel, 'agent_model': clientAgentModel,
'agent_version': clientAgentVersion, 'agent_version': clientAgentVersion,
'description_name': clientDescriptionName, 'client_name': clientName,
'client_type': clientType, 'client_type': clientType,
'no_client': false, 'no_client': false,
}, },
fn: UserWithClientsAndKeys.fromJson, fn: UserWithClientsAndKeys.fromJson,
); );
} }
static Future<KeyToken> getKeyToken(KeyTokenAuth auth, String kid) async {
return await _request(
name: 'getKeyToken',
method: 'GET',
relURL: 'users/${auth.userId}/keys/$kid',
fn: KeyToken.fromJson,
authToken: auth.tokenAdmin,
);
}
static Future<KeyToken> getKeyTokenByToken(String userid, String token) async {
return await _request(
name: 'getCurrentKeyToken',
method: 'GET',
relURL: 'users/${userid}/keys/current',
fn: KeyToken.fromJson,
authToken: token,
);
}
} }

View File

@ -6,7 +6,7 @@ class Client {
final String timestampCreated; final String timestampCreated;
final String agentModel; final String agentModel;
final String agentVersion; final String agentVersion;
final String? descriptionName; final String? name;
const Client({ const Client({
required this.clientID, required this.clientID,
@ -16,7 +16,7 @@ class Client {
required this.timestampCreated, required this.timestampCreated,
required this.agentModel, required this.agentModel,
required this.agentVersion, required this.agentVersion,
required this.descriptionName, required this.name,
}); });
factory Client.fromJson(Map<String, dynamic> json) { factory Client.fromJson(Map<String, dynamic> json) {
@ -28,7 +28,7 @@ class Client {
timestampCreated: json['timestamp_created'] as String, timestampCreated: json['timestamp_created'] as String,
agentModel: json['agent_model'] as String, agentModel: json['agent_model'] as String,
agentVersion: json['agent_version'] as String, agentVersion: json['agent_version'] as String,
descriptionName: json.containsKey('description_name') ? (json['description_name'] as String?) : null, //TODO change once API is updated / branch is merged name: json['name'] as String?,
); );
} }

View File

@ -90,7 +90,7 @@ class _AccountRootPageState extends State<AccountRootPage> {
return Consumer<UserAccount>( return Consumer<UserAccount>(
builder: (context, acc, child) { builder: (context, acc, child) {
if (acc.auth == null) { if (acc.auth == null) {
return buildNoAuth(context); return _buildNoAuth(context);
} else { } else {
return FutureBuilder( return FutureBuilder(
future: acc.loadUser(false), future: acc.loadUser(false),
@ -99,7 +99,7 @@ class _AccountRootPageState extends State<AccountRootPage> {
if (snapshot.hasError) { if (snapshot.hasError) {
return Text('Error: ${snapshot.error}'); //TODO better error display return Text('Error: ${snapshot.error}'); //TODO better error display
} }
return buildShowAccount(context, acc, snapshot.data!); return _buildShowAccount(context, acc, snapshot.data!);
} }
return Center(child: CircularProgressIndicator()); return Center(child: CircularProgressIndicator());
}), }),
@ -109,61 +109,63 @@ class _AccountRootPageState extends State<AccountRootPage> {
); );
} }
Widget buildNoAuth(BuildContext context) { Widget _buildNoAuth(BuildContext context) {
return Padding( return SingleChildScrollView(
padding: const EdgeInsets.fromLTRB(24, 32, 24, 16), child: Padding(
child: Column( padding: const EdgeInsets.fromLTRB(24, 32, 24, 16),
mainAxisAlignment: MainAxisAlignment.start, child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch, mainAxisAlignment: MainAxisAlignment.start,
children: [ crossAxisAlignment: CrossAxisAlignment.stretch,
if (!loading) children: [
Center( if (!loading)
child: Container( Center(
width: 200, child: Container(
height: 200, width: 200,
decoration: BoxDecoration( height: 200,
color: Theme.of(context).colorScheme.secondary, decoration: BoxDecoration(
borderRadius: BorderRadius.circular(100), color: Theme.of(context).colorScheme.secondary,
borderRadius: BorderRadius.circular(100),
),
child: Center(child: FaIcon(FontAwesomeIcons.userSecret, size: 96, color: Theme.of(context).colorScheme.onSecondary)),
), ),
child: Center(child: FaIcon(FontAwesomeIcons.userSecret, size: 96, color: Theme.of(context).colorScheme.onSecondary)),
), ),
), if (loading)
if (loading) Center(
Center( child: Container(
child: Container( width: 200,
width: 200, height: 200,
height: 200, decoration: BoxDecoration(
decoration: BoxDecoration( color: Theme.of(context).colorScheme.secondary,
color: Theme.of(context).colorScheme.secondary, borderRadius: BorderRadius.circular(100),
borderRadius: BorderRadius.circular(100), ),
child: Center(child: CircularProgressIndicator(color: Theme.of(context).colorScheme.onSecondary)),
), ),
child: Center(child: CircularProgressIndicator(color: Theme.of(context).colorScheme.onSecondary)),
), ),
const SizedBox(height: 32),
FilledButton(
style: FilledButton.styleFrom(textStyle: const TextStyle(fontSize: 24), padding: const EdgeInsets.fromLTRB(8, 12, 8, 12)),
onPressed: () {
if (loading) return;
_createNewAccount();
},
child: const Text('Create new account'),
), ),
const SizedBox(height: 32), const SizedBox(height: 16),
FilledButton( FilledButton.tonal(
style: FilledButton.styleFrom(textStyle: const TextStyle(fontSize: 24), padding: const EdgeInsets.fromLTRB(8, 12, 8, 12)), style: FilledButton.styleFrom(textStyle: const TextStyle(fontSize: 24), padding: const EdgeInsets.fromLTRB(8, 12, 8, 12)),
onPressed: () { onPressed: () {
if (loading) return; if (loading) return;
createNewAccount(); Navigator.push(context, MaterialPageRoute<AccountLoginPage>(builder: (context) => AccountLoginPage()));
}, },
child: const Text('Create new account'), child: const Text('Use existing account'),
), ),
const SizedBox(height: 16), ],
FilledButton.tonal( ),
style: FilledButton.styleFrom(textStyle: const TextStyle(fontSize: 24), padding: const EdgeInsets.fromLTRB(8, 12, 8, 12)),
onPressed: () {
if (loading) return;
Navigator.push(context, MaterialPageRoute<AccountLoginPage>(builder: (context) => AccountLoginPage()));
},
child: const Text('Use existing account'),
),
],
), ),
); );
} }
Widget buildShowAccount(BuildContext context, UserAccount acc, User user) { Widget _buildShowAccount(BuildContext context, UserAccount acc, User user) {
//TODO better layout //TODO better layout
return Column( return Column(
children: [ children: [
@ -173,23 +175,23 @@ class _AccountRootPageState extends State<AccountRootPage> {
padding: const EdgeInsets.fromLTRB(8.0, 24.0, 8.0, 8.0), padding: const EdgeInsets.fromLTRB(8.0, 24.0, 8.0, 8.0),
child: Column( child: Column(
children: [ children: [
buildHeader(context, user), _buildHeader(context, user),
const SizedBox(height: 16), const SizedBox(height: 16),
Text(user.username ?? user.userID, overflow: TextOverflow.ellipsis, style: TextStyle(fontWeight: FontWeight.bold, fontSize: 20)), Text(user.username ?? user.userID, overflow: TextOverflow.ellipsis, style: TextStyle(fontWeight: FontWeight.bold, fontSize: 20)),
const SizedBox(height: 16), const SizedBox(height: 16),
...buildCards(context, user), ..._buildCards(context, user),
], ],
), ),
), ),
), ),
const Expanded(child: SizedBox(height: 16)), const Expanded(child: SizedBox(height: 16)),
buildFooter(context, user), _buildFooter(context, user),
SizedBox(height: 40) SizedBox(height: 40)
], ],
); );
} }
Row buildHeader(BuildContext context, User user) { Row _buildHeader(BuildContext context, User user) {
return Row( return Row(
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
@ -284,7 +286,7 @@ class _AccountRootPageState extends State<AccountRootPage> {
); );
} }
List<Widget> buildCards(BuildContext context, User user) { List<Widget> _buildCards(BuildContext context, User user) {
return [ return [
Card.filled( Card.filled(
margin: EdgeInsets.fromLTRB(0, 4, 0, 4), margin: EdgeInsets.fromLTRB(0, 4, 0, 4),
@ -416,20 +418,20 @@ class _AccountRootPageState extends State<AccountRootPage> {
]; ];
} }
Widget buildFooter(BuildContext context, User user) { Widget _buildFooter(BuildContext context, User user) {
return Padding( return Padding(
padding: const EdgeInsets.fromLTRB(8, 0, 8, 0), padding: const EdgeInsets.fromLTRB(8, 0, 8, 0),
child: Row( child: Row(
children: [ children: [
Expanded(child: FilledButton(onPressed: () {/*TODO*/}, child: Text('Logout'), style: TextButton.styleFrom(backgroundColor: Colors.orange))), Expanded(child: FilledButton(onPressed: _logout, child: Text('Logout'), style: TextButton.styleFrom(backgroundColor: Colors.orange))),
const SizedBox(width: 8), const SizedBox(width: 8),
Expanded(child: FilledButton(onPressed: () {/*TODO*/}, child: Text('Delete Account'), style: TextButton.styleFrom(backgroundColor: Colors.red))), Expanded(child: FilledButton(onPressed: _deleteAccount, child: Text('Delete Account'), style: TextButton.styleFrom(backgroundColor: Colors.red))),
], ],
), ),
); );
} }
void createNewAccount() async { void _createNewAccount() async {
setState(() => loading = true); setState(() => loading = true);
final acc = Provider.of<UserAccount>(context, listen: false); final acc = Provider.of<UserAccount>(context, listen: false);
@ -453,9 +455,8 @@ class _AccountRootPageState extends State<AccountRootPage> {
final user = await APIClient.createUserWithClient(null, fcmToken, Globals().platform, Globals().version, Globals().hostname, Globals().clientType); final user = await APIClient.createUserWithClient(null, fcmToken, Globals().platform, Globals().version, Globals().hostname, Globals().clientType);
acc.setUser(user.user); acc.set(user.user, user.clients[0], KeyTokenAuth(userId: user.user.userID, tokenAdmin: user.adminKey, tokenSend: user.sendKey));
acc.setToken(KeyTokenAuth(userId: user.user.userID, tokenAdmin: user.adminKey, tokenSend: user.sendKey));
acc.setClient(user.clients[0]);
await acc.save(); await acc.save();
} catch (exc, trace) { } catch (exc, trace) {
ApplicationLog.error('Failed to create user account: ' + exc.toString(), trace: trace); ApplicationLog.error('Failed to create user account: ' + exc.toString(), trace: trace);
@ -464,4 +465,17 @@ class _AccountRootPageState extends State<AccountRootPage> {
setState(() => loading = false); setState(() => loading = false);
} }
} }
void _logout() async {
final acc = Provider.of<UserAccount>(context, listen: false);
acc.clear();
await acc.save();
Toaster.info('Logout', 'Successfully logged out');
}
void _deleteAccount() async {
//TODO
}
} }

View File

@ -1,14 +1,17 @@
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:provider/provider.dart'; import 'package:provider/provider.dart';
import 'package:simplecloudnotifier/api/api_client.dart'; import 'package:simplecloudnotifier/api/api_client.dart';
import 'package:simplecloudnotifier/components/layout/scaffold.dart';
import 'package:simplecloudnotifier/models/key_token_auth.dart'; import 'package:simplecloudnotifier/models/key_token_auth.dart';
import 'package:simplecloudnotifier/state/application_log.dart'; import 'package:simplecloudnotifier/state/application_log.dart';
import 'package:simplecloudnotifier/state/globals.dart';
import 'package:simplecloudnotifier/state/user_account.dart'; import 'package:simplecloudnotifier/state/user_account.dart';
import 'package:simplecloudnotifier/utils/toaster.dart';
class AccountLoginPage extends StatefulWidget { class AccountLoginPage extends StatefulWidget {
final void Function()? onLogin; const AccountLoginPage({super.key});
const AccountLoginPage({super.key, this.onLogin});
@override @override
State<AccountLoginPage> createState() => _AccountLoginPageState(); State<AccountLoginPage> createState() => _AccountLoginPageState();
@ -16,81 +19,147 @@ class AccountLoginPage extends StatefulWidget {
class _AccountLoginPageState extends State<AccountLoginPage> { class _AccountLoginPageState extends State<AccountLoginPage> {
final TextEditingController _ctrlUserID = TextEditingController(); final TextEditingController _ctrlUserID = TextEditingController();
final TextEditingController _ctrlToken = TextEditingController(); final TextEditingController _ctrlTokenAdmin = TextEditingController();
final TextEditingController _ctrlTokenSend = TextEditingController();
bool loading = false;
@override @override
void dispose() { void dispose() {
_ctrlUserID.dispose(); _ctrlUserID.dispose();
_ctrlToken.dispose(); _ctrlTokenAdmin.dispose();
_ctrlTokenSend.dispose();
super.dispose(); super.dispose();
} }
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return Padding( return SCNScaffold(
padding: const EdgeInsets.all(16.0), title: 'Login',
child: Column( showSearch: false,
mainAxisAlignment: MainAxisAlignment.center, child: SingleChildScrollView(
children: [ child: Padding(
FractionallySizedBox( padding: const EdgeInsets.fromLTRB(24, 32, 24, 16),
widthFactor: 1.0, child: Column(
child: TextField( mainAxisAlignment: MainAxisAlignment.start,
controller: _ctrlUserID, crossAxisAlignment: CrossAxisAlignment.stretch,
decoration: const InputDecoration( children: [
border: OutlineInputBorder(), if (!loading)
labelText: 'UserID', Center(
child: Container(
width: 200,
height: 200,
decoration: BoxDecoration(
color: Theme.of(context).colorScheme.secondary,
borderRadius: BorderRadius.circular(100),
),
child: Center(child: FaIcon(FontAwesomeIcons.solidRightToBracket, size: 96, color: Theme.of(context).colorScheme.onSecondary)),
),
),
if (loading)
Center(
child: Container(
width: 200,
height: 200,
decoration: BoxDecoration(
color: Theme.of(context).colorScheme.secondary,
borderRadius: BorderRadius.circular(100),
),
child: Center(child: CircularProgressIndicator(color: Theme.of(context).colorScheme.onSecondary)),
),
),
const SizedBox(height: 32),
FractionallySizedBox(
widthFactor: 1.0,
child: TextField(
controller: _ctrlUserID,
decoration: const InputDecoration(
border: OutlineInputBorder(),
labelText: 'UserID',
),
),
), ),
), const SizedBox(height: 16),
), FractionallySizedBox(
const SizedBox(height: 16), widthFactor: 1.0,
FractionallySizedBox( child: TextField(
widthFactor: 1.0, controller: _ctrlTokenAdmin,
child: TextField( decoration: const InputDecoration(
controller: _ctrlToken, border: OutlineInputBorder(),
decoration: const InputDecoration( labelText: 'Admin Token',
border: OutlineInputBorder(), ),
labelText: 'Token', ),
), ),
), const SizedBox(height: 16),
FractionallySizedBox(
widthFactor: 1.0,
child: TextField(
controller: _ctrlTokenSend,
decoration: const InputDecoration(
border: OutlineInputBorder(),
labelText: 'Send Token (optional)',
),
),
),
const SizedBox(height: 16),
FilledButton(
style: FilledButton.styleFrom(textStyle: const TextStyle(fontSize: 24), padding: const EdgeInsets.fromLTRB(8, 12, 8, 12)),
onPressed: _login,
child: const Text('Login'),
),
],
), ),
const SizedBox(height: 16), ),
FilledButton(
style: FilledButton.styleFrom(textStyle: const TextStyle(fontSize: 20)),
onPressed: _login,
child: const Text('Login'),
),
],
), ),
); );
} }
void _login() async { void _login() async {
final msgr = ScaffoldMessenger.of(context);
final acc = Provider.of<UserAccount>(context, listen: false); final acc = Provider.of<UserAccount>(context, listen: false);
try { try {
final uid = _ctrlUserID.text; setState(() => loading = true);
final tok = _ctrlToken.text;
final verified = await APIClient.verifyToken(uid, tok); //TODO verify that this is an perm=ADMIN key final uid = _ctrlUserID.text;
if (verified) { final atokv = _ctrlTokenAdmin.text;
msgr.showSnackBar( final stokv = _ctrlTokenSend.text;
const SnackBar(
content: Text('Data ok'), //TODO use toast? final fcmToken = await FirebaseMessaging.instance.getToken();
),
); if (fcmToken == null) {
acc.setToken(KeyTokenAuth(userId: uid, tokenAdmin: tok, tokenSend: '')); //TOTO send token Toaster.warn("Missing Token", 'No FCM Token found, please allow notifications, ensure you have a network connection and restart the app');
await acc.save(); return;
widget.onLogin?.call();
} else {
msgr.showSnackBar(
const SnackBar(
content: Text('Failed to verify token'), //TODO use toast?
),
);
} }
final toka = await APIClient.getKeyTokenByToken(uid, atokv);
if (!toka.allChannels || toka.permissions != 'A') {
Toaster.error("Error", 'Admin token does not have required permissions');
return;
}
final toks = await APIClient.getKeyTokenByToken(uid, stokv);
if (!toks.allChannels || toks.permissions != 'CS') {
Toaster.error("Error", 'Send token does not have required permissions');
return;
}
final kta = KeyTokenAuth(userId: uid, tokenAdmin: atokv, tokenSend: stokv);
final user = await APIClient.getUser(kta, uid);
final client = await APIClient.addClient(acc.auth, fcmToken, Globals().deviceModel, Globals().version, Globals().hostname, Globals().clientType);
acc.set(user, client, kta);
await acc.save();
Toaster.success("Login", "Successfully logged in");
} catch (exc, trace) { } catch (exc, trace) {
ApplicationLog.error('Failed to verify token: ' + exc.toString(), trace: trace); ApplicationLog.error('Failed to verify token: ' + exc.toString(), trace: trace);
Toaster.error("Error", 'Failed to verify token');
} finally {
setState(() => loading = false);
} }
} }
} }

View File

@ -58,6 +58,20 @@ class UserAccount extends ChangeNotifier {
notifyListeners(); notifyListeners();
} }
void set(User user, Client client, KeyTokenAuth auth) {
_client = client;
_user = user;
_auth = auth;
notifyListeners();
}
void clear() {
_client = null;
_user = null;
_auth = null;
notifyListeners();
}
void load() { void load() {
final uid = Globals().sharedPrefs.getString('auth.userid'); final uid = Globals().sharedPrefs.getString('auth.userid');
final toka = Globals().sharedPrefs.getString('auth.tokenadmin'); final toka = Globals().sharedPrefs.getString('auth.tokenadmin');