2019-08-30 15:04:51 +03:00
|
|
|
part of '../main.dart';
|
2019-03-26 00:18:30 +02:00
|
|
|
|
|
|
|
class AuthManager {
|
|
|
|
|
|
|
|
static final AuthManager _instance = AuthManager._internal();
|
|
|
|
|
|
|
|
factory AuthManager() {
|
|
|
|
return _instance;
|
|
|
|
}
|
|
|
|
|
|
|
|
AuthManager._internal();
|
|
|
|
|
2019-10-20 19:45:44 +03:00
|
|
|
Future start({String oauthUrl}) {
|
2019-03-26 00:18:30 +02:00
|
|
|
Completer completer = Completer();
|
2020-01-27 23:12:05 +02:00
|
|
|
final flutterWebviewPlugin = new FlutterWebviewPlugin();
|
|
|
|
flutterWebviewPlugin.onUrlChanged.listen((String url) {
|
2020-01-29 19:31:02 +02:00
|
|
|
if (url.startsWith("http://ha-client.estevez.dev/service/auth_callback.html")) {
|
2020-01-27 23:12:05 +02:00
|
|
|
Logger.d("url=$url");
|
|
|
|
String authCode = url.split("=")[1];
|
|
|
|
Logger.d("authCode=$authCode");
|
|
|
|
Logger.d("We have auth code. Getting temporary access token...");
|
|
|
|
ConnectionManager().sendHTTPPost(
|
|
|
|
endPoint: "/auth/token",
|
|
|
|
contentType: "application/x-www-form-urlencoded",
|
|
|
|
includeAuthHeader: false,
|
2020-01-29 19:31:02 +02:00
|
|
|
data: "grant_type=authorization_code&code=$authCode&client_id=${Uri.encodeComponent('http://ha-client.estevez.dev')}"
|
2019-03-26 00:18:30 +02:00
|
|
|
).then((response) {
|
2019-08-26 18:55:12 +03:00
|
|
|
Logger.d("Got temp token");
|
2019-03-26 00:18:30 +02:00
|
|
|
String tempToken = json.decode(response)['access_token'];
|
2020-01-27 23:12:05 +02:00
|
|
|
Logger.d("Closing webview...");
|
2019-04-05 14:07:03 +03:00
|
|
|
eventBus.fire(StartAuthEvent(oauthUrl, false));
|
2019-03-26 00:18:30 +02:00
|
|
|
completer.complete(tempToken);
|
|
|
|
}).catchError((e) {
|
|
|
|
Logger.e("Error getting temp token: ${e.toString()}");
|
2019-04-05 14:07:03 +03:00
|
|
|
eventBus.fire(StartAuthEvent(oauthUrl, false));
|
2019-09-04 22:46:14 +03:00
|
|
|
completer.completeError(HAError("Error getting temp token"));
|
2020-01-27 23:12:05 +02:00
|
|
|
}).whenComplete(() => flutterWebviewPlugin.close());
|
|
|
|
}
|
|
|
|
});
|
|
|
|
Logger.d("Launching OAuth");
|
|
|
|
eventBus.fire(StartAuthEvent(oauthUrl, true));
|
2019-03-26 00:18:30 +02:00
|
|
|
return completer.future;
|
2020-01-27 23:12:05 +02:00
|
|
|
}
|
2019-03-26 00:18:30 +02:00
|
|
|
|
|
|
|
}
|