Line data Source code
1 : import 'package:amadeus_proto/api/utils/api_base.dart';
2 : import 'package:amadeus_proto/api/utils/api_error.dart';
3 : import 'package:either_dart/either.dart';
4 : import 'package:flutter_secure_storage/flutter_secure_storage.dart';
5 :
6 : extension Auth on ApiBase {
7 : static const String _authRoutesPrefix = "/auth";
8 :
9 1 : Future<Either<ApiError, void>> createUser(
10 : String username, String email, String password) {
11 3 : if (username.isEmpty || email.isEmpty || password.isEmpty) {
12 1 : throw Exception(
13 : "One or more of the field (username, email, password) is empty");
14 : }
15 3 : return post<void>("$_authRoutesPrefix/sign-up", (json) {}, requestBody: {
16 : "username": username,
17 : "email": email,
18 : "password": password
19 : });
20 : }
21 :
22 2 : Future<Either<ApiError, void>> login(String email, String password) async {
23 4 : if (email.isEmpty || password.isEmpty) {
24 1 : throw Exception("One or more of the field (email, password) is empty");
25 : }
26 2 : final result = await get(
27 : "$_authRoutesPrefix/login",
28 10 : (json) => (json["token"].toString(), json["refreshToken"].toString()),
29 2 : queryParameters: {"email": email, "password": password},
30 : );
31 2 : if (result.isRight) {
32 4 : accessToken = result.right.$1;
33 4 : refreshToken = result.right.$2;
34 : const storage = FlutterSecureStorage();
35 4 : storage.write(key: "refreshToken", value: refreshToken);
36 : }
37 : return result;
38 : }
39 :
40 1 : Future<Either<ApiError, void>> refreshAuthToken() async {
41 1 : final result = await post(
42 : "$_authRoutesPrefix/refresh",
43 5 : (json) => (json["token"].toString(), json["refreshToken"].toString()),
44 2 : queryParameters: {"refreshToken": refreshToken ?? "null"},
45 : );
46 1 : if (result.isRight) {
47 2 : accessToken = result.right.$1;
48 2 : refreshToken = result.right.$2;
49 : }
50 : return result;
51 : }
52 : }
53 :
|