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
|
|
|
StreamSubscription deepLinksSubscription;
|
2019-03-26 00:18:30 +02:00
|
|
|
|
2019-10-20 19:45:44 +03:00
|
|
|
Future start({String oauthUrl}) {
|
2019-03-26 00:18:30 +02:00
|
|
|
Completer completer = Completer();
|
2019-10-20 19:45:44 +03:00
|
|
|
deepLinksSubscription?.cancel();
|
|
|
|
deepLinksSubscription = getUriLinksStream().listen((Uri uri) {
|
2019-10-20 21:22:51 +03:00
|
|
|
Logger.d("[LINKED AUTH] We got something private");
|
2019-10-20 19:45:44 +03:00
|
|
|
_getTempToken(oauthUrl, uri.queryParameters["code"])
|
|
|
|
.then((tempToken) => completer.complete(tempToken))
|
|
|
|
.catchError((_){
|
|
|
|
completer.completeError(HAError("Auth error"));
|
|
|
|
});
|
|
|
|
}, onError: (err) {
|
|
|
|
Logger.e("[LINKED AUTH] Error handling linked auth: $e");
|
|
|
|
completer.completeError(HAError("Auth error"));
|
|
|
|
});
|
|
|
|
Logger.d("Launching OAuth");
|
|
|
|
eventBus.fire(StartAuthEvent(oauthUrl, true));
|
|
|
|
return completer.future;
|
|
|
|
}
|
|
|
|
|
|
|
|
Future _getTempToken(String oauthUrl,String authCode) {
|
|
|
|
Completer completer = Completer();
|
|
|
|
ConnectionManager().sendHTTPPost(
|
2019-03-26 00:18:30 +02:00
|
|
|
endPoint: "/auth/token",
|
|
|
|
contentType: "application/x-www-form-urlencoded",
|
|
|
|
includeAuthHeader: false,
|
2019-10-20 19:45:44 +03:00
|
|
|
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'];
|
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) {
|
2019-08-16 12:32:36 +03:00
|
|
|
//flutterWebviewPlugin.close();
|
2019-03-26 00:18:30 +02:00
|
|
|
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"));
|
2019-03-26 00:18:30 +02:00
|
|
|
});
|
|
|
|
return completer.future;
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|