authenticateViaPopup method

  1. @override
Stream<String> authenticateViaPopup(
  1. String url, {
  2. String eventName = 'token',
  3. String? errorMessage,
})
override

Opens the url in a new window, and returns a Stream that will fire a JWT on successful authentication.

Implementation

@override
Stream<String> authenticateViaPopup(String url,
    {String eventName = 'token', String? errorMessage}) {
  var ctrl = StreamController<String>();
  var wnd = window.open(url, 'angel_client_auth_popup');

  Timer t;
  StreamSubscription? sub;
  t = Timer.periodic(Duration(milliseconds: 500), (timer) {
    if (!ctrl.isClosed) {
      if (wnd.closed!) {
        ctrl.addError(AngelHttpException.notAuthenticated(
            message:
                errorMessage ?? 'Authentication via popup window failed.'));
        ctrl.close();
        timer.cancel();
        sub?.cancel();
      }
    } else {
      timer.cancel();
    }
  });

  sub = window.on[eventName].listen((Event ev) {
    var e = ev as CustomEvent;
    if (!ctrl.isClosed) {
      ctrl.add(e.detail.toString());
      t.cancel();
      ctrl.close();
      sub!.cancel();
    }
  });

  return ctrl.stream;
}