Skip to content

Commit

Permalink
Merge pull request #43 from fga-eps-mds/feat#58/login_com_dispositivo
Browse files Browse the repository at this point in the history
Feat#58/login com dispositivo
  • Loading branch information
GabrielCostaDeOliveira authored Dec 15, 2024
2 parents d3e8736 + d315e1c commit 732d328
Show file tree
Hide file tree
Showing 7 changed files with 99 additions and 82 deletions.
4 changes: 3 additions & 1 deletion android/app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android">

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.USE_BIOMETRIC"/>
<uses-permission android:name="android.permission.INTERNET"/>


<application
android:label="aranduapp"
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
package com.example.aranduapp

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

class MainActivity: FlutterActivity()
class MainActivity: FlutterFragmentActivity()
35 changes: 18 additions & 17 deletions lib/core/network/AppInterceptors.dart
Original file line number Diff line number Diff line change
Expand Up @@ -3,25 +3,26 @@ import 'package:aranduapp/core/log/Log.dart';
import 'package:dio/dio.dart';

class AppInterceptors extends Interceptor {

@override
Future<void> onRequest(RequestOptions options, RequestInterceptorHandler handler) async {
super.onRequest(options, handler);

try {

String? token = await StorageValue.getInstance().getAuthToken();

if ( token != null) {
options.headers['Authorization'] = 'Bearer $token';
Log.e(token);
}
Future<void> onRequest(
RequestOptions options,
RequestInterceptorHandler handler
) async {
super.onRequest(options, handler);

handler.next(options);
try {
String? token = await StorageValue.getInstance().getAuthToken();


} catch (e) {
Log.e(e);
if (token != null) {
options.headers['Authorization'] = 'asdfasdfasdfasdfasdfasdfasdfsadfsadf';
} else {
Log.e('Token não encontrado');
}
}
} catch (e) {
Log.e('Erro ao recuperar token: $e');
}

handler.next(options);
}
}

36 changes: 25 additions & 11 deletions lib/core/network/BaseApi.dart
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@

import 'package:aranduapp/core/data/local/StorageValue.dart';
import 'package:aranduapp/core/log/Log.dart';
import 'package:aranduapp/core/network/AppInterceptors.dart';
import 'package:dio/dio.dart';
Expand All @@ -8,35 +8,49 @@ class BaseApi {

static BaseApi? _instance;

BaseApi._internal()
: _dio = Dio() {
_dio.options.baseUrl = 'https://arandu-user-service.onrender.com/';
_dio.options.connectTimeout = const Duration(seconds: 5);
BaseApi._internal() : _dio = Dio() {
_dio.options.baseUrl = 'http://192.168.1.107:3000';
_dio.options.connectTimeout = const Duration(seconds: 5);
_dio.options.receiveTimeout = const Duration(seconds: 5);

_dio.interceptors.add(AppInterceptors());
_dio.interceptors.add(LogInterceptor(requestBody: true, responseBody: true));
_dio.interceptors.add(LogInterceptor(
requestBody: true,
responseBody: true,
requestHeader: true,
error: true,
responseHeader: true,
request: true));
}

static BaseApi getInstance() {
return _instance ??= BaseApi._internal();
}

Future<Response> get({required String path, Map<String, dynamic>? queryParameters}) async {
Future<Response> get( {required String path, Map<String, dynamic>? queryParameters}) async {
try {
_dio.options.headers = {
'Authorization':
'Bearer ${await StorageValue.getInstance().getAuthToken()}',
};

return await _dio.get(path, queryParameters: queryParameters);
} catch (e) {
Log.e(e);
rethrow;
rethrow;
}
}

Future<Response> post({ required String path, Object? data}) async {
Future<Response> post({required String path, Object? data}) async {
try {
_dio.options.headers = {
'Authorization':
'Bearer ${await StorageValue.getInstance().getAuthToken()}',
};

return await _dio.post(path, data: data);
} catch (e) {
Log.e(e);
rethrow;
rethrow;
}
}
}
44 changes: 25 additions & 19 deletions lib/ui/login/service/LoginService.dart
Original file line number Diff line number Diff line change
Expand Up @@ -6,37 +6,43 @@ import 'package:aranduapp/ui/login/model/LoginResponse.dart';
import 'package:dio/dio.dart';

class LoginService {

static Future<Response> login(LoginRequest loginRequest) async {

Log.d('${loginRequest.email} ${loginRequest.password}');

Response response = await BaseApi.getInstance().post(
path: '/auth/login',
data: <String, dynamic> {
'email' : loginRequest.email,
'password': loginRequest.password
}
);

LoginResponse loginResponse = LoginResponse.fromJsonString(response.toString());
path: '/auth/login',
data: <String, dynamic>{
'email': loginRequest.email,
'password': loginRequest.password
});

assert(loginResponse.authToken != null && loginResponse.refreshToken != null);
LoginResponse loginResponse =
LoginResponse.fromJsonString(response.toString());

await StorageValue.getInstance().setAuthToken(loginResponse.authToken ?? '');
await StorageValue.getInstance().setAuthToken(loginResponse.refreshToken??'');
assert(
loginResponse.authToken != null && loginResponse.refreshToken != null);

await StorageValue.getInstance()
.setAuthToken(loginResponse.authToken ?? '');
await StorageValue.getInstance()
.setRefreshToken(loginResponse.refreshToken ?? '');

return response;

}

static Future<LoginRequest> refreshToken() async {
// TODO: implement build
throw UnimplementedError();
static Future<void> refreshToken() async {
Log.d('init reresh token');

}
await BaseApi.getInstance().get(path: '/auth/validate-token');

}
String? refresh = await StorageValue.getInstance().getRefreshToken();

assert(refresh != null);

await BaseApi.getInstance().post(
path: '/auth/refresh',
data: <String, dynamic>{'refreshToken': refresh});

Log.d('finish reresh token');
}
}
13 changes: 10 additions & 3 deletions lib/ui/login/view/LoginView.dart
Original file line number Diff line number Diff line change
Expand Up @@ -91,8 +91,15 @@ class _LoginState extends State<_Login> {
width: 291,
height: 64,
child: ElevatedButton(
onPressed: () {
viewModel.loginWithDeviceAuth();
onPressed: () async {
viewModel.loginWithDeviceAuth().then((ok) {
if (ok)
Navigator.of(context).pushReplacement(
MaterialPageRoute(
builder: (context) => const HomeView(),
),
);
});
},
child: const Text('Usar senha do celular'),
),
Expand Down Expand Up @@ -154,7 +161,7 @@ class _LoginState extends State<_Login> {
onTap: () {
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => RecoverAccount(),
builder: (context) => RecoverAccount(),
),
);
},
Expand Down
45 changes: 16 additions & 29 deletions lib/ui/login/viewModel/LoginViewModel.dart
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@

import 'package:aranduapp/core/log/Log.dart';
import 'package:flutter/material.dart';
import 'package:local_auth/local_auth.dart';
import 'package:aranduapp/ui/login/service/LoginService.dart';
Expand All @@ -7,27 +7,23 @@ import 'package:aranduapp/ui/login/model/LoginRequest.dart';
import 'package:aranduapp/ui/home/view/HomeView.dart';

class LoginViewModel extends ChangeNotifier {

final BuildContext context;

bool isLoading;

final GlobalKey<FormState> formKey;
final TextEditingController emailController;
final TextEditingController passwordController;

LoginViewModel(this.context) :
isLoading = false,
formKey = GlobalKey<FormState>(),
emailController = TextEditingController(),
passwordController = TextEditingController();
LoginViewModel(this.context)
: isLoading = false,
formKey = GlobalKey<FormState>(),
emailController = TextEditingController(),
passwordController = TextEditingController();



Future<void> loginWithEmailAndPassword() async {

// TODO use mutex to make this
if (isLoading){
if (isLoading) {
return;
}

Expand All @@ -39,8 +35,8 @@ class LoginViewModel extends ChangeNotifier {
throw Exception('Valores inválidos');
}

await LoginService.login(LoginRequest(emailController.text, passwordController.text));

await LoginService.login(
LoginRequest(emailController.text, passwordController.text));
} catch (e) {
rethrow;
} finally {
Expand All @@ -50,21 +46,12 @@ class LoginViewModel extends ChangeNotifier {
}

Future<void> getRefreshTokenFuture() async {
// TODO
//return await LoginService.refreshToken();
throw UnimplementedError();
await LoginService.refreshToken();
}

Future<void> loginWithDeviceAuth() async {
bool value = await LocalAuthentication().authenticate(
localizedReason: 'Toque com o dedo no sensor para logar');

if (!value)
throw Exception();

}



Future<bool> loginWithDeviceAuth() async {
Log.d('init loginWithDeviceAuth');
return await LocalAuthentication()
.authenticate(localizedReason: 'Toque com o dedo no sensor para logar');
}
}

0 comments on commit 732d328

Please sign in to comment.