feat: added authentification and redirection
This commit is contained in:
parent
1c9c5ce5fe
commit
ef641d4023
24 changed files with 731 additions and 173 deletions
77
lib/data/services/auth_client.dart
Normal file
77
lib/data/services/auth_client.dart
Normal file
|
|
@ -0,0 +1,77 @@
|
|||
import 'dart:convert';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
|
||||
import 'package:seshat/config/constants.dart';
|
||||
import 'package:seshat/utils/result.dart';
|
||||
import "package:http/http.dart" as http;
|
||||
|
||||
class AuthClient {
|
||||
AuthClient();
|
||||
FlutterSecureStorage? _secureStorage;
|
||||
|
||||
Future<void> _initStore() async {
|
||||
_secureStorage ??= const FlutterSecureStorage(
|
||||
aOptions: AndroidOptions(encryptedSharedPreferences: true),
|
||||
);
|
||||
}
|
||||
|
||||
Future<Result<bool>> hasValidToken() async {
|
||||
try {
|
||||
await _initStore();
|
||||
bool hasToken = await _secureStorage!.containsKey(key: "token");
|
||||
debugPrint("\n\n\n${hasToken == true} => HAS_TOKEN\n\n\n");
|
||||
if (hasToken) {
|
||||
var token = await _secureStorage!.read(key: "token");
|
||||
var url = Uri.parse("https://$apiBasePath/token-check");
|
||||
var response = await http.post(
|
||||
url,
|
||||
headers: {"Content-Type": "application/json"},
|
||||
body: jsonEncode({"token": token}),
|
||||
);
|
||||
debugPrint(
|
||||
"\n\n\n${response.body is String} => ${response.body}\n\n\n",
|
||||
);
|
||||
|
||||
if (response.body == "true") {
|
||||
return Result.ok(true);
|
||||
}
|
||||
}
|
||||
return Result.ok(false);
|
||||
} catch (e) {
|
||||
debugPrint(e.toString());
|
||||
return Result.error(Exception(e));
|
||||
}
|
||||
}
|
||||
|
||||
Future<Result<String>> login(String username, String password) async {
|
||||
var client = http.Client();
|
||||
try {
|
||||
await _initStore();
|
||||
var url = Uri.parse("https://$apiBasePath/auth");
|
||||
var response = await client.post(
|
||||
url,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Accept": "application/json",
|
||||
},
|
||||
body: jsonEncode({"password": password, "username": username}),
|
||||
);
|
||||
if (response.statusCode == 200) {
|
||||
var json = jsonDecode(response.body);
|
||||
await _secureStorage!.write(key: "token", value: json["access_token"]);
|
||||
return Result.ok(json["access_token"]);
|
||||
} else if (response.statusCode == 401) {
|
||||
return Result.error(Exception("Wrong credentials"));
|
||||
} else {
|
||||
return Result.error(Exception("Token creation error"));
|
||||
}
|
||||
} catch (e, stackTrace) {
|
||||
debugPrint(e.toString());
|
||||
debugPrintStack(stackTrace: stackTrace);
|
||||
return Result.error(Exception(e));
|
||||
} finally {
|
||||
client.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in a new issue