Protected Routes in Angular.jS

Hey there internet!

So there I was developing a web application for one of my projects! One basic requirement for any web application is protected routes or Authenticated routes or maybe :

“ Those routes which an unauthenticated user cannot access”.

So, now we know what unauthenticated routes are! :P. Let’s see how to make these in Angular.

Simple routing using ngRoute module

You can see that its a pretty simple and basic code. Now, lets suppose that I have all my protected routes starting with ‘/user’ or ‘/faculty’. I’ll do a simple thing to make these routes secure. I have a service for all authentication purpose called Auth.

Now let’s suppose a user enters a protected url, for example consider ‘localhost/user/home’ in this case. Whenever I enter a route we have an event started known as $routeChangeStart. So, with this event ongoing we know that the route is changing, so now we can intercept the process. Let’s do it!

app.run(function ($rootScope, $location,$window,Auth,$route) {
 $rootScope.$on(“$routeChangeStart”, function (event, next, current) {
 var url = $window.location.pathname;
 if ((!Auth.isLoggedIn()) && (url.indexOf(‘/user/’)!== -1)) {
 $location.path(‘/login’);
 }
 });
 })

So this simple piece of code helps me with all the issues that I was facing. Simple and straight. I don’t say that this is the perfect way to do this, but this is working fine! I welcome more improvements to this function.

Cheers !

A single golf clap? Or a long standing ovation?

By clapping more or less, you can signal to us which stories really stand out.