This repository has been archived on 2023-11-18. You can view files and clone it, but cannot push or open issues or pull requests.
ha_client/lib/managers/auth_manager.class.dart

45 lines
1.6 KiB
Dart
Raw Normal View History

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();
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) {
if (url.startsWith("http://ha-client.homemade.systems/service/auth_callback.html")) {
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,
data: "grant_type=authorization_code&code=$authCode&client_id=${Uri.encodeComponent('http://ha-client.homemade.systems')}"
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
}