0

I have created a factory service in angularjs, which has an authentication service in it. If the authentication succeeded then it generates a token which is required for the dashboard services. I am able to generate the token but not understand how to use it.

Is it a good idea to create a factory service to get a token so I should inject in controllers as needed?

login.html:

<div ng-app="loginFormApp" ng-controller="loginFormCtrl">
    <form method="post" action="" id="login_form" class="row">
        <input type="text" placeholder="Login ID" ng-model="loginId" >
        <input type="password" placeholder="Password" ng-model="password" >
        <input type="button" class="btn btn-theme" ng-click="loginCall()" value="Login">
        <input type="button" class="btn btn-theme" ng-click="loginCall()" value="Register Here">
    </form>
</div>

My controller and factory service (authService.js):

var app = angular.module('loginFormApp', []);
 app.controller('loginFormCtrl', function ($scope, AuthService) {
     $scope.loginCall = function () {
         var token= AuthService.authentication($scope.loginId, $scope.password);
         alert(token);

     };
 });

 app.factory('AuthService', function ($http) {
     return {
         authentication: function (UserName, Password) {
             $http.post("http://103.19.89.152:8080/ccp-services/authenticate", {
                     'userName': UserName,
                     'password': Password
                 })
                 .then(function (response) {
                         window.location.href = "http://192.168.1.144:2000/angular/dashboard.html";
                         var getToken = response.data.httpHeaders.h5cAuthToken;
                      //   alert(token);
                 
                     },
                     // Error Handling
                     function (response) {
                         console.log(response.datas);
                     });
         }
         
     }
 });
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
ashish kumar
  • 67
  • 2
  • 14
  • You could store the token in the sessionStorage. You can find more info [here](https://auth0.com/blog/2014/01/07/angularjs-authentication-with-cookies-vs-token/) – Matheno Jun 17 '16 at 11:37
  • Just be aware if you have multiple areas of the system that need the token and they all hit this service each one will make its own request to the server which is far from ideal. You should just make one request and cache that response in some form so all others will get the cached version. Possible a separate promise or events to broadcast the token being received. How are you using the token? If its in the headers you could implement interceptors and never have to deal with it your controllers etc. (that all is once you've followed the answers to return the promise out your service.) – ste2425 Jun 17 '16 at 11:52

3 Answers3

2

This code does not work, because $http.post returns a promise.

var token = AuthService.authentication($scope.loginId, $scope.password);

First of all, you should return the $http.post method, as shown below.

return $http.post( // rest of code

In the then method after the $http.post, you should return the token.

.then(function (response) {
    window.location.href = "http://192.168.1.144:2000/angular/dashboard.html";
    return response.data.httpHeaders.h5cAuthToken; //return token
},

And the login call in your controller should be

AuthService.authentication($scope.loginId, $scope.password).then(function(token) {
    alert(token);
});

Update 1: reusing the access token

Ofcourse you want to be able to reuse the access token in API calls after the authentication call. This can be done by doing the following. Instead of returning the access token to the calling method, you can 'cache' the token inside the service itself.

app.factory('AuthService', function ($http) {
    var cachedToken; // this is where the token will be saved after authentication
    return {
        authentication: function (UserName, Password) {
            $http.post("http://103.19.89.152:8080/ccp-services/authenticate", {
                'userName': UserName,
                'password': Password
            })
            .then(function (response) {
                window.location.href = "http://192.168.1.144:2000/angular/dashboard.html";
                cachedToken = response.data.httpHeaders.h5cAuthToken; // save token to 'cache'
                return cachedToken
            },
            function (response) { // Error Handling
                console.log(response.datas);
            });
        },
        getToken: function() { // new method to retrieve the cached token
            return cachedToken;
        }
    }
});

In your dashboard controller, you can retrieve the token with:

AuthService.getToken();

Ofcourse, you need additional code to check if a token is actually retrieved (otherwise you will get undefined).

Vadiem Janssens
  • 4,069
  • 1
  • 17
  • 27
  • Thanks Vadiem Janssens by this way i get the token in the loginFormCtrl controller but how i can achieve the token by using the AuthService service in any other controller like dashboardController. – ashish kumar Jun 17 '16 at 12:57
0

$http.post invokes asynchronously, so you have to use callback to get token variable, authentication function will not return it.

Constantine
  • 482
  • 3
  • 10
0

Use the below factory. I added a return in $http call.

app.factory('AuthService', function ($http) {
 return {
     authentication: function (UserName, Password) {
       return  $http.post("http://103.19.89.152:8080/ccp-services/authenticate", {
                 'userName': UserName,
                 'password': Password
             })
             .then(function (response) {
                     window.location.href = "http://192.168.1.144:2000/angular/dashboard.html";
                     var getToken = response.data.httpHeaders.h5cAuthToken;
                  //   alert(token);

                 },
                 // Error Handling
                 function (response) {
                     console.log(response.datas);
                 });
     }

 }

});

Anandhan Suruli
  • 365
  • 3
  • 13