Sunday, 3 April 2016

JWT angular

.factory('authService', ['$http', '$q', 'localStorageService', 'ngAuthSettings', '$window', function ($http, $q, localStorageService, ngAuthSettings, $window) {
    return {
        serviceBase: ngAuthSettings.apiServiceBaseUri,
        authentication: {
            isAuth: false,
            userId: ""
        },
        logOut: function () {
            localStorageService.remove('Token');
            this.authentication.isAuth = false;
            this.authentication.userId = "";
            //localStorageService.set('Token', this.authentication);
        },
        gettoken: function () {
           this.logOut();
            var deferred = $q.defer();
            var data = 'client_id=6241438034&client_secret=1929220595&grant_type=client_credentials';
            localStorageService.remove('Token');
            $http.post(this.serviceBase + 'oauth/token', data, { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }).success(function (response, status) {
                localStorageService.set('Token', { access_token: response.access_token });
                deferred.resolve({ data: response, status: status });
            }).error(function (err, status) {
                this.logOut();
                $window.location.reload();
                deferred.reject(err);
            });
            return deferred.promise;
        },
        UpdateToken: function (data) {
            localStorageService.set('Token', data);
        },
        GetCurrentToken: function () {
            return !localStorageService.get('Token') ? {} : localStorageService.get('Token');
        },
        fillAuthData: function () {
            var authData = localStorageService.get('Token');
            if (authData) {
                this.authentication.isAuth = true;
                this.authentication.userId = authData.UserId;
            }
        }
    }
}])
.factory('authInterceptorService', ['$q', '$injector', '$location', 'localStorageService', '$window', '$rootScope', function ($q, $injector, $location, localStorageService, $window, $rootScope) {
    return {
        request: function (config) {
            config.headers = config.headers || {};
            var authData = localStorageService.get('Token');
            if (authData) {
                config.headers.Authorization = 'Bearer ' + authData.access_token;
            }
            return config;
        },
        responseError: function (rejection) {
            if (rejection.status === 401) {
                var authService = $injector.get('authService');
                authService.logOut();
                //$location.path('#/sigin');

            }
            if (rejection.status === 0) {
                alert("Please check your Internet connection.");
            }
            return $q.reject(rejection);
        }
    }
}])



  .controller('SigninCntrl', ["$scope", "$window", "CoreService", 'localStorageService', 'authService', 'toaster', '$location', function ($scope, $window, CoreService, localStorageService, authService, toaster, $location) {
      //$scope.firstlogin = true;
      $scope.pop = function (state,title,body) {
          toaster.pop(state, title, body);
      };
      $scope.SignIn = function () {
          debugger;
          if ($scope.SignInData) {
              if ($scope.SignInData.Email && $scope.SignInData.Password) {
                  authService.gettoken().then(function (successs) {
                      if (successs.status == 200) {
                          CoreService.Login([$scope.SignInData.Email, $scope.SignInData.Password]).then(function (success) {
                              if (successs.status == 200) {
                                  angular.forEach(success.data.Attributes, function (obj, index) {
                                      if (obj.Key == 'iotap_isfirsttime') {
                                          if (obj.Value) {
                                              $location.path('/change');
                                              $window.location.reload();
                                          } else {
                                              //window.location.reload(true);
                                              $location.path('/dashboard');
                                              $window.location.reload();
                                          }
                                      }
                                  })
                              } else {
                                  $scope.pop('error', "Unauthorized", "Please Check your UserId and password.");
                              }
                          }, function (err) {
                              $scope.firstlogin = false;
                              $scope.pop('error', "Unauthorized", "Please Check your UserId and password.");
                          })
                      }
                  })


              };
          }
        
      }
      $scope.ChangePassword = function () {
          console.log($scope.Data);
          if ($scope.Data.NewPassword == $scope.Data.NewConfirmPassword) {
              var data = authService.GetCurrentToken();
              CoreService.Change(data.UserId, [$scope.Data.Password, $scope.Data.NewPassword, $scope.Data.NewConfirmPassword]).then(function (success, status) {
                  console.log(status)
                  if (data.IsfirstTime) {
                      CoreService.UpdateEntity(localStorageService.get('uid').UserId, [false]).then(function (success, status) {
                          data.IsfirstTime = false;
                          authService.UpdateToken(data);
                          $location.path('/dashboard');
                      })
                  } else {
                      $location.path('/dashboard');
                  }
              }, function (error) {
                  alert(error.Message);
              })
          }
      }
  }])

No comments:

Post a Comment