How to keep logged in session after user is successfully authenticated with his iCloud Account?

325 Views Asked by At

This is what I call when my site is loaded:

(function($){})(window.jQuery);

$(document).ready(function () {

  window.addEventListener('cloudkitloaded', function() {

    CloudKit.configure({
      containers: [{
        containerIdentifier: 'iCloud.pl.blueworld.fieldservice',
        apiToken: 'fc363369412ad6c99020e7e0ed3e2be121008e34534cff7debe1f4f7f829d152',
        environment: 'production'
      }]
    });

    var container = CloudKit.getDefaultContainer();
    var privateDB = container.privateCloudDatabase;

    this.gotoAuthenticatedState = function(userInfo) {

      if(userInfo.isDiscoverable) {
        //success
      } else {
        //failure
      }

      container
      .whenUserSignsOut()
      .then(this.gotoUnauthenticatedState);
    };

    this.gotoUnauthenticatedState = function(error) {
      //do something of sign out

      container
      .whenUserSignsIn()
      .then(this.gotoAuthenticatedState)
      .catch(this.gotoUnauthenticatedState);
    };

    container.setUpAuth().then(function(userInfo) {

      if(userInfo) {
          this.gotoAuthenticatedState(userInfo);
      } else {
          this.gotoUnauthenticatedState();
      }
    });
  });
});

And when I login with success, there correct button appears:

enter image description here

But every time when I refresh the page this button changes:

enter image description here

What to do to keep session and possibility to fetch records until user manually will log out?

How to check if there exists current session (user already authenticated itself) and use it?

1

There are 1 best solutions below

0
Brian Hamm On

Put your token inside an apiTokenAuth object, and add a persist key.

CloudKit.configure({
    containers: [{
        containerIdentifier: '<your container>',
        environment: 'production',

        apiTokenAuth: {
            apiToken: '<your token>',
            persist: true
        }
    }]
});