7
votes

I have a structural question regarding angulardart and sign in flows. I have a service that talks a server and has methods like login(), logout(), loggedIn(). That is all working really nicely in angular but i am looking for a best practice way to incorporate the login flow into my application.

The app requires the user to be logged in. So would i reroute to a custom "login" view at startup when the user is not logged in? Would i switch parts of my main index.html when not logged in? Would i create a custom component handling the login?

Is there a common angular pattern for such an scenario?

1

1 Answers

7
votes

My current solution is based on routing. I created views for sign in and a landing page. When the user is on the sign in page and logs in he is routed to the landing page. When a user is not authenticated and enters any path on the website he is redirected to the sign in page.

here is the RouteInitializer:

  ..addRoute(
      name: 'signin',
      path: '/signin',
      enter: view('view/signin.html'))
  ..addRoute(
      name: 'dashboard',
      path: '/dashboard',
      defaultRoute: true,
      preEnter: _ensureAuthenticated,
      enter: view('view/dashboard.html'))  

The _ensureAuthenticated() method has to be set as the preEnter callback and evaluates the login state:

  _ensureAuthenticated(RoutePreEnterEvent routeEvent) {
    if (!_userService.loggedIn) {
      routeEvent.allowEnter(new Future<bool>.value(false));
      _router.go('signin', {});
    }
  }

While this works nicely, the _ensureAuthenticated() method has to be set as a preEnter callback in every route. Is there a way to more easily catch the preEnter globally? Setting it on the root route does not work.