4

I'm not quite ready to jump into Angular 2, but I wanted to tackle their new router and components.

For background, I am using a Python instance on Google App Engine that uses Endpoints in conjunction with Angular.

How do I use AngularJS 1.5's Component Router to serve html with and without an authenticated user? I want to accomplish this in the most "Angular way" as possible. The current documentation is lost on me.

David Kirk
  • 342
  • 3
  • 5
  • I am asking myself the same question. It seems that one way using Angular's 2 version is to extend RouterOutlet but I can't find the way for Angular 1.5 either. – Boris Mar 28 '16 at 17:33
  • @Boris `$canActivate` looks like that is where I can deny access if the user is logged out by returning a promise that returns false. Inside that I think I can `$rootRouter.navigate(["LogIn"])`. – David Kirk Mar 28 '16 at 20:11
  • Agreed, but I was hoping for a more generic solution where you can handle authentication for any route, rather than a per-component solution. – Boris Mar 30 '16 at 10:11

1 Answers1

0

Recently I struggled with the same thing. I solved it like this:

In component definition object add $canActivate property:

import { MainController } from './main.controller';

export class MainComponent {

    constructor() { 
        this.controller = MainController;
        this.templateUrl = 'app/main/main.html';
        this.$canActivate = (Auth) => {
            'ngInject';

            return Auth.redirectUnauthenticated();
        };
    }
}

Create Authentication service, which holds all the auth info:

export class AuthService {

    constructor($auth, UserApi, $q, $rootRouter, Storage) {
        'ngInject';

        this.$auth = $auth;
        this.$q = $q;
        this.$rootRouter = $rootRouter;
        this.storage = Storage;
        this.userApi = UserApi.resource;
    }

    /**
     * Check user's status
     */
    isAuthenticated() {
        return this.$auth.isAuthenticated();
    }

    /**
     * Redirect user to login page if he is not authenticated
     */
    redirectUnauthenticated() {
        if (!this.$auth.isAuthenticated()) {
            this.$rootRouter.navigate(['Login']);

            return false;
        }

        return true;
    }
}

NOTE: $auth service comes from satellizer library.

Basically, in every component (which you can navigate to), where you need only authenticated access, put the same $canActivate property. I'm not sure if this is the nicest solution, but it works :)

stic
  • 66
  • 3