Skip to content

Commit

Permalink
fix(#59): corrige e melhora api do aplicativo
Browse files Browse the repository at this point in the history
  • Loading branch information
GabrielCostaDeOliveira committed Dec 19, 2024
1 parent 33c817d commit 62a0856
Show file tree
Hide file tree
Showing 11 changed files with 137 additions and 89 deletions.
28 changes: 0 additions & 28 deletions lib/core/network/AppInterceptors.dart

This file was deleted.

53 changes: 53 additions & 0 deletions lib/core/network/app_interceptors.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import 'package:aranduapp/core/data/local/StorageValue.dart';
import 'package:aranduapp/core/log/Log.dart';
import 'package:aranduapp/core/network/token_manager/auth_service.dart';
import 'package:aranduapp/core/network/token_manager/model/refresh_token_response.dart';
import 'package:dio/dio.dart';

class AppInterceptors extends Interceptor {
@override
Future<void> onRequest(
RequestOptions options, RequestInterceptorHandler handler) async {
String? token = await StorageValue.getInstance().getAuthToken();

Log.w(token);

if (token != null) {
options.headers['Authorization'] = token;
} else {
Log.w('Token não encontrado');
}

super.onRequest(options, handler);
}

@override
Future onError(DioException err, ErrorInterceptorHandler handler) async {
if (err.response?.statusCode == 401) {
try {
Log.i('Token expirado. Tentando atualizar o token...');

RefreshTokenResponse tokens =
await AuthService().refreshToken();

final requestOptions = err.requestOptions;

requestOptions.headers['Authorization'] = 'Bearer ${tokens.authToken}';

final response = await Dio().request(
requestOptions.path,
options: Options(
method: requestOptions.method,
headers: requestOptions.headers,
),
data: requestOptions.data,
);

Log.i('Token expirado atualizado.');
return handler.resolve(response);
} catch (e) {
super.onError(err, handler);
}
}
}
}
35 changes: 17 additions & 18 deletions lib/core/network/BaseApi.dart → lib/core/network/base_api.dart
Original file line number Diff line number Diff line change
@@ -1,18 +1,22 @@
import 'package:aranduapp/core/data/local/StorageValue.dart';
import 'package:aranduapp/core/log/Log.dart';
import 'package:aranduapp/core/network/AppInterceptors.dart';
import 'package:aranduapp/core/network/app_interceptors.dart';

import 'package:dio/dio.dart';

class BaseApi {
final Dio _dio;

static BaseApi? _instance;
static BaseApi? _authInstance, _nonAuthInstance;

final String url = 'https://arandu-user-service.onrender.com';

BaseApi._internal() : _dio = Dio() {
_dio.options.baseUrl = 'http://192.168.1.107:3000';
BaseApi._internal(bool auth) : _dio = Dio() {
_dio.options.baseUrl = url;
_dio.options.connectTimeout = const Duration(seconds: 5);
_dio.options.receiveTimeout = const Duration(seconds: 5);

if (auth) _dio.interceptors.add(AppInterceptors());

_dio.interceptors.add(LogInterceptor(
requestBody: true,
responseBody: true,
Expand All @@ -22,17 +26,17 @@ class BaseApi {
request: true));
}

static BaseApi getInstance() {
return _instance ??= BaseApi._internal();
static BaseApi getInstance({required bool auth}) {
if (auth) {
return _authInstance ??= BaseApi._internal(auth);
} else {
return _nonAuthInstance ??= BaseApi._internal(auth);
}
}

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);
Expand All @@ -42,11 +46,6 @@ class BaseApi {

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);
Expand Down
31 changes: 31 additions & 0 deletions lib/core/network/token_manager/auth_service.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import 'package:aranduapp/core/data/local/StorageValue.dart';
import 'package:aranduapp/core/log/Log.dart';
import 'package:aranduapp/core/network/base_api.dart';
import 'package:aranduapp/core/network/token_manager/model/refresh_token_response.dart';
import 'package:dio/dio.dart';

class AuthService {
Future<RefreshTokenResponse> refreshToken() async {
String? refresh = await StorageValue.getInstance().getRefreshToken();

assert(refresh != null);

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

RefreshTokenResponse tokens =
RefreshTokenResponse.fromJsonString(response.toString());

await StorageValue.getInstance().setAuthToken(tokens.authToken!);
await StorageValue.getInstance().setRefreshToken(tokens.refreshToken!);

Log.i("Tokens atualizados com sucesso.");

return tokens;
}

Future<void> validateToken() async {
await BaseApi.getInstance(auth: true).get(path: '/auth/validate-token');
}
}
18 changes: 18 additions & 0 deletions lib/core/network/token_manager/model/refresh_token_response.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import 'dart:convert';

class RefreshTokenResponse {

String? authToken;
String? refreshToken;

RefreshTokenResponse(this.authToken, this.refreshToken);

factory RefreshTokenResponse.fromJsonString(String jsonString) {
Map<String, dynamic> json = jsonDecode(jsonString);
return RefreshTokenResponse(
json['accessToken'] as String?,
json['refreshToken'] as String?
);
}

}
8 changes: 4 additions & 4 deletions lib/ui/login/model/LoginResponse.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,17 @@ import 'dart:convert';

class LoginResponse {

String? authToken;
String? refreshToken;
String authToken;
String refreshToken;

LoginResponse(this.authToken, this.refreshToken);


factory LoginResponse.fromJsonString(String jsonString) {
Map<String, dynamic> json = jsonDecode(jsonString);
return LoginResponse(
json['accessToken'] as String?,
json['refreshToken'] as String?
json['accessToken']! as String,
json['refreshToken']! as String
);
}

Expand Down
29 changes: 7 additions & 22 deletions lib/ui/login/service/LoginService.dart
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import 'package:aranduapp/core/data/local/StorageValue.dart';
import 'package:aranduapp/core/log/Log.dart';
import 'package:aranduapp/core/network/BaseApi.dart';
import 'package:aranduapp/core/network/base_api.dart';
import 'package:aranduapp/core/network/token_manager/auth_service.dart';
import 'package:aranduapp/ui/login/model/LoginRequest.dart';
import 'package:aranduapp/ui/login/model/LoginResponse.dart';
import 'package:dio/dio.dart';
Expand All @@ -9,7 +10,7 @@ class LoginService {
static Future<Response> login(LoginRequest loginRequest) async {
Log.d('${loginRequest.email} ${loginRequest.password}');

Response response = await BaseApi.getInstance().post(
Response response = await BaseApi.getInstance(auth: false).post(
path: '/auth/login',
data: <String, dynamic>{
'email': loginRequest.email,
Expand All @@ -19,30 +20,14 @@ class LoginService {
LoginResponse loginResponse =
LoginResponse.fromJsonString(response.toString());

assert(
loginResponse.authToken != null && loginResponse.refreshToken != null);

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

return response;
}

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');
static Future<void> validateToken() async {
await AuthService().refreshToken();
}
}
2 changes: 1 addition & 1 deletion lib/ui/login/view/LoginView.dart
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ class _LoginState extends State<_Login> {
void initState() {
super.initState();
_future = Provider.of<LoginViewModel>(context, listen: false)
.getRefreshTokenFuture();
.validateToken();
}

@override
Expand Down
8 changes: 2 additions & 6 deletions lib/ui/login/viewModel/LoginViewModel.dart
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,6 @@ import 'package:local_auth/local_auth.dart';
import 'package:aranduapp/ui/login/service/LoginService.dart';
import 'package:aranduapp/ui/login/model/LoginRequest.dart';

import 'package:aranduapp/ui/home/view/HomeView.dart';

class LoginViewModel extends ChangeNotifier {
final BuildContext context;

Expand Down Expand Up @@ -46,10 +44,8 @@ class LoginViewModel extends ChangeNotifier {
}
}

Future<void> getRefreshTokenFuture() async {
await Future.delayed(const Duration(seconds: 2));

//await LoginService.refreshToken();
Future<void> validateToken() async {
await LoginService.validateToken();
}

Future<bool> loginWithDeviceAuth() async {
Expand Down
4 changes: 2 additions & 2 deletions lib/ui/recover_account/service/RecoverAccountService.dart
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import 'package:aranduapp/core/network/BaseApi.dart';
import 'package:aranduapp/core/network/base_api.dart';
import 'package:aranduapp/ui/recover_account/model/RecoverAccountRequest.dart';

class RecoverAccountService {


static Future<void> forgetPassword(RecoverAccountRequest recoverAccountRequest) async {

await BaseApi.getInstance().post(
await BaseApi.getInstance(auth:false).post(
path: '/auth/forgot-password',
data: <String, dynamic> {
'email' : recoverAccountRequest.email,
Expand Down
10 changes: 2 additions & 8 deletions lib/ui/register_account/service/RegisterService.dart
Original file line number Diff line number Diff line change
@@ -1,20 +1,14 @@
import 'package:aranduapp/core/network/BaseApi.dart';
import 'package:dio/dio.dart';
import 'package:aranduapp/core/network/base_api.dart';
import '../model/RegisterRequest.dart';

class RegisterService {

static Future<void> register(RegisterRequest registerRequest) async {

await BaseApi.getInstance()
await BaseApi.getInstance(auth: false)
.post(path: '/users', data: <String, dynamic>{
'name': registerRequest.name,
'email': registerRequest.email,
'username': registerRequest.userName,
'password': registerRequest.password,
});

}

}

0 comments on commit 62a0856

Please sign in to comment.