Sunday, 30 April 2017

Add authentication token in every http request call in angular js applications

In this post we are going to see how to pass the authentication token in every http request call in angular js application

authService:
*************
 mvcapp.service('authService', ['$localStorage', '$rootScope',function ($localStorage,$rootScope) {

    this.getAuthCode = function () {
        return $localStorage.authuser;
    }

    this.setAuthCode = function (authdata) {
        $localStorage.authuser = authdata;
    }

    this.removeAuthCode = function () {
        delete $localStorage.authuser;       
        var loggeduser = { Status: '', Username: '', Authcode: '' };
        $rootScope.$broadcast('loguser', loggeduser);
    }

    this.isLoggedIn = function () {
        return $localStorage.authuser != null && $localStorage.authuser.Authcode != null;
    }


}]);




Factory:
*********
mvcapp.factory('httpRequest', ['$q', 'authService', function ($q, authService) {

    var _interceptors = {
        request: function (config) {
            if (angular.isObject(config)) {
                config.delay = new Date().getTime();
                var loggedin = authService.getAuthCode();

                if (loggedin!=undefined && loggedin.Authcode != null)
                    config.headers["Authorization"] = "Bearer " + loggedin.Authcode;

            }
            return config;
        },
        response: function (response) {
            if (angular.isObject(response.config)) {
                response.config.delay = new Date().getTime() - response.config.delay;
            }
            return response;
        },
        requestError: function (config) {
            if (angular.isObject(config)) {
                config.delay = new Date().getTime();
            }
            return $q.reject(config);
        },
        responseError: function (response) {
            if (angular.isObject(response.config)) {
                response.config.delay = new Date().getTime() - response.config.delay;
            }
            return $q.reject(response);
        }
    };

    return _interceptors;

}]);



mvcapp.config(['$httpProvider', function ($httpProvider) {
    $httpProvider.interceptors.push('httpRequest');
}]);



From this post you can learn how to pass the authentication token in every http request call.

How to write a login authentication using stateprovider and authentication for each state in angular js application

In this post we are going to see how to create the login authentication in angular js application in state provider.

First we have to create the states, Then we have to create the variable name authenticate to the states which ever need the authentication

We are creating a hook for $stateChangeStart event , so when ever we change state this will hooked, from there we are checking whether authenticate is required for this state, if it is required then we are invoking the authService for checking the authentication, if failed then we change the state or transition the state to login state.

var mvcapp = angular.module('mvcapp', ['ui.router', 'ngCookies', 'ngStorage',]);


configure states:

******************

mvcapp.config(['$stateProvider', '$urlRouterProvider', '$localStorageProvider',            
               '$locationProvider',
function ($stateProvider, $urlRouterProvider, $localStorageProvider, $locationProvider) {


    $stateProvider.state('home',
        {
            name: 'home',
            url: '/home',
            templateUrl: 'app/templates/home.html',
            controller: 'homeController'
        })
        .state('about',
        {
            name: 'about',
            url: '/about',
            templateUrl: 'app/templates/about.html',
            controller: 'aboutController'
        })
        .state('login',
        {
            name: 'login',
            url: '/login',
            templateUrl: 'app/templates/login.html',
            controller: 'loginController',
            resolve: { signIn: AlreadySignin }
        })
        .state('register',
        {
            name: 'register',
            url: '/register',
            templateUrl: 'app/templates/register.html',
            controller: 'registerController',
            resolve: { signIn: AlreadySignin }
        })
        .state('profile',
        {
            name: 'profile',
            url: '/profile',
            templateUrl: 'app/templates/profile.html',
            controller: 'profileController',
            authenticate: true
        })
        .state('history',
        {
            name: 'history',
            url: '/history',
            templateUrl: 'app/templates/history.html',
            controller: 'historyController',
            authenticate: true
        })       
        .state("default",
        {
            name: 'default',
            url: '/',
            templateUrl: 'app/templates/home.html',
            controller: 'homeController'
        });
        
    $urlRouterProvider.otherwise('/'); 
    $localStorageProvider.setKeyPrefix('mvcapp');
    $locationProvider.html5Mode(false);

}]);



handling exception in global:

********************************
mvcapp.config(['$provide',function ($provide) {
    $provide.decorator('$exceptionHandler', ['$delegate', '$log'
     function ($delegate, $log) {
        return function (exception, cause) {
            $delegate(exception, cause);
            $log.info(exception.message + " (because of " + cause + " )");
        };
    }])
}]);



check for login, if logged in redirect to home:
***************************************************
AlreadySignin.$inject = ['$rootScope','$state', '$location', 'authService'];

function AlreadySignin($rootScope, $state,$location, authService) {
    if (authService.isLoggedIn()) {      
        return $location.path("/home");      
    }

}



Then we have to write logic in statechangestart event in run based on authenticate variable, now we will see what is the authservice, and what logic it resides


mvcapp.run(['$rootScope', '$location', '$http', 'authService', '$state', '$timeout',
  function ($rootScope, $location, $http, authService, $state, $timeout) {

    if (authService.isLoggedIn())
    {
        $http.defaults.headers.common['Authorization'] = 'Bearer ' +
authService.getAuthCode().Authcode;
    }


    function safeApply(scope, fn) {
        (scope.$$phase || scope.$root.$$phase) ? fn() : scope.$apply(fn);
    }


    $rootScope.$on('$stateChangeStart', function (event, toState, toParams,
fromState, fromParams) {

        if (toState.authenticate && !authService.isLoggedIn()) {
            // User isn’t authenticated
            $state.transitionTo("login");           
            $rootScope.redirect = toState.name;
            event.preventDefault();
        }

        if (toState.authenticate && authService.isLoggedIn()) {
            var role = authService.getAuthCode().Role;
           
        }

        safeApply($rootScope, function () {
            $timeout(function () {
                $rootScope.$broadcast('updatelogin');
            })          
        });

       

    });


}]);





authService:
*************


mvcapp.service('authService', ['$localStorage', '$rootScope',

function ($localStorage,$rootScope) {

    this.getAuthCode = function () {
        return $localStorage.authuser;
    }

    this.setAuthCode = function (authdata) {
        $localStorage.authuser = authdata;
    }

    this.removeAuthCode = function () {
        delete $localStorage.authuser;       
        var loggeduser = { Status: '', Username: '', Authcode: '' };
        $rootScope.$broadcast('loguser', loggeduser);
    }

    this.isLoggedIn = function () {
        return $localStorage.authuser != null && $localStorage.authuser.Authcode != null;
    }



}]);


Output:
*************





















From this post you can learn how to add the authentication for each state in the angular js applications


Saturday, 29 April 2017

Installing GitHub for Windows failed - Resolved

Installing github for windows sometimes failed, in this post we are going to see how to resolve this issue and make a successful installation, This installation may fail after 80% or 95%, now we see what kind of error it is.

Application installation did not succeed.  Cannot locate application files on the server.  Contact the application vendor or your administrator for assistance.

Clicking on Details...

PLATFORM VERSION INFO
    Windows             : 6.1.7601.65536 (Win32NT)
    Common Language Runtime     : 4.0.30319.18034
    System.Deployment.dll       : 4.0.30319.17929 built by: FX45RTMREL
    clr.dll             : 4.0.30319.18034 built by: FX45RTMGDR
    dfdll.dll           : 4.0.30319.17929 built by: FX45RTMREL
    dfshim.dll          : 4.0.41209.0 (Main.041209-0000)

SOURCES
    Deployment url          : http://github-windows.s3.amazonaws.com/GitHub.application
    Server                         : AmazonS3
    Application url           : http://github-windows.s3.amazonaws.com/Application%20Files/GitHub_1_0_47_0/GitHub.exe.manifest
     Server                        : AmazonS3

IDENTITIES
    Deployment Identity     : GitHub.application, Version=1.0.47.0, Culture=neutral, PublicKeyToken=317444273a93ac29,
    processorArchitecture = x86
    Application Identity        : GitHub.exe, Version=1.0.47.0, Culture=neutral, PublicKeyToken=317444273a93ac29,
    processorArchitecture = x86, type=win32


Now we see how to resolve this issue,
Download the github from the following url in Internet Explorer, Internet explorer only give a success installation

https://github-windows.s3.amazonaws.com/GitHub.application


From this post you can install the github for windows

create a component in angular 1.5 using Typescript

In this post we are going to see how to create the component in angular 1.5 using Typescript. first we have to understand what is component, component is a isolated directive with some functionalities, most of functionalities are look like same for directive and components, few things will change, we will see the how to write the components using Typescript

First we have to create the interface for bindings parameters, then implement that in a controller , later assign this controller to component, in component we have bindings parameters there also we have to specify the parameters.


export interface  StarBindings {
        ratingValue: any;
        max: number;
        readonly: boolean;
        starSize: number;
        onRatingChanged: (value: any) => any; }


In component

this.bindings = {
                ratingValue: '=',
                max: '=',
                readonly: '@',
                starSize: '=',
                onRatingChanged: '&'
            };



Then write logic inside the controller, later access everything using the $ctrl, which is automatically created alias by component.

module app.components {

    export interface  StarBindings {
        ratingValue: any;
        max: number;
        readonly: boolean;
        starSize: number;
        onRatingChanged: (value: any) => any;
    }

    class  StarController implements  StarBindings {

        public ratingValue: any;
        public max: number;
        public readonly: boolean;
        public starSize: number;
        public onRatingChanged: (value: any) => any;
        public stars: any =[];

        static  $inject = ['$log','$element','$scope'];

        constructor(private $log: ng.ILogService, private $element: ng.IAugmentedJQuery, 
                    private $scope: ng.IScope){

        }

        $postLink = (): void => {
            this.$log.info('post link invoked');
            this.drawStar();
        };

        drawStar = (): void => {
            this.$element.css('font-size',this.starSize+'px');
            this.$scope.ratingValue = 0;
            let t = this;
            this.$scope.$watch('ratingValue', function (oldval, newval) {
                if (newval) {
                    t.updateStars();
                }
            });

            this.$scope.ratingValue = this.ratingValue;

        };



        toggle =  (index: number) => {
            if (this.readonly && this.readonly === true) {
                return;
            }
            this.ratingValue = index + 1;
            this.$scope.ratingValue = this.ratingValue;
            this.onRatingChanged({ rating: index + 1 });

        };




        updateStars = (): void => {
            this.stars = [];
            for (let i:number = 0; i < this.max; i++) {
                this.stars.push({ filled: i < this.ratingValue });
            }
        }
    }

    class StarComponent {

        public bindings: any;
        public controller: any;
        public template: string;

        constructor(){
            this.template = '<ul class="rating">' +
                                '<li ng-repeat="star in $ctrl.stars" ng-class="star"'+
                                   ' ng-click="$ctrl.toggle($index)">' +
                                '\u2605' +
                                '</li>' +
                            '</ul>';
            this.controller = StarController;
            this.bindings = {
                ratingValue: '=',
                max: '=',
                readonly: '@',
                starSize: '=',
                onRatingChanged: '&'
            };
        }

    }

    angular.module('myapp').component('star',new StarComponent());
}

Here you can see that i am using the $postLink method to render the star , $postLink is a predefined method called by component, Assign the template, bindings, controller inside the component, star rendering logic are present inside the controller, i am using the $watch  here to render the star in the when user click.

app.controller.ts


/// <reference path="../node_modules/@types/angular/index.d.ts" />


module mymod{
    class MyController{

        private name: string;
        private sample: string;
        private title: string;
        private rating2: number;

        static $inject = ['$log']

        constructor(private $log: angular.ILogService){
            this.title = "Angular with Typescript";
            this.name = 'rajesh1';
            this.sample = 'raise';
            this.rating2 = 4;
        }

        save = (rating: any): void => {
            console.log('rating changed');
            console.log(rating);
        };


        dosomething = (): void => {
            window.setTimeout(3, () => { this.$log.warn('do something'); });
            
        }

    }
    var myApp= angular.module('myapp',[]);
    myApp.controller('mycontroller',MyController);
}



Html


<!DOCTYPE html>
<html lang="en" ng-app="myapp">
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body ng-controller="mycontroller as vm">
      
        <h2 style="margin:20px">{{vm.title}}</h2>
        <br/>

        <star rating-value="vm.rating2" max="10" star-size="45"
              on-rating-changed="vm.save(rating)"></star>

        <link href="styles.css" rel="stylesheet" />
        <script src="bower_components/angular/angular.min.js"></script>
        <script src="app/app.js"></script>
        <script src="app/star.component.js"></script>

    </body>
</html>


CSS:


.rating {
    color: #a9a9a9;
    margin: 0;
    padding: 0;
}

ul.rating {
    display: inline-block;
}

.rating li {
    list-style-type: none;
    display: inline-block;
    padding: 1px;
    text-align: center;
    font-weight: bold;
    cursor: pointer;
}

.rating .filled {
    color: red;
}


Output:



From this post you can learn how to create components in angular 1.5 using Typescript