70 lines
2.1 KiB
Dart
70 lines
2.1 KiB
Dart
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");
|
|
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}),
|
|
);
|
|
|
|
if (response.body == "true") {
|
|
return Result.ok(true);
|
|
}
|
|
}
|
|
return Result.ok(false);
|
|
} catch (e) {
|
|
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) {
|
|
return Result.error(Exception(e));
|
|
} finally {
|
|
client.close();
|
|
}
|
|
}
|
|
}
|