Tuesday, July 30, 2013

Setting up Auth in an Angular App

So I was tasked to set up some type of simple authentication system using Angular.  The basis was that there be a login page, and a main page.  If a user navigates directly to the app, then they go to the login page.  If the user clicks an authorized link, they are logged in and taken to the main page.  So to get started I laid out my app with three routes:


var tmapp = angular.module('tmapp', [])
.config(['$routeProvider', function($routeProvider) {
    $routeProvider
        .when('/',{templateUrl: '/partials/admin/login.html',   controller: LoginController})
        .when('/main',{templateUrl:'/partials/admin/splash.html',controller:SplashController})
        .otherwise({redirectionTo:'/'});
}]);

Simple enough, the base route displays the login page, and the main route displays the splash page. Now for problem number one, if I type in /main, the I am able to visit that page. Obfuscating the code would make it harder, but definitely not too hard to see the routes my app has, so this isn't secure.

To solve the problem, we can add a .run function. This will get ran when the app is initialized. We can tie in some pretty important event bindings at this level to ensure that the proper authentication is happening.

tmapp.run(['$rootScope',function($rootScope){
}]);

Now inside, we can use the $rootScope as a $scope variable. Think of $rootScope as the parent of $scope, and all $scope variables inherit the properties of $rootScope. So if I make an event binding on $rootScope, then the child $scope also has that binding. For instance:

tmapp.run(['$rootScope',function($rootScope){
    $rootScope.$on('$routeChangeStart', function(event, next, current){
        //check if logged in
        //redirect if not
    }
}]);

Now every time a route is called, this function will be called. Of course, nothing yet exists in the function, but we could test it using console.log or alert and we would see that every time the route changed, the function was called.

If I want to check logged in status, where do I put it? Not in a controller, because those only handle functions specific for the route, and this function would need to be for ALL routes AND be persistent between routes. If I set $scope.myVar=1 with a button on my view that increments it by 1 each click, you would see the count increase. If I refreshed the route, the count would be back at 1 again, so $scope data is not persistent. The answer is to create a service. Services are static across all routes, so it would be a perfect place to check and store authentication. To set up a service, you use the factory method.

.factory('sessionHandler',['$http','$location',function($http,$location){
    var setLoggedIn=function(){
        s['auth']=true;
    };
    var redirectHome=function(){
        s={};
        $location.path('/',true);
    };
    var s={};
    return {
        set:function(key,val){
            s[key]=val;
        },
        get:function(key){
            if(!angular.isDefined(s[key])){
                return false;
            }
            return s[key];
        },
        logout:function(){
            $http.get('/admin/logout').success(function(){
                s={};
                window.location=window.location.origin+window.location.pathname;
            });
        },
        checkLoggedIn:function(){
            if(s['auth']){
                return true;
            }else{
                $http.get('/admin/authStatus').success(setLoggedIn).error(redirectHome);
            }
        }
    };
}]);

This is a big blob of code that I am now going to walk through and explain.  Again, the first line is the simple syntax to set up your service, injecting specific angular services into my service.  Then we move on to some private functions (setLoggedIn and redirectHome).  The first sets a variable called s['auth'] as true, which is the property we look for when the service starts to see if a user is logged in.  The second function essentially unsets our s variable and takes them to the login screen, so this is called when they are not logged in.  Finally, we return the service functions that interact with the private functions.  The functions set and get can be used to set/get data across the controllers, much like session variables can be used on the server.  The logout function sends the request to the server to log the user out, resets the s variable, and refreshes the app, which takes them back to the initial route (/).  The last function, checkLoggedIn, checks for s['auth'].  If it can't find it, it makes the request to the server to see if the user is logged in on the server.  If it gets a successful response, it sets the s['auth'] variable, otherwise it redirects them to the home and unsets any data they had.

So now to implement this, in our app.run function.

tmapp.run(['$rootScope','sessionHandler','$location',function($rootScope,sessionHandler,$location){
    $rootScope.$on('$routeChangeStart', function(event, next, current){
        if(sessionHandler.checkLoggedIn()&&($location.path()===''||$location.path()==='/')){
            $location.path('/main',true);    
        }
    }
}]);

Let's walk through this. First, notice the additional dependencies I have injected: my service (sessionHandler), and $location. Second, the if statement executes checkLoggedIn(). If it fails, it will automatically redirect the user to the home page because that is what checkLoggedIn does in the function. Next, it checks the current location. If they are on the login page, which has a blank or null route, then it will redirect them to the main page. Otherwise, the function just leaves the user alone.

If a user navigates to the main page without logging in, the service will catch that and redirect the user back to the login page. If they login, and then try navigating back to the login page, the check will catch that as well and redirect the user to the main page. That is it!

Now for some advanced material. Using sessionStorage. If a user refreshes the page, their data will be lost. s['auth'] will be undefined, and the check will need to take place again. Any other variables you set in the sessionHandler service will be wiped out. So to implement this, we need to modify the sessionHandler.

.factory('sessionHandler',['$http','$location',function($http,$location){
    var setLoggedIn=function(){
        s['auth']=true;
        sessionStorage.data=angular.toJson(s);
    };
    var redirectHome=function(){
        s={};
        sessionStorage.data=angular.toJson(s);
        $location.path('/',true);
    };
    if(angular.isDefined(sessionStorage.init)){
        var s=angular.fromJson(sessionStorage.data);
    }else{
        var s={};
        sessionStorage.init=true;
    }
    return {
        set:function(key,val){
            s[key]=val;
            sessionStorage.data=angular.toJson(s);
        },
        get:function(key){
            if(!angular.isDefined(s[key])){
                return false;
            }
            return s[key];
        },
        logout:function(){
            $http.get('/admin/logout').success(function(){
                s={};
                sessionStorage.data=angular.toJson(s);
                window.location=window.location.origin+window.location.pathname;
            });
        },
        checkLoggedIn:function(){
            if(s['auth']){
                return true;
            }else{
                $http.get('/admin/authStatus').success(setLoggedIn).error(redirectHome);
            }
        }
    };
}]);

You will notice just a few additional lines, but most notably, the if statement. What it does is check to see if a sessionStorage variable is currently set. If it is, then it grabs the data and parses it into our "s" variable. If not, it initializes the session storage and an empty "s" variable. All the other lines simply store data to the sessionStorage.data variable in JSON format. This is done to minimize the amount of variables stored by the browser, and hopefully help hide some of the data. The other reason I chose to do it this way is because sessionStorage does not store objects. Even simple objects without functions cannot be stored in sessionStorage, only strings. So by JSONifying the object, you can store it easily in sessionStorage. Everything else is pretty self explanatory. You can now use the service in your controllers and persist data AND logins across a page refresh.

That concludes my tutorial for now. It is very simple, and I didn't cover anything else except using the app.run and app.factory methods. I also didn't include data on the logout function, but I am sure you can add the route yourselves and call the service function. If there is any other questions or issues, let me know!

Tuesday, May 14, 2013

Working with Bower and Grunt

Even after getting everything up and running with Yeoman, Bower and Grunt, I realized there were still issues, especially when it came to utilizing Twitter Bootstrap in my project.  The problem arose from the Angular Generator, specifically in the fact that there were no images or javascript files included, only the stylesheet.

Solution #1


Yeoman has a separate generator (bootstrap-generator) that you can download:
npm install -g bootstrap-generator
After installation, you can then navigate to your app directory and run:
yo bootstrap:app
This will create a folder in your components directory with all your bootstrap needs.  You can then include the files as needed.

Problem #1

Bower also uses the components directory to add extra components.  Running the command:
bower list
or
bower update
causes errors to be thrown because that folder should only be used for Bower

Solution #2


Well, Yeoman works, but causes more errors than it is worth.  Bower was my next thought, and sure enough, you can get bootstrap installed with:
bower install bootstrap

Problem #2

Bower grabs the files from Twitter's GIT, and if you didn't already know, the files are all LESS, not CSS.  So if you are looking for vanilla CSS, this doesn't help.  Turns out however, that the files in the docs folder are the compiled version of Bootstrap, so that actually does work.  The only problem with that though is that Bower's simplistic nature (
<script src= 'components/COMPONENT_NAME/COMPONENT_NAME.js' > ) doesn't apply.

Final Solution


After doing some digging, Bower also has a package called Bootstrap.css, which is vanilla Bootstrap and Javascript files.  It is straightforward and contains all the images and everything needed to get you app up and running.

Final Problem


Trying to build with Grunt is a pain.  Grunt will only package up Javascript files located directly in the scripts folder, and image files located directly in the images folder.  Grunt will also find all your CSS files, and then package all those together in one single CSS file.  This is great, but can be a problem because your Bootstrap CSS points to ../img/glyphicons-halflings.png which wasn't moved to the image or img folder from the components folder.

Final Fix


The final solution is to edit your Gruntfile.js and add in a few things in your grunt.initConfig object.  All I did was changed the imagemin object to look like this:

    imagemin: {
      dist: {
        files: [{
          expand: true,
          cwd: '<%= yeoman.app %>/img',
          src: '{,*/}*.{png,jpg,jpeg}',
          dest: '<%= yeoman.dist %>/img'
        },{
          expand: true,
          cwd: '<%= yeoman.app %>/components/bootstrap/img',
          src: '{,*/}*.{png,jpg,jpeg}',
          dest: '<%= yeoman.dist %>/img'
        }]
      }
    },
This solved all my issues and even put the images into the img folder instead of images for a cleaner transition and less editing of Bootstrap.


Saturday, May 11, 2013

Creating an Angular app with Yeoman, Bower, and Grunt on Windows

I will be brutally honest, as a Windows user I feel a little left out when it comes to terminal and the cool ability to install repositories by typing a few words.  I feel intimidated using SVN, GIT, Composer, PHP, Pecl, Pear, Phar, Node and any other program/script that seems to run with ease on Mac and Linux.  Over time things have become easier.  I have figured out the PATH file to let commands run a little easier in Windows Command Prompt.  I am not going to go over PATH and everything since I am assuming that is something you should probably already have figure out.  What I intend to go over is getting a basic Angular JS app up and running with tests and dependencies using Yeoman, Bower, and Grunt.

What is Yeoman, Bower, and Grunt


Yeoman (http://yeoman.io) is a scaffold manager/app generator.  The whole goal of apps is consistency.  Think of it as a template for your app with the index page created, script tags in place, css files loaded, an so on.  The whole point is just to make your life easier.  How often have you gone to a website, downloaded the *.zip file, created a directory, and then copied and pasted parts of the zip file into specific directories?  And for a single app, you probably do this a half a dozen times (angular, angular-resouces, jquery, jquery-ui, twitter bootstrap, angular-ui, etc).  Then you go to your index.html and go back and forth remembering to type the names correctly and put them in the right place.  Yeoman does this for you, so ultimately you save time and headaches.

Bower (http://bower.io) is a package/resource manager.  You want jQuery, you got jQuery.  You want angular-mocks, you got angular-mocks.  It seriously makes getting resources downloaded and put in the right directories super easy.  The upside to this is that any updates (lets say jQuery 2.1 comes out) can be done by running an update on Bower.  All the resources will be checked and the outdated ones will be updated to the latest version.  No more remembering weekly to visit all the resource sites.  Bower has around 2000 resources in their repository, so anything you can think of from HTML, to CSS, to Javascript, they got it.

Grunt (http://grunt.io) is the worker of the bunch.  With Grunt you can set up a mock server to see your app in action.  You can also run the Karma tests that you should be writing.  And finally you can compile, minify/uglify, and prep your code for production.  If you are writing tests, you now how hard it is to get the adapters to work in Windows the first time and then remembering the steps... this simplifies it completely.

Prerequisites


Node.  That's it.  Node is super easy to install, just visit http://nodejs.org and click the Install button.  On Windows you will get the *.msi file and in a few seconds the installer will be done.

**NOTE**
It has been a while since I installed Node, but if I am correct, using the MSI installer will also configure your PATH and allow you to use node and npm in Command Prompt.  For this tutorial you will need to use npm.

Installing the programs


First things first, install the three amigos, and then the generators Yeoman needs for the Angular scaffolding.
npm install -g yo bower grunt-cli
npm install -g generator-angular generator-karma
 That is it!

Creating your first Angular app


Using Command Prompt (because that is what we are doing), navigate to a directory to create your app.  Really anywhere is fine:

cd c:\
mkdir angular-apps
cd angular-apps
mkdir first-app
cd first-app

Inside the first-app directory, we now run Yeoman (yo) and create our scaffolding:

yo angular

Wait for a minute and then you will be presented with the following options:

Would you like to include Twitter Bootstrap? (Y/n) y
If so, would you like to use Twitter Bootstrap for Compass (as opposed to vanill
a CSS)? (Y/n) n
Would you like to include angular-resource.js? (Y/n) y
Would you like to include angular-cookies.js? (Y/n) y
Would you like to include angular-sanitize.js? (Y/n) y

After which it will download and organize your app entirely.

Now on to bower.  We need to actually install the components the make this app run and tests to work:

bower install angular
bower install angular-resource
bower install angular-cookies
bower install angular-sanitize
bower install angular-mocks

If you wanted jQuery or some other plugins, you can install those as well.  All these components are installed in the app/components folder and are very easy to tag:

<script type='text/javascript' src='components/angular/angular.js'></script>
<script type='text/javascript' src='components/angular-resource/angular-resource.js'></script>
 <script type='text/javascript' src='components/%BowerPackage%/%BowerPackage%.js'></script>

Well the good news is, we don't have to write those in our index.html file as Yeoman already did all that for us, along with the app.js and controller.js files.  So that brings us to the final category, running and testing with Grunt.  There are 3 commands (grunt server, grunt test, and grunt) that will be used most often, but they may or may not work by default.  Because of Yeoman's scaffolding generation, the Gruntfile.js has Compass dependencies, which in turn has Ruby dependencies.  This can be a headache if you aren't planning on using Compass.

**NOTE** 
Compass is a styling/scripting language for generating CSS files.  If you have heard about LESS or SASS, it is similar and much more user friendly.  Compass, in fact, takes what you have coded and converts it to SASS, which in turn is converted to CSS.

If you don't have Ruby installed and you aren't planning on using Compass, then you will need to edit your Gruntfile.js.  The easiest thing to do is search for "Compass" and delete those objects/values.  There are 5 places where Compass objects appear.  First in the grunt.initConfig.watch object, then in the main object of grunt.initConfig.  Finally in the three grunt.registerTask functions, there are 3 instances of Compass that need to be removed.  If you are coding Angular you should be able to figure out how to remove those objects from the file, so I am not going to post the entire Gruntfile here.

Finally, you can run grunt server and Chrome will pop open with your first app.  You can close that and run grunt test and your initial Karma test will run (Chrome will open, run the tests and close.  The output is in the Command Prompt).  And then you can build your app using grunt when it comes time for production.

I hope this helps get things going for you.  It took me a while to figure out what all this was about and how to get the 3 amigos to play nicely with each other on Windows.  If you have any questions, feel free to let me know.