Login SDK

syncAccess User Login SDK

The User Login SDK (Login SDK) is a JavaScript library that is used to integrate with the built-in user account management facilities in syncAccess.  Customers often need a way to add a convenient login link to their home pages that allow existing subscribers to quickly gain access to the customer's published content.  The SDK provides a convenient way to allow users to log in, log out and to see whether or not they are currently logged in. The SDK hides some of the more esoteric requirements of a direct integration with syncAccess service API methods.

Use this SDK if you want to include your own custom login link (and logged-in status form) to your own web pages.

Installing the SDK

Install the SDK by referencing the JavaScript library from your document:

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title>Login Sdk Test</title>
    <script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
</head>
<body>
<script src="https://cdn.syncronex.com/libs/v1.9/syncLoginSdk.js"></script>
<script>
    // initialization here...
</script>
</body>
</html>
  • Note the Login SDK requires JQuery version 2 or higher so you must also include a reference to an appropriate JQuery library.
  • The current version of the login SDK must be referenced from within the <body> element in your document. The SDK leverages dynamic <iframe>elements during load so the library must have access to the body of the document. The SDK won’t work correctly if you reference it from the head section of the html page.

For test purposes: you should reference the library from our test/staging servers:  https://cdn.stage.syncronex.com/libs/v1.9/syncLoginSdk.js

Initializing the SDK

The Login SDK must be setup with specific configuration options before you can use it. Set your options in a <script> block that is executed when your page loads like this:

<script>
    var sdk = window.syncLoginSdk;
    sdk.applicationOrigin = 'https://syncaccess-co-pr.syncronex.com';
    sdk.debug = true;
    sdk.apiTimeout = 5000;
    sdk.sessionExpireDays = 30;
    sdk.requireLegacyLogin = false;
    sdk.tenantId = 'co-pr'
</script>

We recommend defining a local variable like sdk and setting it to the actual login SDK object just to make working with the SDK a bit easier.  The actual SDK object is window.syncLoginSdk and this is defined by the syncLoginSdk.js file.

Options

Option Default Description
applicationOrigin
The domain-part of your site-specific Url provided by Syncronex Support. This option is required.
debug false Set this option to true to get detailed information on the SDK's processing.  This is optional and switched off by default.
apiTimeout 3000 ms Controls how long the SDK will wait for API requests before aborting and raising an error. This is optional and the default is 3 seconds (3000 ms).
sessionExpireDays 30 Controls how many days saved session data will be kept. This is an optional setting that defaults to 30 days.
requireLegacyLogin false This option is only required if you are planning to use the original syncAccess workflow OR if you are using the Federated Authentication API (for example, you have a Replica Edition product that is leveraging the Syncronex logon in a Single Sign On mode).  Contact Syncronex Support if you are unsure whether or not you need to set this option.
tenantId
This option is required if you are using your own domain to reference syncAccess objects (i.e. you are not using the traditional https://syncaccess-co-pr.syncronex.com domain name, where ‘co’ is the company and ‘pr’ is the property). It should contain the company and property separated by a hyphen or an underscore (e.g. sync-test1 or sync_test1). Contact Syncronex Support if you are unsure whether or not you need to set this option.

Quick Start Example

The following example code shows how to create a very basic login status form using the LoginSdk. You can copy this example into your own html page and experiment with it to get a feel for how the SDK works.

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title>Login Sdk Test</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
    <style>
        body {
            padding-top: 50px;
        }
        * {
            border-radius: 0 !important;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="row check-status-view">
            <div class="col-sm-12">
                <p>Checking status...</p>
            </div>
        </div>
        <form class="form logged-out-view">
            <div class="form-group">
                <label for="exampleInputEmail1">Email address</label>
                <input type="email" class="form-control" id="inputEmail" 
                       placeholder="Email">
            </div>
            <div class="form-group">
                <label for="exampleInputPassword1">Password</label>
                <input type="password" class="form-control" id="inputPassword"    
                       placeholder="Password">
            </div>
            <button id="submit" type="submit" 
                    class="btn btn-info">Login</button>
        </form>
        <br/>
        <div class="row logged-in-view">
            <div class="col-sm-12">
                <p>Welcome back <span id="userNameSpan">???</span> 
                    <a id="btnLogout" href="javascript:void(0)">logout</a>
                </p>
            </div>
        </div>
    </div>
    <script src="https://cdn.syncronex.com/libs/v1.9/syncLoginSdk.js"></script>    
    <script>
        var sdk = window.syncLoginSdk;
        sdk.applicationOrigin = 
          'https://syncaccess-sync-ncsstage1.stage.syncronex.com';
        sdk.apiTimeout = 5000;
        $('#submit').click(function (event) {
            // if you use <input type="submit">, remember to
            // supress the built-in form submit behavior
            // otherwise, the page will refresh before the login
            // has completed.
            event.preventDefault();

            var un = $('#inputEmail').val();
            var pw = $('#inputPassword').val();
            sdk.loginUser(un, pw, function (data) {
                checkStatus();
            }, function (data) {
                alert('logon failed!');
            });
        });
        $('#btnLogout').click(function () {
            sdk.logOut(function () {
                checkStatus();
            }, function () {
                alert('logout failed!');
                checkStatus();
            });
        });
        var checkStatus = function () {
            $('.logged-in-view').hide();
            $('.logged-out-view').hide();
            $('.check-status-view').show();
            sdk.getLoginStatus(function (data) {
                setView(true,data.username);
            }, function (errStatus) {
                setView();
            });
        };
        var setView = function (loggedIn,userName) {
            if (loggedIn) {
                $('.check-status-view').hide();
                $('.logged-out-view').hide();
                $('#userNameSpan').html(userName ? userName:'unknown');
                $('.logged-in-view').show();
            } else {
                $('#userNameSpan').html('????');
                $('.check-status-view').hide();
                $('.logged-in-view').hide();
                $('.logged-out-view').show();
            }
        };
        $(function () {
            checkStatus();
        });
    </script>
</body>
</html>

SDK Functions

.loginUser(username,password,successCallback,failCallback)

username: String

Current user's authentication identifier.  This is typically an email address[1] and is a required field to the function.

password: String

Current user's authentication password.  This is a required value.

successCallback: Function(LoginUserResult:object)

You must provide a function that will be called by the Login SDK when the supplied credentials have been validated and the user has been signed into the system.  User login is an asynchronous process so a callback function is required.  The provided function will be passed a LoginUserResult object.

failCallback: Function(LoginUserResult:object)

This is a function that will be called when the user login process fails (for any reason, including system error OR invalid credentials).  The user login process is asynchronous so a callback function is required here.  The provided function will be passed a LoginUserResult object.

Use the login function to send credentials to the server and log the user in.  Note that all requests to the server are done over https so data is encrypted over the wire.  This function is useful when you wish to create your own login form on your page instead of redirecting the user to a syncAccess page.

.getLoginStatus(successCallback,failCallback)

successCallback: Function(LoggedInStatus:object)

A function that will be called when the system determines that the current user is actively signed in.  Checking the status of the current user is an asynchronous operation so you must provide a callback function here.  The provided function will be passed a LoggedInStatus object.

failCallback: Function(LoggedInStatus:object)

A function that will be called when the system determines that the current user is not signed in.  Checking the status of the current user is an asynchronous operation so you must provide a callback function here.  The provided function will be passed a LoggedInStatus object.

Use this function to find out if the current user is actively signed in.  If the current user is signed in, this function will call the provided successCallback function and pass it an object that provides some details about the logged in user.  You can then use those details to decorate a logged-in status form on your page.

.getLoggedInUserProfile(successCallback,failCallback)

successCallback: Function(UserProfile:object)

A function that will be called when the system has successfully fetched the logged-in user’s profile information.  Fetching the user’s profile is an asynchronous operation so you must provide a callback function.  The function will be passed a UserProfile object as an argument.

failCallback: Function(ErrorInfo:string)

A function to call if the attempt to get user profile data fails.

Use this function to fetch basic profile information about the logged-in user. Specifically, the first name and last name (if they are recorded).  There must be a logged-in user for this method to work. It will report a failure condition if you call this without a logged-in user.  You’d typically call this function after calling the getLoginStatus function and establishing that there is a current user.

.logout(successCallback,failCallback)

successCallback: Function()

A function that will be called when the current user is successfully logged out of the system.  There are no arguments passed to the callback function.

failCallback: Function()

A function that will be called if an error occurs while trying to log the current user off of the system.  A failure here may or may not mean the user is actually logged out. You should call the getLoggedInStatus method to verify.

Use the logout function to sign out the currently logged-in user.  After the logout, a call to getLoggedInStatus will indicate that there is no currently signed in user. 

.getSubscriberStatus(successCallback,failCallback)

successCallback: Function(SubscriberStatus:object)

A function that will be called once the system has pulled up the current user's subscription details.  Finding the subscriber's details is an asynchronous operation so you must provide a callback method here that will be executed once the details are available.  The provided function will be passed a SubscriberStatus object (see below).

failCallback: Function(SubscriberStatus:object,errorMessage:String)

A function that will be called if there is an error trying to determine the current user's subscription status.  The provided function will be passed an empty SubscriberStatus object and an error message that provides some insight into the problem.

Use the getSubscriberStatus method if you want information about the user's subscription status.  Keep in mind that a user is allowed to log in even if she does not have any active plans at all.  Logging into the system is independent of checking a given user's authorization (permissions) to view a particular kind of content.  Combining the getLoggedInStatus and getSubscriberStatus methods should give you a complete picture of the current user.

SDK Objects

Many of the SDK functions will pass specific data structures back to your callback functions.  This section describes the important objects that you'll need to work with when implementing a solution built on the Login SDK.

LoginUserResult

This kind of object describes the results of a user login attempt.  If the login attempt was successful, this object will contain the user's username as well as authentication tokens.  If the login attempt fails, the object will contain an error message that provides details as to why the attempt failed. The callback functions provided to the .loginUser method get passed objects of this type.

{
    token: string,
    username: string,
    legacyToken: string,
    errorMsg: string
}

token

If the login attempt was successful, this property will hold the user's temporary authentication token.  The value is null if the login attempt failed.

username

If the login attempt was successful, this property will hold the user's username value. This is typically the user's email. The value is null if the login attempt failed.

legacyToken

If you are using the legacy purchase workflow and if the login attempt was successful, this property will hold the legacy authentication token.  Just as with the regular authentication token, the value here is null if the login attempt failed.  If you are not using the legacy purchase workflow, this value will always be null.

errorMsg

If the login attempt fails for any reason, this property will hold details explaining why the attempt failed.  This value is null if the login attempt succeeded.

LoggedInStatus

This object provides information about the logged in user and is passed to the callback functions provided in the .getLoggedInStatus function. The most useful information is the username which can be used to decorate a logged in status area on your page.

{
    loggedIn: boolean,
    username: string,
    email: string,
    portalAuthToken: string,
    legacyAuthToken: string,
    userid: number
}

loggedIn

This is a true/false property that indicates whether the user is currently logged into the system.

username

This property will hold the current user's username value if the user is actively logged in.  If there is no logged in user, this value will be set to null and the value of the loggedIn property would be false. 

email

This property holds the current user’s email address.  Note that the email and username are typically the same value except in some older instances of syncAccess.

portalAuthToken

This property holds the current user’s temporary authentication token.

legacyAuthToken

If the system is running in a mixed-mode environment and RequireLegacyLogin  is set to true, then this property will hold the older authentication token used to authenticate the user against legacy workflow.

userid

This property will hold the current user's internal identifier. This is a permanent and consistent unique id used to identify the user within the system.

 

UserProfile

This object provides minimal profile data for the current, logged-in, user. 

{
    userId: number,
    firstName: string,
    lastName: string
}

userId: Number

This property will hold the current user's internal identifier. This is a permanent and consistent unique id used to identify the user within the system

firstName: String

This property holds the user’s first name if one was recorded. First name is not a required field in the system so there is a possibility this value could be an empty string.

lastName: String

This property holds the user’s last name if one was recorded. Like first name, the Last Name is not a required field in the system so this value could be blank.  For example, if a new user creates an account in the system but does not proceed to enter any other information as part of a new subscription purchase, she will have a blank first and last name in the system.  Its’ up to the programmer to account for potentially blank data and fall back to using the email address, etc.

SubscriberStatus

This object provides details about the specific plan(s) the current user has.  You can use this object to determine specific subscriber status based on different subscriptions or to apply any other specific logic to a user based on her current subscriptions.  This object is passed to a callback function provided to the getSubscriberStatus function.

{
    hasPlans: boolean,
    hasActivePlans: boolean,
    planList: planList[]
}

hasPlans: Boolean

This is a convenience property you can use to quickly decide if the current user has any plans at all (either active or inactive). This property is true if the planList array is not empty.

hasActivePlans  : Boolean

This is a convenience property you can use to quickly decide if the current user has valid subscriptions.  Remember that a user can log into the system even if she doesn't have any active subscriptions.  Logging into the system is independent of determining a user's access permissions.  This property is true if the planList array is not empty and at least one of the plans in the array is active.

planList: SubscriberPlan[]

This property holds a list of SubscriberPlan objects for the current user.  There may be zero, one, or more plans for the current user. See below for details on a SubscriberPlan.

SubscriberPlan

This is a child object within the SubscriberStatus object.  A SubscriberPlan describes a specific plan (aka subscription) that is held by the user.

{
    id: String,
    purchased: Date,
    cancelled: Date,
    planId: Int,
    planCode: String,
    planName: String,
    active: Boolean,
    mapped: Boolean,
    circulationSystemId: String
}

id

This is an internal identifier that represents the current user plus the specific plan. It's only useful for notation and debugging purposes.

purchased

This property represents the date and time when the plan was associated with the user. Note that for a new plan purchased through the syncAccess workflow, this date really does represent a 'purchase' date. However, for plans that get assigned to a user as the result of an activation, admin-assignment, etc., this value only represents when the plan was applied to the user. As an example, if an existing subscriber activates here current print subscription, the purchased date here will reflect the date and time at which she activated.  The actual purchase date of her existing subscription is likely far in the past.  The date and time reflect UTC.

cancelled

This property represents the date and time on which the plan was cancelled by an administrator OR the date and time at which the circulation system reported the underlying subscription no longer valid.  The date and time reflect UTC.

planId

This property holds the internal numeric identifier for the plan that was assigned to the user.

planCode

This property holds the plan's code value as defined in the Plan Configuration area within the administrative console.

planName

This property holds the plan's name value as defined in the Plan Configuration area within the administrative console.

active

This property indicates whether or not the plan is still considered active.  Cancelled plans, for instance, are not active.  This property provides a convenient way to detect active or inactive without having to query the purchased and/or cancelled date properties.

mapped

This property indicates whether or not the plan was assigned to the user as the result of a circulation system communication (synchronization).  In other words, the plan was not specifically chosen by the user during a purchase but was assigned because the user's underlying circulation system subscription(s) qualified as valid subscriptions allowing access to content.

circulationSystemId

For any plans that are linked to a circulation system, this property will hold the underlying system's identifier for a subscription. For example, in an NCS Circulation system, this property would hold the NCS subscription Id (aka account number) and is useful for tying the subscriber back to a specific record within the underlying circulation system.

Here is an example of a SubscriberStatus object.

{
  hasPlans: true,
  hasActivePlans: true,
  planList: [
    {
      id: 477,
      purchased: 2017-01-06T16:58:41,
      cancelled: 2017-01-11T22:55:24,
      planId: 3,
      planCode: MONDIG,
      planName: Monthly Digital,
      active: false,
      mapped: false,
      circulationSystemId: 
    },
    {
      id: 496,
      purchased: 2017-04-17T20:27:45,
      cancelled: 9999-12-31T23:59:59.9999999,
      planId: 5,
      planCode: PRINT,
      planName: *Qualified Plan,
      active: true,
      mapped: true,
      circulationSystemId: 156194
    }
  ]
}

[1] Older versions of syncAccess would support a non-email-based username but that functionality is being deprecated.