Getting Started with Scripting in ForgeRock Identity Cloud: Part 3 - Capturing user login time

This is Part 3 of 5 in the series Getting started with Scripting in ForgeRock Identity Cloud.

Capturing user login time using a script ~ 10 minutes

Capturing the login time in a user’s profile upon successful authentication can be useful in many situations. At minimum it can be used to keep track of active vs dormant user accounts in a system.

ForgeRock Identity Cloud has a sample Journey Decision Node script that calculates the current date and time and inserts it into the sharedState. When invoked from a Scripted Decision node in an authentication journey, the script makes the current date and time (effectively the time at which a user authenticates) available in the sharedState, which can then be used by a suitable node later in the journey to update the user’s profile.

Overview

This guide takes you through the following steps:

Creating the last-login-time script in Identity Cloud

  1. In the Identity Cloud Admin UI, go to /alpha > Scripts > Auth Scripts > + New Script.

  2. Select Journey Decision Node and click Next.

  3. Provide the following details:

    Name: last-login-time
    Description: Script to set last login time in ForgeRock Identity Cloud
    JavaScript: Replace the placeholder code with the code below. You can also find the sample script on ForgeRock GitHub Community repository, here.

       /**
       * @file Script to store the last login time of a user on successful AuthN
       * @version 0.1.0
       * @keywords authN lastLoginTime ISO8601
       * @license
       * DISCLAIMER: The sample code described herein is provided on an "as is" basis, without warranty of any kind, to the fullest extent permitted by law. ForgeRock does not warrant or guarantee the individual success developers may have in implementing the sample code on their development platforms or in production configurations. ForgeRock does not warrant, guarantee or make any representations regarding the use, results of use, accuracy, timeliness or completeness of any data or information relating to the sample code. ForgeRock disclaims all warranties, expressed or implied, and in particular, disclaims all warranties of merchantability, and warranties related to the code, or any service or software related thereto.
       * ForgeRock shall not be liable for any direct, indirect or consequential damages or costs of any type arising out of any action taken by you or others related to the sample code.
       */
    
      /**
       * Script configuration
      */
      var config = {
          /**
           * @property {string} nodeName - The name of the executing node, used for logging
           * @property {string} lastLoginAttribute - The name of attribute used to the store the last login timestamp of a user
           */
          lastLoginAttribute: "frUnindexedDate1",
          nodeName: "***last-login-time"
      };
    
      /**
       * Enum Pass or Fail outcomes
       * @readonly
       * @enum {number}
       */
      var nodeOutcome = {
          PASS: "Success"
      };
    
      /**
       * Add the node info prefix to a log message
       * @param {string} message - the message body
       * @returns a tagged version of the message
       */
       function tag(message) {
          return "***".concat(config.nodeName).concat(": ").concat(message);
      }
    
      /**
       * Node entry point
       */
      logger.message(tag("Node executing"));
      var dateTime = new Date().toISOString();
      sharedState.get("objectAttributes").put(config.lastLoginAttribute, dateTime);
      logger.message(tag("User object attributes updated to populate " + config.lastLoginAttribute + " with this date: " + dateTime));
      outcome = nodeOutcome.PASS;
    

For reference, important sections of the script are described in the table below:

Code Section

Description
var config = { 
        lastLoginAttribute: "frIndexedDate1", 
        nodeName: "***last-login-time"
};
Declares the following two properties:
  • lastLoginAttribute – points to the Identity Cloud IDM attribute identified (frIndexedDate1) to store the last login time of a user
  • nodeName – sets a name for the node (***last-login-time)
var nodeOutcome = { 
        PASS: "Success" 
};

Declares a property PASS set to a value "Success". This is used to define the outcome of the node later in the code.

 function tag(message) { 
    return "***".concat(config.nodeName). 
        concat(": ").concat(message); 
} 
logger.message(tag("Node executing"));

Defines a function named tag that concatenates the value of the nodeName config property as a tag to the messages it receives from the logger methods (logger.message) in the code.

e.g: ******last-login-time: Node executing

var dateTime = new Date().toISOString();

Sets the current date & time in ISO format as value to the variable dateTime.

sharedState.get("objectAttributes").
put(config.lastLoginAttribute, dateTime); 
logger.message(tag("User object attributes updated"));

Updates the "objectAttributes" in the sharedState to include the lastLoginAttribute property value, set to date & time saved in the dateTime variable.

The Identity Management nodes save the data in shared state in the "objectAttributes" object. An example:

objectAttributes={username=fruser10,givenName=ForgeRock,sn=User10,mail=fruser10@example.com,preferences={marketing=false,updates=false}}

So to access IDM properties saved in shared state, refer to it using the "objectAttributes" object. For example, to access the last name (sn) from the shared state, returned from an Identity Management node, use the following:

var lastName = objectAttributes.get("sn").asString();

outcome = nodeOutcome.PASS; 

Lastly, the outcome variable is set to a value Success.

Recall, the script outcome can be defined either by using the outcome variable or by using the Action interface. In an earlier example, the outcome was set using the goTo method of the Action interface.

  1. Click Save and Close.

Preparing the attribute in Identity Management (IDM)

  1. In the Identity Cloud Admin UI, go to /alpha > Native Consoles > Identity Management.

    The Identity Management admin UI opens in a separate browser tab.

  2. Go to CONFIGURE > MANAGED OBJECTS.

  3. Click on Alpha_user Managed Object.

  4. Scroll down the list of properties to find the frIndexedDate1 property.

    Note that this is the IDM property used in the “last-login-time” script to set the last login time of a user. Several such placeholder attributes are present in Identity Cloud, which can be used to store values for custom attributes in a user profile. Some of these attributes are indexed, making it search-friendly, while some are unindexed. The attribute name suggests whether an attribute is indexed or not.

  5. Click on frIndexedDate1 property and change the Readable Title to Last Login Time and click Save.

Modifying the Login journey in Identity Cloud

  1. In the Identity Cloud Admin UI, go to /alpha > Journeys.

  2. Duplicate the Login journey by using the Login > > Duplicate option.

  3. Use the information below as a reference to complete the Duplicate Journey form:

    Name: Login with script sample
    Identity Object: Alpha realm - Users managed/alpha_user
    Description: Login that uses a Scripted Decision Node to capture last login time

  4. Click Save.

  5. Drag the Scripted Decision (Utilities) node on to the Login with script sample journey.

  6. Select the Scripted Decision node.

  7. Under Script drop down, choose the script “last-login-time” script you created earlier.

  8. In Outcomes, type Success and hit enter.

    Notice that the Scripted Decision node now has an outcome that can be connected to other nodes in the journey. Also, give the node a more meaningful name, say “Last Login Time”.

  9. Drag the Patch Object (Identity Management) node onto the canvas.

  10. Select the Patch Object node and change the value of Identity Resource property to managed/alpha_user.

    gs_scripts_patch_object

  11. Connect the nodes as shown in the following screenshot and click Save.

Testing the journey

  1. In the top right corner of the journey edit page, copy the journey preview URL.

  2. In a supported browser, different from the one that has an active Identity Cloud admin session, paste and go to the Login with script sample journey preview URL.

    The Sign In screen appears.

  3. Log in using one of the Identity Cloud user credentials (say, fruser10).

    The user is logged into the end user dashboard.

  4. Click Edit Your Profile.

  5. Click Edit Personal Info.

  6. Scroll down to see the updated Last Login Time field.

    1. Log out of the end user session.

Further reading

Other guides in the Getting started with Scripting in ForgeRock Identity Cloud series:

Other useful links:

Please provide us your feedback on this guide.

1 Like