Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: added local biometric authentication #19

Merged
merged 6 commits into from
Oct 3, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions android/app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.USE_BIOMETRIC"/>
<application
android:label="login_mobile"
android:name="${applicationName}"
Expand All @@ -7,10 +8,12 @@
android:name=".MainActivity"
android:exported="true"
android:launchMode="singleTop"
android:theme="@style/LaunchTheme"
android:theme="@style/Theme.AppCompat.Light.DarkActionBar"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
android:hardwareAccelerated="true"
android:windowSoftInputMode="adjustResize">
android:windowSoftInputMode="adjustResize"
android:enableOnBackInvokedCallback="true"
>
<!-- Specifies an Android theme to apply to this Activity as soon as
the Android process has started. This theme is visible to the user
while the Flutter UI initializes. After that, this theme continues
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package com.example.login_mobile

import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.android.FlutterFragmentActivity

class MainActivity: FlutterActivity() {
class MainActivity: FlutterFragmentActivity() {
// ...
}

4 changes: 2 additions & 2 deletions lib/features/auth/domain/entities/user.dart
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
class User {
//final String uuid;
//final String username;
final String? username;
//final int statusCode;
//final String? message;
final String token;

//TODO?: add required
User({
//required this.uuid,
//required this.username,
required this.username,
//required this.statusCode,
//required this.message,
required this.token,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,13 @@ import 'package:login_mobile/features/auth/infrastructure/infrastructure.dart';
class AuthDataSourceImpl extends AuthDataSource {
final dio = Dio(BaseOptions(
baseUrl: Enviroment.apiURL,

));

@override
Future<User> checkAuthStatus(String token) async {
try {
final response = await dio.post('/challenge',
final response = await dio.post('/refreshtoken',
data: {'token': token},
options: Options(headers: {'Authorization': 'Bearer $token'}));
final user = UserMapper.userJsonToEntity(response.data);
return user;
Expand Down
5 changes: 3 additions & 2 deletions lib/features/auth/infrastructure/mappers/user_mapper.dart
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,12 @@ class UserMapper {

static User userJsonToEntity(Map<String, dynamic> json) {
return User(
//TODO: setup new user model with new fields returned from Proxy...
//uuid: json['uuid'],
//username: json['username'],
username: json['username'],
//statusCode: json['statusCode'],
//message: json['message'],
token: json['jwt']
token: json['token']
);
}
}
144 changes: 126 additions & 18 deletions lib/features/auth/presentation/providers/auth_provider.dart
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,11 @@ Nos permite a nosotros llegar a nuestro backend directamente
DataSource tiene las conexiones e implementaciones necesarias
*/

import 'dart:async';

import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:local_auth/local_auth.dart';
import 'package:login_mobile/features/auth/infrastructure/infrastructure.dart';
import 'package:login_mobile/features/shared/infrastructure/inputs/services/key_value_storage_impl.dart';
import 'package:login_mobile/features/shared/infrastructure/inputs/services/key_value_storage_services.dart';
Expand All @@ -28,29 +32,46 @@ final authProvider = StateNotifierProvider<AuthNotifier, AuthState>((ref) {
class AuthNotifier extends StateNotifier<AuthState> {
final AuthRepository authRepository;
final KeyValueStorageService keyValueStorageService;
final LocalAuthentication auth = LocalAuthentication();
final Function? closeModalCallback;

AuthNotifier({
required this.authRepository,
required this.keyValueStorageService,
this.closeModalCallback,
}) : super(AuthState()) {
checkAuthStatus();
} //no hace falta mandar nada porque todo son valores opcinonales
//estas funciones terminan delegando en el repositorio

Future<void> loginUser(String email, String password) async {
Future<void> loginUser(String username, String password,
{bool biometric = false, bool authBiometric = false}) async {
await Future.delayed(const Duration(milliseconds: 500));

try {
final user = await authRepository.login(email, password);
_setLoggedUser(user);
final user = await authRepository.login(username, password);
_setUsername(username);
if (biometric == false) {
_setTempLoggedUser(user);
}
if (biometric == true && state.user != null) {
_setBiometricLoggedUser(user);
}
if (closeModalCallback != null) {
closeModalCallback!();
}
} on CustomError catch (e) {
logout(e.message);
if (biometric == false) {
logout(e.message);
} else {
biometricError(e.message);
}
} catch (e) {
logout('Something went wrong');
if (biometric == false) {
logout('Something went wrong');
} else {
biometricError('Your username or password is incorrect');
}
}

//final user = await authRepository.login(email, password);
//state = state.copyWith(user: user, authStatus: AuthStatus.authenticated); //copia del usuario donde ya tengo el estado
}

//TODO: implementar el registro
Expand All @@ -60,49 +81,136 @@ class AuthNotifier extends StateNotifier<AuthState> {
void checkAuthStatus() async {
final token = await keyValueStorageService.getValue<String>('token');
if (token == null) return logout();

try {
//el repositorio hace la auth
final user = await authRepository.checkAuthStatus(token);
_setLoggedUser(user);
_setBiometricLoggedUser(user);
} catch (e) {
logout();
}
}

void _setLoggedUser(User user) async {
void _setTempLoggedUser(User user) async {
state = state.copyWith(
user: user, errorMessage: '', authStatus: AuthStatus.authenticated);
}

Future<void> _setBiometricLoggedUser(User user) async {
await keyValueStorageService.setKeyValue('token', user.token);
await keyValueStorageService.setKeyValue('hasBiometric', true);
state = state.copyWith(
user: user,
errorMessage: '',
authStatus: AuthStatus.authenticated,
hasBiometric: true,
);
}

void disableBiometric(ref) async {
await keyValueStorageService.removeKey('token');
await keyValueStorageService.removeKey('hasBiometric');
state = state.copyWith(
user: user, errorMessage: '', authStatus: AuthStatus.authenticated);
user: null,
errorMessage: '',
authStatus: AuthStatus.authenticated,
hasBiometric: false);
//Aqui puedo abrir otro modal
// showModalBottomSheet(
// isScrollControlled: true,
// context: ref,
// builder: (context) => const CustomLogin());
}

void _setUsername(String username) async {
await keyValueStorageService.setKeyValue('username', username);
}

Future<void> logout([String? errorMessage]) async {
await keyValueStorageService.removeKey('token');
//await keyValueStorageService.removeKey('token');
await keyValueStorageService.removeKey('username');
state = state.copyWith(
user: null,
errorMessage: errorMessage,
authStatus: AuthStatus.notAuthenticated);
}

Future<void> biometricError([String? errorMessage]) async {
state = state.copyWith(
errorMessage: errorMessage,
);
}

Future<bool> authWithBiometrics() async {
bool authenticated = false;
try {
state = state.copyWith(authStatus: AuthStatus.checking);
authenticated = await auth.authenticate(
localizedReason:
'Scan your fingerprint (or face or whatever) to authenticate',
options: const AuthenticationOptions(
stickyAuth: true,
biometricOnly: true,
),
);
if (authenticated) {
state = state.copyWith(authStatus: AuthStatus.authenticated);
} else {
state = state.copyWith(authStatus: AuthStatus.notAuthenticated);
}
} on PlatformException catch (e) {
state = state.copyWith(
errorMessage: 'Error - ${e.message}',
authStatus: AuthStatus.notAuthenticated);
}
return authenticated;
}

Future<bool> loginWithBiometrics() async {
try {
final token = await keyValueStorageService.getValue<String>('token');
if (token == null) {
return false;
}
final user = await authRepository.checkAuthStatus(token);
state = state.copyWith(
user: user,
errorMessage: '',
authStatus: AuthStatus.authenticated,
);
authWithBiometrics();
return true;
} catch (e) {
state = state.copyWith(
errorMessage: 'Error: $e',
authStatus: AuthStatus.notAuthenticated,
);
return false;
}
}
}

enum AuthStatus { checking, authenticated, notAuthenticated }
enum AuthStatus { checking, authenticated, notAuthenticated, hasBiometric }

class AuthState {
final AuthStatus authStatus;
final User? user;
final String errorMessage;
final bool? hasBiometric;

AuthState(
{this.authStatus = AuthStatus.checking,
this.user,
this.errorMessage = ''});
this.errorMessage = '',
this.hasBiometric});

AuthState copyWith(
{AuthStatus? authStatus, User? user, String? errorMessage}) =>
{AuthStatus? authStatus,
User? user,
String? errorMessage,
bool? hasBiometric}) =>
AuthState(
authStatus: authStatus ?? this.authStatus,
user: user ?? this.user,
errorMessage: errorMessage ?? this.errorMessage,
hasBiometric: hasBiometric ?? this.hasBiometric,
);
}
28 changes: 26 additions & 2 deletions lib/features/auth/presentation/providers/login_form_provider.dart
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ class LoginFormState {
// LoginFormNotifier es el que controla cuando cambia el email y el password
//! 2 - Cómo implemenrtamos un notifier provider
class LoginFormNotifier extends StateNotifier<LoginFormState> {
final Function(String, String) loginUserCallback;
final Function(String, String, {bool biometric}) loginUserCallback;
LoginFormNotifier({required this.loginUserCallback})
: super(LoginFormState());
onUsernameChange(String value) {
Expand All @@ -73,8 +73,32 @@ class LoginFormNotifier extends StateNotifier<LoginFormState> {

onFormSubmitted() async {
_touchEveryField();
if (!state.isValid) return;
if (!state.isValid) {
return;
}
state = state.copyWith(isPosting: true); //actualiza el estado

await loginUserCallback(state.username.value, state.password.value);

state = state.copyWith(isPosting: false);
}

onFormSubmittedBiometric() async {
_touchEveryField();
if (state.isValid) {
return await loginUserCallback(state.username.value, state.password.value,
biometric: true);
}
state = state.copyWith(isPosting: true); //actualiza el estado

state = state.copyWith(isPosting: false);
}

onFormAuthBiometric() async {
_touchEveryField();
if (!state.isValid) {
return;
}
state = state.copyWith(isPosting: true); //actualiza el estado

await loginUserCallback(state.username.value, state.password.value);
Expand Down
32 changes: 26 additions & 6 deletions lib/features/auth/presentation/screens/login_screen.dart
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,9 @@ class _LoginForm extends ConsumerWidget {
@override
//WidgetRef ref: todos los provider de RiverPod
Widget build(BuildContext context, WidgetRef ref) {
final textStyles = Theme.of(context).textTheme;
final hasBiometric = ref.watch(authProvider).hasBiometric;

final loginForm =
ref.watch(loginFormProvider); //acceso al state no al notifier

Expand All @@ -83,8 +86,6 @@ class _LoginForm extends ConsumerWidget {
showSnackbar(context, next.errorMessage);
});

final textStyles = Theme.of(context).textTheme;

return Padding(
padding: const EdgeInsets.symmetric(horizontal: 50),
child: Column(
Expand Down Expand Up @@ -112,10 +113,29 @@ class _LoginForm extends ConsumerWidget {
width: double.infinity,
height: 60,
child: CustomFilledButton(
text: 'Sign in',
buttonColor: Colors.black,
onPressed: loginForm.isPosting ? null : ref.read(loginFormProvider.notifier).onFormSubmitted //si no posteo mando ref a la func
)),
text: 'Sign in',
buttonColor: Colors.black,
onPressed: loginForm.isPosting
? null
: ref
.read(loginFormProvider.notifier)
.onFormSubmitted //si no posteo mando ref a la func
)),
const SizedBox(height: 10),
if (hasBiometric == true)
SizedBox(
width: double.infinity,
height: 60,
child: CustomFilledButton(
text: 'Sign in with biometric',
buttonColor: Colors.black,
onPressed: loginForm.isPosting
? null
: () {
ref
.read(authProvider.notifier)
.loginWithBiometrics();
})),
const Spacer(flex: 2),
Row(
mainAxisAlignment: MainAxisAlignment.center,
Expand Down
Loading