platform/lib/browser.dart

49 lines
1.6 KiB
Dart
Raw Normal View History

2016-06-25 18:37:49 +00:00
/// Browser library for the Angel framework.
library angel_client.browser;
2016-12-09 00:24:07 +00:00
import 'dart:async' show Future;
2016-06-25 18:37:49 +00:00
import 'dart:convert' show JSON;
2016-12-09 00:24:07 +00:00
import 'dart:html' show window;
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
}
}
2016-06-25 18:37:49 +00:00
}