Active Session in ionic Framework (Sqlite)

0

I am using sqlite database in my app to save the session status and information of a user. What I am doing has worked for me but I have a problem: When validating if the status of the session is active, I will show the corresponding html view to the user all right there, but when I close my app and run it again FIRST, THE LOGIN VIEW IS SHOWN and after 1 or 2 The USER'S VIEW is displayed.

What I am trying to do is that when you run the application, the user's view is shown directly. In case what I want is that the login view is not shown unless the session status is not active

This is my code: App.js (This whole process I do here)

var db = null;//paso 1 BD
angular.module('starter', ['ionic', 'ngCordova', 'starter.controllers'])

.run(function($ionicPlatform, $cordovaSQLite,$state) {//paso 2 agrego cordovaSqlite
  $ionicPlatform.ready(function() {
    if(window.cordova && window.cordova.plugins.Keyboard) {
      // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
      // for form inputs)
      cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);

      // Don't remove this line unless you know what you are doing. It stops the viewport
      // from snapping when text inputs are focused. Ionic handles this internally for
      // a much nicer keyboard experience.
      cordova.plugins.Keyboard.disableScroll(true);
      //creo la tabla tutoria
      db = $cordovaSQLite.openDB({ name: 'tuto.db' });//paso 3 creo  la BD
      $cordovaSQLite.execute(db,"CREATE TABLE IF NOT EXISTS tutoria (id integer primary key, estado text, rolUs text, pNombre text, Inicial text, sNombre text, pApellido text, sApellido text, cedula text)");
      //fin creo la tabla tutoria
      //comprobar sesion
      var query = "SELECT * FROM tutoria";
      $cordovaSQLite.execute(db,query).then(function(result) {
        for ( j=0; j < result.rows.length; j++) { 
          if(result.rows.item(j).estado=="Sesion_Activa" && result.rows.item(j).rolUs=="docente"){
            $state.go('tabs.perfilDocente'); //aqui hago que se muestra la vista del docente
          }else{
            if(result.rows.item(j).estado=="Sesion_Activa" && result.rows.item(j).rolUs=="estudiante"){
              $state.go('tabsEst.perfilEstudiante'); // aca muestro la vista del estudiante dependiendo del rol
            }
          }               
        }
      });
      //fin comprobar sesion
    }
    if(window.StatusBar) {
      StatusBar.styleDefault();
    }
  });
})
//VISTAS
.config(function($stateProvider, $urlRouterProvider) {  
  $stateProvider
    //Login de la APP
    .state('login',{
      cache: false,
      url:'/login',
      templateUrl:'templates/login.html',
      controller: 'LoginCtrl'
    })
    // PADRE DE VISTAS TABS DOCENTE
    .state('tabs',{
      cache: false,
      url:'/Gtuto',
      abstract:true,
      templateUrl:'templates/tabs.html'
    })
    //Hijos de TABS
    .state('tabs.perfilDocente', {
      cache: false,
      url:'/perfil',
      views:{
        'perfil-tab':{
          templateUrl:'templates/perfilDocente.html',
          controller:'SalirCtrl'
        }
      }
    })
    .state('tabs.CompDocente', {
      cache: false,
      url:'/componentes',
      views:{
        'componentes-tab':{
          templateUrl:'templates/CompDocente.html',
          controller:'DocenteCtrl'
        }
      }
    })    
    .state('tabs.ListaTutoDocente', {
      cache: false,
      url:'/componentes/:nom_coe',
      views:{
        'componentes-tab':{
          templateUrl:'templates/ListaTutoDocente.html',
          controller:'DocenteCtrl'
        }
      }
    })
    .state('tabs.CrearTutoria', {
      cache: false,
      url:'/componentes/:nom_coe/:paralelo',
      views:{
        'componentes-tab':{
          templateUrl:'templates/CrearTutoria.html',
          controller:'DocenteCtrl'
        }
      }
    })
    .state('tabs.ContEdicionTuto', {
      cache: false,
      url:'/componentes/:Nom_coe/EdicionTutorias/:id',
      views:{
        'componentes-tab':{
          templateUrl:'templates/ContEdicionTuto.html',
          controller:'DocenteCtrl'
        }
      }
    })
    .state('tabs.comentarios', {
      cache: false,
      url:'/componentes/:componentesId/:c/:f/:d',
      views:{
        'componentes-tab':{
          templateUrl:'templates/comentarios.html',
          controller:'DocenteCtrl'
        }
      }
    })
    .state('tabs.participantes', {
      cache: false,
      url:'/componentes/:componentesId/:c/:f/:d/:e',
      views:{
        'componentes-tab':{
          templateUrl:'templates/participantes.html',
          controller:'DocenteCtrl'
        }
      }
    })
    .state('tabs.notDoc', {
      cache: false,
      url:'/notificaciones',
      views:{
        'notificaciones-tab':{
          templateUrl:'templates/NotDoc.html'
        }
      }
    })
    // PADRE DE VISTAS TABSEST ESTUDIANTE
    .state('tabsEst',{
      cache: false,
      url:'/Gtuto',
      abstract:true,
      templateUrl:'templates/tabsEst.html'
    })
    //Hijos de TABSEST
    .state('tabsEst.perfilEstudiante', {
      cache: false,
      url:'/perfilEst',
      views:{
        'perfil-tabsEst':{
          templateUrl:'templates/perfilEstudiante.html',
          controller:'SalirCtrl'
        }
      }
    })
    .state('tabsEst.CompEstudiante', {
      cache: false,
      url:'/componentesEst',
      views:{
        'componentes-tabsEst':{
          templateUrl:'templates/CompEstudiante.html',
          controller:'AlumnoCtrl'
        }
      }
    })    
    .state('tabsEst.ListaTutoEstudiante', {
      cache: false,
      url:'/componentesEst/:nombre',
      views:{
        'componentes-tabsEst':{
          templateUrl:'templates/ListaTutoEstudiante.html',
          controller:'AlumnoCtrl'
        }
      }
    })
    .state('tabsEst.notificaciones', {
      cache: false,
      url:'/notificacionesEst',
      views:{
        'notificaciones-tabsEst':{
          templateUrl:'templates/NotEst.html'
        }
      }
    })
  $urlRouterProvider.otherwise('/login');
})
//FIN VISTAS
    
asked by Dimoreno 12.04.2016 в 00:12
source

2 answers

0

The reason why this is happening to you is simple.

  • You have 15 routes but none is linked to the url '/'
  • You have a setting that says $urlRouterProvider.otherwise('/login');

This means that your application will always use the status login as its initial screen since the default url is '/' and then it will navigate to '/login' following the configuration you set it . To avoid seeing the login screen you have three options

  • Use a splash-screen and hide it after you have verified whether the session is active or not.

    $cordovaSQLite.execute(db,query).then(function(result) {
        // verifico que estoy logueado y navego a la vista correspondiente
        $cordovaSplashscreen.hide(); 
    });
    

    This option will only work on a mobile and not when you are testing your application on the browser

  • Use an empty view linked to the url '/' and in a controller tests if the session is active, from there you do the redirection

    route definition

     $stateProvider
         .state('start',{
             url:'/',
             controller: 'StartCtrl'
          })
    

    controller

    angular.module('app')
        .controller('StartCtrl', function() {
            $cordovaSQLite.execute(db,query).then(function(result) {
               // determina si tienes una sesión activa
               if (session) {
                   $state.go('usuario');
               } else {
                   $state.go('login')
               }
            });
        });
    

    With this option you have an extra controller in your app whose only function is to verify that you are logged in.

  • Use the event $stateChangeStart make event.preventDefault() and redirect in view of the user in case you are logged in

     $rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams, options) {
         if (toState === 'login' && session) {
             event.preventDefault();
             $state.go('usuario');
         }
     });
    

    The event handler is synchronous and you are using promises to get your data $cordovaSQLite.execute(db,query).then(...) so this variant may not work for you .

  • answered by 12.04.2016 / 16:33
    source
    0

    You can observe the routes and credentials and redirect to login if it is not authenticated

    In your config you can change

    $urlRouterProvider.otherwise('/login');
    

    for

    $urlRouterProvider.otherwise('/usuario');
    

    and in run add an observer

        $rootScope.$on('$locationChangeStart', function(event, next, current) {
        var restrictedPage = $.inArray($location.path(), ['/login', '/register']) === -1;
        var loggedIn = $rootScope.globals.currentUser;// aqui tu usuario logeado desde sqlLite
    //si loggedIn es null o undefinid se enviara a la pagina login
        if (restrictedPage && !loggedIn) {
            $location.path('/login');
        }
        });
    

    This way, if it is not logged in, it will always be sent to login.

        
    answered by 14.04.2016 в 04:06