Blocking unauthorized access

With all this in place, it’s time to actually prevent unlogged users from accessing protected content. In our case, it just entails protecting the task editing form component from unauthorized requests.

With that knowledge to hand, protecting the task editor component from undesired visits becomes quite simple. Open the TaskEditorComponent file, import our new AuthenticationService provider, and check whether the user is authorized by binding the execution of the static isAuthorized() method to the CanActivate decorator:

app/tasks/task-editor.component.ts

...
// Other import statements remain as they are already
import {
  Task,
  TaskService,
  AuthenticationService } from '../shared/shared';

@Component({
  selector: 'pomodoro-tasks-editor',
  directives: [ROUTER_DIRECTIVES],
  providers: [Title],
  templateUrl: 'app/tasks/task-editor.component.html',
  styles: [`
        .ng-valid { border-color: #3c763d; }
        .ng-invalid { border-color: #a94442; }
        .ng-untouched { border-color: #999999; }
    `]
})
@CanActivate(AuthService.isAuthorized)
export default class TaskEditorComponent implements OnActivate, CanDeactivate, OnDeactivate {
  // The class implementation remains the same
  ...
}

And that’s it! Now, any unlogged user attempting to access the protected task editor component will get nothing! If you look carefully at the @CanActivate() decorator, you will understand why we defined the isAuthorized() method of the AuthenticationService as static. The reason relies on the fact that we can only inject dependency singletons in our components but not in decorators. While this is not exactly true (we can leverage the provide() injector to bring the desired singleton although the code required is nowhere near as simple or neat), the truth is that this implementation is simple: providing the same level of effectiveness in a neat and clear fashion.



Note

The ideal scenario would be to inject both the AuthenticationService and the Router providers in the CanActivate implementation, and then redirect the user to the login page should the user is not logged in.

Unfortunately, there is still no formal support for dependency injection in the context of the CanActivate router hook. However, this issue is part of the features that will become part of Angular 2 Final. It is quite likely that the @CanActivate decorator will be replaced by an analogue instance method of a parent routing component once Angular 2 becomes final eventually. Please refer to the official documentation.