platform/lib/browser.dart

74 lines
2.4 KiB
Dart
Raw Normal View History

2016-06-25 18:37:49 +00:00
/// Browser library for the Angel framework.
library angel_client.browser;
2017-02-28 21:56:59 +00:00
import 'dart:async' show Future, Stream, StreamController;
2016-06-25 18:37:49 +00:00
import 'dart:convert' show JSON;
2017-02-28 21:56:59 +00:00
import 'dart:html' show CustomEvent, window;
2016-12-09 00:24:07 +00:00
import 'package:http/browser_client.dart' as http;
2016-09-03 12:02:32 +00:00
import 'angel_client.dart';
2016-11-28 03:28:41 +00:00
import 'auth_types.dart' as auth_types;
2016-12-09 00:24:07 +00:00
import 'base_angel_client.dart';
2016-09-03 12:02:32 +00:00
export 'angel_client.dart';
2016-06-25 18:37:49 +00:00
/// Queries an Angel server via REST.
2016-12-09 00:24:07 +00:00
class Rest extends BaseAngelClient {
Rest(String basePath) : super(new http.BrowserClient(), basePath);
2016-11-28 03:28:41 +00:00
@override
2016-12-09 00:24:07 +00:00
Future<AngelAuthResult> authenticate(
{String type: auth_types.LOCAL,
2016-11-28 03:28:41 +00:00
credentials,
2016-11-29 00:42:02 +00:00
String authEndpoint: '/auth',
String reviveEndpoint: '/auth/token'}) async {
2016-11-28 03:34:04 +00:00
if (type == null) {
2016-12-03 18:21:44 +00:00
if (!window.localStorage.containsKey('token')) {
throw new Exception(
'Cannot revive token from localStorage - there is none.');
}
2016-12-09 00:24:07 +00:00
try {
final result = await super.authenticate(
credentials: {'token': JSON.decode(window.localStorage['token'])},
reviveEndpoint: reviveEndpoint);
window.localStorage['token'] = JSON.encode(authToken = result.token);
window.localStorage['user'] = JSON.encode(result.data);
return result;
} catch (e, st) {
throw new AngelHttpException(e,
message: 'Failed to revive auth token.', stackTrace: st);
}
2016-11-28 03:28:41 +00:00
} else {
2016-12-09 00:24:07 +00:00
final result = await super.authenticate(
type: type, credentials: credentials, authEndpoint: authEndpoint);
window.localStorage['token'] = JSON.encode(authToken = result.token);
window.localStorage['user'] = JSON.encode(result.data);
return result;
2016-11-28 03:28:41 +00:00
}
}
2017-02-28 21:56:59 +00:00
@override
Stream<String> authenticateViaPopup(String url,
{String eventName: 'token', String errorMessage}) {
var ctrl = new StreamController<String>();
var wnd = window.open(url, 'angel_client_auth_popup');
wnd
..on['beforeunload'].listen((_) {
if (!ctrl.isClosed) {
ctrl.addError(new AngelHttpException.notAuthenticated(
message:
errorMessage ?? 'Authentication via popup window failed.'));
ctrl.close();
}
})
..on[eventName ?? 'token'].listen((CustomEvent e) {
if (!ctrl.isClosed) {
ctrl.add(e.detail);
ctrl.close();
}
});
return ctrl.stream;
}
2016-06-25 18:37:49 +00:00
}