Skip to content

Commit

Permalink
Implement login logic
Browse files Browse the repository at this point in the history
  • Loading branch information
aguilaair committed Nov 22, 2021
1 parent 343f9c5 commit abdc26f
Show file tree
Hide file tree
Showing 5 changed files with 146 additions and 97 deletions.
5 changes: 3 additions & 2 deletions lib/providers/account_provider.dart
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ class AccountProvider extends StateNotifier<AccountState> {
AccountProvider(this.ref) : super(AccountState(null));
final Ref ref;

Future<void> getMe() async {
Future<Account?> getMe() async {
final token = ref.read(authProvider).token;

/*if (retryTimer != null) {
Expand Down Expand Up @@ -62,11 +62,12 @@ class AccountProvider extends StateNotifier<AccountState> {
deletedAt: _deletedAt,
driver: genDriver(resData),
email: resData["email"],
organization: Organization.fromJson(resData["organization"]),
organization: Organization.fromMap(resData["organization"]),
phoneNumber: resData["phone_number"],
yardId: resData["yard_id"],
);
}
return state.account;
} catch (e) {
/*print("Trying to reconnet");
retryTimer = Timer(
Expand Down
26 changes: 17 additions & 9 deletions lib/providers/auth_provider.dart
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,9 @@ class Auth extends StateNotifier<AuthState> {
}

Future<bool> tryAutoLogin() async {
if (isAuth) {
return true;
}
final prefs = await SharedPreferences.getInstance();
if (!prefs.containsKey("authInfo")) {
return false;
Expand All @@ -84,9 +87,10 @@ class Auth extends StateNotifier<AuthState> {
_expiryDate = expiryDate;
notifyListeners();*/

state.copyWith(
state = state.copyWith(
token: extractedData["token"],
userId: extractedData["userId"],
expiryDate: expiryDate,
);

_autoLogout();
Expand Down Expand Up @@ -115,24 +119,28 @@ class Auth extends StateNotifier<AuthState> {
if (res.statusCode == 200) {
final resData = json.decode(res.body);

state.copyWith(
var tempState = state;

tempState = tempState.copyWith(
token: resData["jwt_token"],
userId: username,
);

if (state.token != null) {
state.copyWith(
tempState = tempState.copyWith(
expiryDate: JwtDecoder.getExpirationDate(state.token!),
);

state = tempState;

_autoLogout();
_autoRefreshToken();

final prefs = await SharedPreferences.getInstance();
final userData = json.encode({
"token": state.token,
"token": tempState.token,
"userId": state.userId,
"expiryDate": state.expiryDate,
"expiryDate": state.expiryDate!.toIso8601String(),
});

prefs.setString("authInfo", userData);
Expand Down Expand Up @@ -172,7 +180,7 @@ class Auth extends StateNotifier<AuthState> {
throw "No token recieved";
}

state.copyWith(
state = state.copyWith(
token: resData["jwt_token"],
expiryDate: JwtDecoder.getExpirationDate(resData["jwt_token"]),
);
Expand Down Expand Up @@ -200,7 +208,7 @@ class Auth extends StateNotifier<AuthState> {
}

Future<void> logout() async {
state.copyWith(token: null, expiryDate: null, userId: null);
state = state.copyWith(token: null, expiryDate: null, userId: null);
if (state.authTimer != null) {
state.authTimer!.cancel();
}
Expand All @@ -222,7 +230,7 @@ class Auth extends StateNotifier<AuthState> {
final _timeToExpiry =
state.expiryDate!.difference(DateTime.now()).inSeconds;

state.copyWith(
state = state.copyWith(
authTimer: Timer(Duration(seconds: _timeToExpiry), logout),
);
}
Expand All @@ -233,7 +241,7 @@ class Auth extends StateNotifier<AuthState> {
}
final _timeToExpiry =
state.expiryDate!.difference(DateTime.now()).inSeconds;
state.copyWith(
state = state.copyWith(
refreshTimer: Timer(Duration(seconds: _timeToExpiry - 30), _tryReferesh),
);
}
Expand Down
191 changes: 107 additions & 84 deletions lib/screens/login.dart
Original file line number Diff line number Diff line change
@@ -1,113 +1,136 @@
import 'package:flutter/material.dart';
import 'package:guard_app/providers/providers.dart';
import 'package:guard_app/widgets/logo.dart';
import 'package:guard_app/widgets/text_input.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';

class LoginPage extends HookWidget {
class LoginPage extends HookConsumerWidget {
const LoginPage({Key? key, required this.title}) : super(key: key);

final String title;

@override
Widget build(BuildContext context) {
Widget build(BuildContext context, WidgetRef ref) {
final usernameController = useTextEditingController();
final passwordController = useTextEditingController();
final usernameFocusNode = useFocusNode();
final passwordFocusNode = useFocusNode();

final useAuth = ref.watch(authProvider.notifier);

final autoLoginState = useAuth.tryAutoLogin();

return Scaffold(
backgroundColor: Theme.of(context).backgroundColor,
body: SafeArea(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 20),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
mainAxisSize: MainAxisSize.max,
children: [
Expanded(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: const [
Logo(
width: 170,
),
const SizedBox(
height: 12,
),
Text(
'''Welcome to the gatego guard app.
Please log in to continue''',
textAlign: TextAlign.center,
),
],
),
),
Card(
child: Padding(
padding:
const EdgeInsets.symmetric(horizontal: 12, vertical: 30),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
TextInput(
c: usernameController,
fn: usernameFocusNode,
text: "Username or Email",
icon: Icons.person,
),
TextInput(
c: passwordController,
fn: passwordFocusNode,
obscureText: true,
icon: Icons.vpn_key,
text: "Password",
),
],
),
),
),
Expanded(
child: Padding(
padding: const EdgeInsets.only(bottom: 50),
child: Column(
mainAxisAlignment: MainAxisAlignment.end,
children: [
ElevatedButton.icon(
icon: const Icon(
Icons.login_rounded,
size: 18,
),
style: ButtonStyle(
padding: MaterialStateProperty.resolveWith(
(states) => const EdgeInsets.symmetric(
horizontal: 50, vertical: 10),
child: FutureBuilder<bool>(
future: autoLoginState,
builder: (context, future) {
return Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
mainAxisSize: MainAxisSize.max,
children: [
Expanded(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: const [
Logo(
width: 170,
),
shape: MaterialStateProperty.resolveWith(
(states) => RoundedRectangleBorder(
borderRadius: BorderRadius.circular(50000),
),
SizedBox(
height: 12,
),
Text(
'''Welcome to the gatego guard app.
Please log in to continue''',
textAlign: TextAlign.center,
),
],
),
),
Card(
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 12, vertical: 30),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
TextInput(
c: usernameController,
fn: usernameFocusNode,
text: "Username or Email",
icon: Icons.person,
),
TextInput(
c: passwordController,
fn: passwordFocusNode,
obscureText: true,
icon: Icons.vpn_key,
text: "Password",
nextFocus: (string) {},
),
],
),
onPressed: () {},
label: Text(
"Log In",
style: Theme.of(context)
.textTheme
.headline6
?.copyWith(
color: Colors.white,
fontSize: 18,
fontWeight: FontWeight.bold),
),
),
Expanded(
child: Padding(
padding: const EdgeInsets.only(bottom: 50),
child: Column(
mainAxisAlignment: MainAxisAlignment.end,
children: [
ElevatedButton.icon(
icon: const Icon(
Icons.login_rounded,
size: 18,
),
style: ButtonStyle(
padding: MaterialStateProperty.resolveWith(
(states) => const EdgeInsets.symmetric(
horizontal: 50, vertical: 10),
),
shape: MaterialStateProperty.resolveWith(
(states) => RoundedRectangleBorder(
borderRadius: BorderRadius.circular(50000),
),
),
),
onPressed: () {
login(usernameController.text,
passwordController.text, ref);
},
label: Text(
"Log In",
style: Theme.of(context)
.textTheme
.headline6
?.copyWith(
color: Colors.white,
fontSize: 18,
fontWeight: FontWeight.bold),
),
),
],
),
),
],
),
),
),
],
),
),
],
);
}),
),
),
);
}
}

void login(String usr, String psw, WidgetRef ref) async {
final resLogin = await ref.read(authProvider.notifier).signIn(usr, psw);

if (resLogin & ref.read(authProvider.notifier).isAuth) {
print((await ref.read(accountProvider.notifier).getMe())!.id);
}
}
19 changes: 18 additions & 1 deletion lib/theme/dark_theme.dart
Original file line number Diff line number Diff line change
Expand Up @@ -40,12 +40,29 @@ ThemeData darkTheme() {
),
cardTheme: CardTheme(
elevation: 4,
color: const Color(0xff37383d),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(
8,
),
),
),
backgroundColor: const Color(0xffF7F9FD),
shadowColor: const Color(0xff494b52),
elevatedButtonTheme: ElevatedButtonThemeData(
style: ButtonStyle(
shape: MaterialStateProperty.resolveWith(
(states) => RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8),
),
),
backgroundColor: MaterialStateProperty.resolveWith(
(states) => const Color(0xff00a1d3),
),
shadowColor: MaterialStateProperty.resolveWith(
(states) => const Color(0xff494b52),
),
),
),
backgroundColor: const Color(0xff494b52),
);
}
2 changes: 1 addition & 1 deletion lib/utils/debug_mode.dart
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ class DebugUtils {
String get baseUrl {
assert(_inDebugMode = true);
if (_inDebugMode) {
return "https://dev.cloud.gatego.io/";
return "https://api-dev.gatego.io/";
} else {
return "https://cloud.gatego.io/";
}
Expand Down

0 comments on commit abdc26f

Please sign in to comment.