From 63155fc6bbc175c8dcc10a70ce2392976a03c0ff Mon Sep 17 00:00:00 2001 From: Jakob Meier Date: Fri, 17 Mar 2023 21:08:45 +0100 Subject: [PATCH] Added basic user authentification & auto-login --- lib/main.dart | 59 ++++++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 51 insertions(+), 8 deletions(-) diff --git a/lib/main.dart b/lib/main.dart index fb402bd..d7235c3 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -1,8 +1,12 @@ import 'package:flutter/material.dart'; +import 'package:outbag_app/backend/storage.dart'; import './screens/home.dart'; import './screens/welcome.dart'; import './screens/room.dart'; +import './screens/auth.dart'; +import './backend/request.dart'; import 'package:routemaster/routemaster.dart'; +import 'package:localstore/localstore.dart'; // routes when user is logged in final routesLoggedIn = RouteMap(routes: { @@ -12,18 +16,18 @@ final routesLoggedIn = RouteMap(routes: { info.pathParameters['tag'] ?? "", page: info.pathParameters['page'] ?? ""), ) -}); + }, onUnknownRoute: (_) => const Redirect('/')); // routes when user is not logged in -final routesUnauthorized = RouteMap( - routes: { +final routesUnauthorized = RouteMap(routes: { '/welcome/': (_) => const MaterialPage(child: WelcomePage()), - '/signin': (_) => const MaterialPage(child: HomePage()), - '/signup': (_) => const MaterialPage(child: HomePage()), - }, - onUnknownRoute: (_) => const Redirect('/welcome') -); + '/signup': (_) => const MaterialPage(child: AuthPage(mode: Mode.signup)), + '/signupOTA': (_) => + const MaterialPage(child: AuthPage(mode: Mode.signupOTA)), + '/signin': (_) => const MaterialPage(child: AuthPage(mode: Mode.signin)), + }, onUnknownRoute: (_) => const Redirect('/welcome')); void main() { + WidgetsFlutterBinding.ensureInitialized(); runApp(const OutbagApp()); } @@ -43,6 +47,45 @@ class _OutbagAppState extends State { // TODO: try to login user, // with existing details + + (() async { + try { + final credentials = await LoginDetails.fromDisk(); + final resp = await postUnauthorized( + target: credentials.server, + path: 'signin', + body: { + 'name': credentials.username, + 'server': credentials.server.tag, + 'accountKey': credentials.password + }); + if (resp.res == Result.ok) { + setState(() { + isAuthorized = true; + }); + } + } catch (_) { + // user is currently offline + // approve login, + // until user goes back offline + // NOTE TODO: check user data once online + setState(() { + isAuthorized = true; + }); + } + })(); + + // wait for user to be authorized + final db = Localstore.instance; + final stream = db.collection('meta').stream; + stream.listen((data) async { + try { + await LoginDetails.fromDisk(); + setState(() { + isAuthorized = true; + }); + } catch (_) {} + }); } @override