How to prevent having to login every time without logging out in Ionic app?

How can I make my app for Ionic to prevent having to log in every time after exiting the app, or back to the background without logging out? Its source code:

login.js

   angular.module('starter.controllers')

   .controller('LoginCtrl', ['$scope', '$rootScope', '$location', '$localStorage', '$q', '$http', '$window', '$state', 'AuthFac tory', 'SessionFactory',
       function($scope, $rootScope, $location, $localStorage, $q, $http, $window, $cordovaSQLite, $state, AuthFactory, SessionFactory) {

           $scope.login = {
               email: null,
               password: null
           };

           $scope.login = function() {
               $rootScope.showLoading("Authenticating..");

               var email = $scope.login.email,
                   password = $scope.login.password;

               if (email !== undefined && password !== undefined) {
                   AuthFactory.login(email, password).success(function(data, status, headers, config) {
                       if (data.success === false) {
                           $rootScope.hideLoading();
                           $rootScope.toast('Invalid Credentials');
                       } else {
                           SessionFactory.isLogged = true;
                           SessionFactory.user = data.data.username;
                           SessionFactory.userRole = data.data.name;
                           $localStorage.id = data.data.id;
                           $localStorage.token = data.data.token;
                           $window.sessionStorage.token = data.data.token;
                           console.log($window.sessionStorage.token);
                           $localStorage.user = data.data.username; // to fetch the user details on refresh
                           console.log($localStorage.user);
                           $localStorage.userRole = data.data.name; // to fetch the user details on refresh
                           console.log($localStorage.userRole);
                       } //end else data.success
                   }).error(function(data, status, headers, config) {
                       if (status === 500) {
                           $rootScope.hideLoading();
                           $rootScope.toast('Invalid Email');
                       }
                   });
               }
           };
       }
   ]);

      

authfactory.js

angular.module('starter.factories')

.factory('SessionFactory', function($window, $localStorage) {
  var auth = {
    isLogged: false,
    check: function() {
      if ($localStorage.token && $localStorage.user ) {
        this.isLogged = true;
      } else {
        this.isLogged = false;
        delete this.user;
      }
    }
  }


  return auth;
})


    .factory('AuthFactory', function($window, $location, $http, SessionFactory, $localStorage) {
      return {
        login: function(email, password) {
          return $http.post('url', {
            email : email,
            password: password
          });

        },

        logout: function() {

          if (SessionFactory.isLogged) {

            SessionFactory.isLogged = false;
            delete SessionFactory.user;
            delete SessionFactory.userRole;

            delete $localStorage.token;
            delete $localStorage.user ;
            delete $window.sessionStorage.userRole;

            $location.path("/login");
          }

        }
      }
    })


    .factory('TokenInterceptor', function($q, $window, $localStorage) {
      return {
        request: function(config) {
          config.headers = config.headers || {};
          if ($localStorage.token) {
            config.headers['X-Access-Token'] = $localStorage.token;
            config.headers['X-Key'] = $localStorage.user;
            config.headers['Content-Type'] = "application/json";
          }
          return config || $q.when(config);
        },

        response: function(response) {
          return response || $q.when(response);
        }
      };
    })

      

app.js

angular.module('starter.controllers', []);
angular.module('starter.services', []);
angular.module('starter.factories', []);

angular.module('starter', ['ionic', 'starter.controllers', 'starter.services', 'starter.factories', 'ngCordova', 'ngRoute'])

.run(function($ionicPlatform, $rootScope, $ionicLoading, $state, $location, $q, $http, $timeout, $localStorage, $window, SessionFactory) {
  $ionicPlatform.ready(function() {

    // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
    // for form inputs)
    if (window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard) {
      cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
    }
    if (window.StatusBar) {
      // org.apache.cordova.statusbar required
      StatusBar.styleLightContent();
    }

    $ionicPlatform.registerBackButtonAction(function(event) {
      if ($state.current.name == "tab.dashboard") {
        navigator.app.exitApp();
        console.log('1');
      } else {
        navigator.app.backHistory();
        console.log('2');
      }
    }, 100);

    if (window.cordova) {


    });

    // when the page refreshes, check if the user is already logged in
    SessionFactory.check(); $rootScope.showLoading = function(msg) {
      $ionicLoading.show({
        template: msg || 'Loading',
        animation: 'fade-in',
        showBackdrop: true,
        maxWidth: 200,
        showDelay: 0
      });
      $timeout(function() {
        $rootScope.hideLoading();
      }, 2999);
    }

    $rootScope.hideLoading = function() {
      $ionicLoading.hide();
    };

    $rootScope.toast = function(msg) {
      $rootScope.showLoading(msg);
      $timeout(function() {
        $rootScope.hideLoading();
      }, 2999);
    };

    $ionicPlatform.on('resume', function() {
      $rootScope.$on("$routeChangeStart", function(event, nextRoute, currentRoute) {
        if ((nextRoute.access && nextRoute.access.requiredLogin) && !SessionFactory.isLogged) {
          $location.path("/login");
        } else {
          // check if user object exists else fetch it. This is incase of a page refresh
          if (!SessionFactory.user) SessionFactory.user = $localStorage.user;
          if (!SessionFactory.userRole) SessionFactory.userRole = $localStorage.userRole;
        }
        console.log('true');
      });

      $rootScope.$on('$routeChangeSuccess', function(event, nextRoute, currentRoute) {
        $rootScope.showMenu = SessionFactory.isLogged;
        $rootScope.role = SessionFactory.userRole;
        // if the user is already logged in, take him to the home page
        if (SessionFactory.isLogged == true && $location.path() == '/login') {
          $location.path('/tab/price');
        }
      });
      console.log(SessionFactory.isLogged);
      $rootScope.$broadcast('onResume');
    });

    $ionicPlatform.on('pause', function() {
      $rootScope.$broadcast('onPause');
      console.log('pause');
    });


  })

  .config(function($stateProvider, $urlRouterProvider, $httpProvider, $ionicConfigProvider) {

    $httpProvider.interceptors.push('TokenInterceptor');
    // Ionic uses AngularUI Router which uses the concept of states
    // Learn more here: https://github.com/angular-ui/ui-router
    // Set up the various states which the app can be in.
    // Each state controller can be found in controllers.js
    $stateProvider

    // setup an abstract state for the tabs directive
    .state('login', {
      url: '/login',
      templateUrl: 'templates/login.html',
      controller: 'LoginCtrl',
      access: {
        requiredLogin: false
      }
    })


    // if none of the above states are matched, use this as the fallback
    $urlRouterProvider.otherwise('/login');

  });

      

login.html

<ion-view view-title="Ionic App">
  <ion-content> 
    <ion-list>
      <form name="loginForm">
        <div class="list">

            <label class="item item-input">
                <input type="email" placeholder="Email" ng-model="login.email"  required>
            </label>
            <label class="item item-input">
                 <input type="password" placeholder="Password" ng-model="login.password"  required>
            </label>
              <button class="button button-block button-assertive" ng-click="login()" ng-disabled="loginForm.$invalid">
           <b>Login</b>
           </button>
        </div>
      </form>
    </ion-list>
  </ion-content>
</ion-view>         

      

I hope someone can help me solve this problem.

+3


source to share


3 answers


Simple and Recommended Solution: Store user credentials in local storage and auto-login. As I see your code, you are already storing some user data in localStorage. You can check if these details exist in localStorage when your controller is loaded and your login method is called directly.

Something like that:

function($scope, $rootScope, $location, $localStorage, $q, $http, $window, $cordovaSQLite, $state, AuthFactory, SessionFactory) {
   $scope.login = {
       email: null,
       password: null
   };

   $scope.isLoggedIn = false;

   $scope.login = function() {

        // on login set a flag to mark the user as logged in

   };


   if (!$scope.isLoggedIn) {   
        if ($localStorage.userName  !== undefined and $localStorage.password !== undefined) {
            $scope.login();
        }
   }

]);

      



Alternatively, if you are working on some authentication with a login token, you can also save that token and use it to communicate with the server next time.

Remember to use encryption though (y)

+2


source


1). In $ urlRouterProvider.otherwise ('') set the url of the app toolbar or home page where the user is sent after logging in. Let's assume $ urlRouterProvider.otherwise ('/ dashboard').



2). In the dashboard controller, enter the service that authenticates the user and sends the user to login if not authenticated.

0


source


This is possible with local storage in ionic

  • Set some credentials in local storage on first login window.localStorage.setItem("username", "rahul"); window.localStorage.setItem("password", "123");

  • Check your local credentials store when you open the app next time in the .run () method.

        var localval = window.localStorage.getItem('username');
        var localval1 = window.localStorage.getItem('password');
        console.log(localval);
        if(localval != null && localval1 != null)
        {
          $state.go('app.home');
        }
    
          

  • Clear local app storage when exiting an app window.localStorage.removeItem("username", "rahul"); window.localStorage.removeItem("password", "123");

0


source







All Articles