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

55 lines
2.0 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();
StreamSubscription deepLinksSubscription;
2019-03-26 00:18:30 +02:00
Future start({String oauthUrl}) {
2019-03-26 00:18:30 +02:00
Completer completer = Completer();
deepLinksSubscription?.cancel();
deepLinksSubscription = getUriLinksStream().listen((Uri uri) {
Logger.d("[LINKED AUTH] We got something private: $uri");
Logger.d("[LINKED AUTH] code=${uri.queryParameters["code"]}");
_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,
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) {
//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;
}
}