Search code examples
appcelerator-mobile

Appcelerator. Handling user sessions


Titanium SDK version: 1.6.1 iPhone SDK version: 4.2

I am a bit confused about what is the best practice when dealing with user "sessions" in Appcelerator apps (iPhone). Like it is now I save the users token in a property and then check on each page that it still exists (like on a webpage). This does not work so good and there must be a better way.

So, what is the best practise for handling user login sessions? Can someone explain the process for me? Step by step.

Thankful for all input!


Solution

  • I've been handling authentication verification on iOS as follows:

    1. In my app.js on first load I check that the token is valid, if not I display a login.

      I use methods similar to the below

        function need2Login(){
          var lastLogin = Ti.App.Properties.getString('last_login');
          if(lastLogin.length==0){
              return true; 
          }
    
          //add some date validation to expire any tokens
    
          // return a value based on the validation rules
        };
    
    function manageLogin(){
        if(need2Login()){
           wLogin.open(); //Open Login window
        }else{
                 wMain.open(); //Open Main window
        }   
    };
    
    1. When the user logs out, I fire an event back to the app.js to reload the login screen
    2. I also have the below in my app.js to handle on App Resume I also check if the token is still valid

    For the resuming handling I use the following in my app.sj:

    1) Check if we're on iOS 4+

    function isiOS4Plus(){
        // add iphone specific tests
        if (Ti.Platform.name == 'iPhone OS'){
            var version = Ti.Platform.version.split(".");
            var major = parseInt(version[0],10);
    
        // can only test this support on a 3.2+ device
        if (major >= 4){
            return true;
        }
       }
       return false;
    };
    

    2) Then add the handler

    if (isiOS4Plus()){
        // fired when an app resumes for suspension
        Ti.App.addEventListener('resumed',function(e){
           //check if login is still valid
           manageLogin(); //I just reuse my login logic on resume
        });
    }
    

    Please note this assumes checking the authentication token only needs to be done when the App starts, or resumes. This should cover most cases, but there are aways ones were it wont fit.