REST API Persistent Login / stayLoggedIn example

Hi Folks - Backendless newbie - My app allows users to interact to the database as guest users using the rest API. According to the documentation, I can set user logins as persistent using the stayLoggedIn argument though I’m struggling to achieve this. Existing guest user sessions can be reconstructed next time the app relaunches but the there is no example of how this might be done. I would really appreciate some guidance here. My current guest user post call is below - I’m saving the returned user-token to window context for future rest calls in that session, but how do I validate an existing user for a new session? Currently I am refreshing the cache every time I reload the app - I feel like I’m missing something obvious. Thanks in advance!

Backbone.$.ajax({
type: "POST",
url:
  "https://api.backendless.com/APP_CREDS/services/User/login",
success: function(result) {
  console.log("result = ", result["user-token"]);
  window.usertoken = result["user-token"];
  initApp();
  // doGet();
},
error: function(result) {
  console.log("error = ", result);
}

});

Hi Dan,

the session is automatically restored if you use JS SDK with stayLoggedIn option when calling SDK’s method Backendless.UserService.login() (see docs https://backendless.com/docs/js/users_login.html).

As you’re using business logic for user authorization, you should take care of this behaviour yourself. When you recieve user-token, put it in LocalStorage (not window - the value will be lost after page refresh) and then after application restarts, check if user-token exists in LocalStorage and if exists, validate it using isValidLogin method (https://backendless.com/docs/js/users_login.html#validating-user-login) of JS SDK or using REST API if you don’t use JS SDK. The server returns a boolean value of true if token is valid, false otherwise.
And if token is valid, put it in ‘user-token’ header of each call you are making to server.
If token is not existing or is not valid, then user is not authorized.

Regards,
Stanislaw

Thanks for the direction Stanislaw. Thanks for pointing out that I was using business logic to handle gust login. This was a hangover from a previous attempt and I’ve now removed it and replaced it with the api call described in the docs.

My current setup now saves the user token to local storage ( as you directed ). On page load, I see if the token exists on local storage and valid it as you describe. This works well so thanks for the steer. If the user doesn’t exist or the token validation returns false, I then attempt to login as guest. This is working most of the time but I’ve noticed that sometimes if I clear cache AND local storage, the attempt to register as guest still errors with message "statusText: “TypeError: ns.GetCommandSrc is not a function” - again this doesn’t happen all the time, its fairly intermittent.

My code is below :

// Execute after the DOM has loaded
Backbone.$(function() {
  var retrievedObject = localStorage.getItem("userToken");
  if (retrievedObject) {
    validateUser(JSON.parse(retrievedObject));
  } else {
    registerGuestUser();
  }
});

function initApp() {
  // Create the router
  new AppRouter();

  // Start listening for route changes
  Backbone.history.start();
}

function validateUser(userToken) {
  Backbone.$.ajax({
    type: "GET",
    url:
      "https://api.backendless.com/" +
      APP_KEY +
      "/" +
      RESTAPI_KEY +
      "/users/isvalidusertoken/" +
      userToken,
    success: function(result) {
      console.log("user validated, initApp");
      initApp();
    },
    error: function(result) {
      console.log("user invalid, attempting register as guest");
      registerGuestUser();
    }
  });
}

function registerGuestUser() {
  Backbone.$.ajax({
    type: "POST",
    url:
      "https://api.backendless.com/" +
      APP_KEY +
      "/" +
      RESTAPI_KEY +
      "/users/register/guest",
    success: function(result) {
      console.log("user registered as guest, initApp");
      localStorage.setItem("userToken", JSON.stringify(result["user-token"]));
      initApp();
    },
    error: function(result) {
      console.log("error = ", result);
    }
  });

Any ideas?

Hi Dan,

the error you receive is not from Backendless, it’s somewhere in your code, so it’s hard for me to assist you with this.
BTW, why don’t you use our JS SDK? This will greatly simplify your development and coding. Most (if not all) cases are already thought out in our library.

Hi! Thanks for replying. I’m pretty new to any kind of frontend/backend dev - I’m using Backbone.js for my frontend which calls the database via RESTAPI calls, I got the impression from the docs that you either used the SDK or you used RESTAPI to interface with the DB - I didn’t think you could do both.

Aside from that though - I’ve uploaded the app here - you can recreate the issue if you clear local storage and cache a couple of times.

In a previous backendless implementation ( using the SDK this time ) I ran into the same error which you helped me resolve which made me conclude it was something wrong with my register as guest implementation.

Does that link provide any clues with the issue? Cheers!

Well, I tried a lot of times to clear cache and Local Storage and reload page after this, but got no error. I’m using Chrome 78.0.3904.97. Maybe some additional steps to reproduce required. But anyway, the error you’ve described is definitely comes not from the Backendless side. It may appear in some of your js libraries you’ve included in your app. Try to find where function GetCommandSRC is used. This is the place where error occurs.

As for using REST API along with the SDK, it’s ok, but there is no need in this, because SDK fully covers all the REST API methods. It just gives you a handly instruments to write code cleaner and faster. I would recommend you to spend some time on reading the documentation.

Are you running any sort of Kaspersky Internet protection product by any chance? It looks to me that one of their product is wrapping XMLHttpRequest::open() calls to analyze what web pages are doing, but their implementation is buggy, hence the error. Try to disable an option called “Inject script into web traffic to interact with web pages”. The error should go away forever I hope.

Thank you! Yes! I’m using Kaspersky - disabled the feature and it’s fixed! Thanks for the steer about the SDK too, I’ll look at that next time I need to use Backendless.

1 Like