PingIDM 7.5.0

Scripting function reference

If you need to request specific resource versions, refer to REST API versioning.

Functions (access to managed objects, system objects, and configuration objects) within IDM are accessible to scripts via the openidm object, which is included in the top-level scope provided to each script.

Most of the following function examples are in JavaScript. To use the functions in Groovy scripts, make adjustments as necessary. For example, you need to pass parameters using square brackets (not curly braces):

openidm.query("managed/user", ["_queryFilter" : "/userName sw \"user.1\""], ["userName", "_id"])

The script engine supports the following functions:

openidm.create(resourceName, newResourceId, content, params, fields)

This function creates a new resource object.

Parameters
resourceName

string

The container in which the object will be created, for example, managed/user.

newResourceId

string

The identifier of the object to be created, if the client is supplying the ID. If the server should generate the ID, pass null here.

content

JSON object

The content of the object to be created.

params

JSON object (optional)

Additional parameters that are passed to the create request.

fields

JSON array (optional)

An array of the fields that should be returned in the result. The list of fields can include wild cards, such as * or *_ref. If no fields are specified, the entire new object is returned.

Returns

The created resource object.

Throws

An exception is thrown if the object could not be created.

Example
openidm.create("managed/user", ID, JSON object);
openidm.patch(resourceName, rev, value, params, fields)

This function performs a partial modification of a managed or system object. Unlike the update function, only the modified attributes are provided, not the entire object.

Parameters
resourceName

string

The full path to the object being updated, including the ID.

rev

string

The revision of the object to be updated. Use null if the object is not subject to revision control, or if you want to skip the revision check and update the object, regardless of the revision.

value

An array of one or more JSON objects

The value of the modifications to be applied to the object. The patch set includes the operation type, the field to be changed, and the new values. A PATCH request can add, remove, replace, or increment an attribute value.

A remove operation removes a property if the value of that property equals the specified value, or if no value is specified in the request. The following example value removes the marital_status property from the object, if the value of that property is single:

[
    {
        "operation": "remove",
        "field": "marital_status",
        "value": "single"
    }
]

For fields whose value is an array, it’s not necessary to know the position of the value in the array, as long as you specify the full object. If the full object is found in the array, that value is removed. The following example removes user adonnelly from bjensen’s reports:

{
    "operation": "remove",
    "field": "/manager",
    "value": {
      "_ref": "managed/user/adonnelly",
      "_refResourceCollection": "managed/user",
      "_refResourceId": "adonnelly",
      "_refProperties": {
        "_id": "ed6620e4-98ba-410c-abc0-e06dc1be7aa7",
        "_rev": "000000008815942b"
      }
    }
}

If an invalid value is specified (that is a value that does not exist for that property in the current object) the patch request is silently ignored.

A replace operation replaces an existing value, or adds a value if no value exists.

params

JSON object (optional)

Additional parameters that are passed to the patch request.

fields

JSON array (optional)

An array of the fields that should be returned in the result. The list of fields can include wild cards, such as * or *_ref. If no fields are specified, the entire new object is returned.

Returns

The modified resource object.

Throws

An exception is thrown if the object could not be updated.

Examples

Patching an object to add a value to an array:

openidm.patch("managed/role/" + role._id, null, [{"operation":"add", "field":"/members/-", "value": {"_ref":"managed/user/" + user._id}}]);

Patching an object to remove an existing property:

openidm.patch("managed/user/" + user._id, null, [{"operation":"remove", "field":"marital_status", "value":"single"}]);

Patching an object to replace a field value:

openidm.patch("managed/user/" + user._id, null, [{"operation":"replace", "field":"/password", "value":"Passw0rd"}]);

Patching an object to increment an integer value:

openidm.patch("managed/user/" + user._id, null, [{"operation":"increment","field":"/age","value":1}]);
openidm.read(resourceName, params, fields)

This function reads and returns a resource object.

Parameters
resourceName

string

The full path to the object to be read, including the ID.

params

JSON object (optional)

The parameters that are passed to the read request. Generally, no additional parameters are passed to a read request, but this might differ, depending on the request. If you need to specify a list of fields as a third parameter, and you have no additional params to pass, you must pass null here. Otherwise, you simply omit both parameters.

fields

JSON array (optional)

An array of the fields that should be returned in the result. The list of fields can include wild cards, such as * or *_ref. If no fields are specified, the entire object is returned.

Returns

The resource object, or null if not found.

Example
openidm.read("managed/user/"+userId, null, ["*", "manager"]);
openidm.update(resourceName, rev, value, params, fields)

This function updates an entire resource object.

Parameters
id

string

The complete path to the object to be updated, including its ID.

rev

string

The revision of the object to be updated. Use null if the object is not subject to revision control, or if you want to skip the revision check and update the object, regardless of the revision.

value

object

The complete replacement object.

params

JSON object (optional)

The parameters that are passed to the update request.

fields

JSON array (optional)

An array of the fields that should be returned in the result. The list of fields can include wild cards, such as * or *_ref. If no fields are specified, the entire object is returned.

Returns

The modified resource object.

Throws

An exception is thrown if the object could not be updated.

Example

In this example, the managed user entry is read (with an openidm.read, the user entry that has been read is updated with a new description, and the entire updated object is replaced with the new value.

var user_read = openidm.read('managed/user/' + source._id);
user_read['description'] = 'The entry has been updated';
openidm.update('managed/user/' + source._id, null, user_read);
openidm.delete(resourceName, rev, params, fields)

This function deletes a resource object.

Parameters
resourceName

string

The complete path to the to be deleted, including its ID.

rev

string

The revision of the object to be deleted. Use null if the object is not subject to revision control, or if you want to skip the revision check and delete the object, regardless of the revision.

params

JSON object (optional)

The parameters that are passed to the delete request.

fields

JSON array (optional)

An array of the fields that should be returned in the result. The list of fields can include wild cards, such as * or *_ref. If no fields are specified, the entire object is returned.

Returns

Returns the deleted object if successful.

Throws

An exception is thrown if the object could not be deleted.

Example
openidm.delete('managed/user/'+ user._id, user._rev);
openidm.query(resourceName, params, fields)

This function performs a query on the specified resource object. For more information, refer to Construct Queries.

Parameters
resourceName

string

The resource object on which the query should be performed, for example, "managed/user", or "system/ldap/account".

params

JSON object

The parameters that are passed to the query (_queryFilter, or _queryId). Additional parameters passed to the query will differ, depending on the query.

Certain common parameters can be passed to the query to restrict the query results. The following sample query passes paging parameters and sort keys to the query.

reconAudit = openidm.query("audit/recon", {
    "_queryFilter": queryFilter,
    "_pageSize": limit,
    "_pagedResultsOffset": offset,
    "_pagedResultsCookie": string,
    "_sortKeys": "-timestamp"
});

For more information about _queryFilter syntax, refer to Common Filter Expressions. For more information about paging, refer to Page Query Results.

fields

list

A list of the fields that should be returned in the result. The list of fields can include wild cards, such as * or *_ref. The following example returns only the userName and _id fields:

openidm.query("managed/user", { "_queryFilter": "/userName sw \"user.1\""}, ["userName", "_id"]);

This parameter is particularly useful in enabling you to return the response from a query without including intermediary code to massage it into the right format.

Fields are specified as JSON pointers.

Returns

The result of the query. A query result includes the following parameters:

query-time-ms

(For JDBC repositories only) the time, in milliseconds, that IDM took to process the query.

result

The list of entries retrieved by the query. The result includes the properties that were requested in the query.

The following example shows the result of a custom query that requests the ID, user name, and email address of all managed users in the repository.

{
  "result": [
    {
      "_id": "9dce06d4-2fc1-4830-a92b-bd35c2f6bcbb",
      "_rev": "00000000a059dc9f",
      "userName": "bjensen",
      "mail": "bjensen@example.com"
    },
    {
      "_id": "42f8a60e-2019-4110-a10d-7231c3578e2b",
      "_rev": "00000000d84ade1c",
      "userName": "scarter",
      "mail": "scarter@example.com"
    }
  ],
  "resultCount": 2,
  "pagedResultsCookie": null,
  "totalPagedResultsPolicy": "NONE",
  "totalPagedResults": -1,
  "remainingPagedResults": -1
}
Throws

An exception is thrown if the given query could not be processed.

Examples

The following sample query uses a _queryFilter to query the managed user repository:

openidm.query("managed/user", {'_queryFilter': userIdPropertyName + ' eq "' + security.authenticationId  + '"'});

The following sample query references the for-userName query, defined in the repository configuration, to query the managed user repository:

openidm.query("managed/user", {"_queryId": "for-userName", "uid": request.additionalParameters.uid });
openidm.action(resource, actionName, content, params, fields)

This function performs an action on the specified resource object. The resource and actionName are required. All other parameters are optional.

Parameters
resource

string

The resource that the function acts upon, for example, managed/user.

actionName

string

The action to execute. Actions are used to represent functionality that is not covered by the standard methods for a resource (create, read, update, delete, patch, or query). In general, you should not use the openidm.action function for create, read, update, patch, delete or query operations. Instead, use the corresponding function specific to the operation (for example, openidm.create).

Using the operation-specific functions lets you benefit from the well-defined REST API, which follows the same pattern as all other standard resources in the system. Using the REST API enhances usability for your own API, and enforces the established patterns.

IDM-defined resources support a fixed set of actions. For user-defined resources (scriptable endpoints) you can implement whatever actions you require.

Supported Actions Per Resource

The following list outlines the supported actions for each resource or endpoint. The actions listed here are also supported over the REST interface.

Actions supported on the authentication endpoint (authentication/*)

reauthenticate

Actions supported on the configuration resource (config/)

No action parameter applies.

Actions supported on custom endpoints

Custom endpoints enable you to run arbitrary scripts through the REST URI, and are routed at endpoint/name, where name generally describes the purpose of the endpoint. For more information on custom endpoints, refer to Create custom endpoints to launch scripts. You can implement whatever actions you require on a custom endpoint. IDM uses custom endpoints in its workflow implementation. Those endpoints, and their actions are as follows:

endpoint/getprocessforuser - create, complete
endpoint/gettasksview - create, complete

Actions supported on the external endpoint
  • external/email - send, for example:

    {
        emailParams = {
            "from" : 'admin@example.com',
            "to" : user.mail,
            "subject" : 'Password expiry notification',
            "type" : 'text/plain',
            "body" : 'Your password will expire soon. Please change it!'
        }
        openidm.action("external/email", "send",  emailParams);
    }
  • external/email - sendTemplate, for example:

    {
        emailParams = {
            "templateName" : "welcome",
            "to" : user.mail,
            "cc" : "ccUser1@example.com,ccUser2@example.com",
            "bcc" : "bigBoss@example.com"
        }
        openidm.action("external/email", "sendTemplate",  emailParams);
    }
  • external/rest - call, for example:

    openidm.action("external/rest", "call", params);
Actions supported on the info endpoint (info/*)

No action parameter applies.

Actions supported on managed resources (managed/*)

patch, triggerSyncCheck

Actions supported on the policy resource (policy)

validateObject, validateProperty

For example:

openidm.action("policy/" + fullResourcePath, "validateObject", request.content, { "external" : "true" });
Actions supported on the reconciliation resource (recon)

recon, reconById, cancel

For example:

openidm.action("recon/_id", "cancel", content, params);
A cancel action requires the entire reconciliation resource path (_id).
Actions supported on the repository (repo)

command

For example:

var r, command = {
    "commandId": "purge-by-recon-number-of",
    "numberOf": numOfRecons,
    "includeMapping": includeMapping,
    "excludeMapping": excludeMapping
};
r = openidm.action("repo/audit/recon", "command", {}, command);
Actions supported on the script resource (script)

eval

For example:

openidm.action("script", "eval", getConfig(scriptConfig), {});
Actions supported on the synchronization resource (sync)

getLinkedResources, notifyCreate, notifyDelete, notifyUpdate, performAction

For example:

openidm.action('sync', 'performAction', content, params);
Actions supported on system resources (system/*)

availableConnectors, createCoreConfig, createFullConfig, test, testConfig, liveSync, authenticate, script

For example:

openidm.action("system/ldap/account", "authenticate", {"username" : "bjensen", "password" : "Passw0rd"});
Actions supported on the task scanner resource (taskscanner)

execute, cancel

Actions supported on the workflow resource (workflow/*)

On workflow/processdefinition create, complete

On workflow/processinstance create, complete

For example:

var params = {
    "_key":"contractorOnboarding"
};
openidm.action('workflow/processinstance', 'create', params);

On workflow/taskinstance claim, create, complete

For example:

var params = {
    "userId":"manager1"
};
openidm.action('workflow/taskinstance/15', 'claim', params);
content

object

Content given to the action for processing.

params

object (optional)

Additional parameters passed to the script. The params object must be a set of simple key:value pairs and cannot include complex values. The parameters must map directly to URL variables, which take the form name1=val1&name2=val2&....

fields

JSON array (optional)

An array of the fields that should be returned in the result. The list of fields can include wild cards, such as * or *_ref. If no fields are specified, the entire object is returned.

Returns

The result of the action may be null.

Throws

If the action cannot be executed, an object containing an error property is returned.

openidm.encrypt(value, cipher, alias)

This function encrypts a value.

Parameters
value

any

The value to be encrypted.

cipher

string

The cipher with which to encrypt the value, using the form "algorithm/mode/padding" or just "algorithm". Example: AES/CBC/PKCS5Padding.

alias

string

A purpose defined in the secrets.json file, such as idm.password.encryption.

Using key aliases from the keystore, such as openidm-sym-default, is deprecated. Use purposes instead.
Returns

The value, encrypted with the specified cipher and key.

Throws

An exception is thrown if the object could not be encrypted.

openidm.decrypt(value)

This function decrypts a value.

Parameters
value

object

The value to be decrypted.

Returns

A deep copy of the value, with any encrypted value decrypted.

Throws

An exception is thrown if the object could not be decrypted for any reason. An error is thrown if the value is passed in as a string - it must be passed in an object.

openidm.isEncrypted(object)

This function determines if a value is encrypted.

Parameters
object to check

any

The object whose value should be checked to determine if it is encrypted.

Returns

Boolean, true if the value is encrypted, and false if it is not encrypted.

Throws

An exception is thrown if the server is unable to detect whether the value is encrypted, for any reason.

openidm.hash(value, algorithm, options)

This function calculates a value using a salted hash algorithm.

Supported Hashing Algorithms and Configuration Properties
Algorithm Config Property and Description

BCRYPT

cost

Value between 4 and 31. Default is 13.

PBKDF2

hashLength

Byte-length of the generated hash. Default is 16.

saltLength

Byte-length of the salt value. Default is 16.

iterations

Number of cryptographic iterations. Default is 20000.

hmac

HMAC algorithm. Default is SHA3-256.

Supported values:

  • SHA-224

  • SHA-256

  • SHA-384

  • SHA-512

  • SHA3-224

  • SHA3-256

  • SHA3-384

  • SHA3-512

SCRYPT

hashLength

Byte-length of the generated hash, must be greater than or equal to 8. Default is 16.

saltLength

Byte-length of the salt value. Default is 16.

n

CPU/Memory cost. Must be greater than 1, a power of 2, and less than 2^(128 * r / 8). Default is 32768.

p

Parallelization. Must be a positive integer less than or equal to Integer.MAX_VALUE / (128 * r * 8). Default is 1.

r

Block size. Must be greater than or equal to 1. Default is 8.

SHA-256

saltLength

Byte-length of the salt value. Default is 16.

This is the default hashing.

SHA-384

saltLength

Byte-length of the salt value. Default is 16.

SHA-512

saltLength

Byte-length of the salt value. Default is 16.

Parameters
value

any

The value to be hashed.

algorithm

string (optional)

The hashing algorithm. Example: SHA-512.

If no algorithm is provided, a null value must be passed, and the algorithm defaults to SHA-256.

options

For Groovy, Map or JSON value (optional)

For JavaScript, JSON object (optional)

Configuration properties for the selected algorithm.

Returns

The value, calculated with the specified hash algorithm.

Throws

An exception is thrown if the object could not be hashed for any reason.

Examples
Groovy (Map)
openidm.hash(\"dummy\", \"BCRYPT\", [\"cost\": 10]);
Groovy (JSON value)
JsonValue v = new JsonValue( [\"cost\": 10]); return openidm.hash(\"dummy\", \"BCRYPT\", v);
JavaScript
openidm.hash(\"dummy\", \"BCRYPT\", {\"cost\": 10})
openidm.isHashed(value)

This function detects whether a value has been calculated with a salted hash algorithm.

Parameters
value

any

The value to be reviewed.

Returns

Boolean, true if the value is hashed, and false otherwise.

Throws

An exception is thrown if the server is unable to detect whether the value is hashed, for any reason.

openidm.matches(string, value)

This function detects whether a string, when hashed, matches an existing hashed value.

Parameters
string

any

A string to be hashed.

value

any

A hashed value to compare to the string.

Returns

Boolean, true if the hash of the string matches the hashed value, and false otherwise.

Throws

An exception is thrown if the string could not be hashed.

These functions can also have a vanity binding to make them more descriptive, such as consent.action() instead of openidm.action("consent" ...), by setting resourceBindings when you declare the script. In this case, the syntax for these functions would omit the resource name from the function parameters.

See Call a script from the IDM configuration for more information about resourceBindings.

Log functions

IDM also provides a logger object to access the Simple Logging Facade for Java (SLF4J) facilities. The following code shows an example of the logger object.

logger.info("Parameters passed in: {} {} {}", param1, param2, param3);

To set the log level for JavaScript scripts, add the following property to your project’s conf/logging.properties file:

org.forgerock.openidm.script.javascript.JavaScript.level

The level can be one of SEVERE (highest value), WARNING, INFO, CONFIG, FINE, FINER, or FINEST (lowest value). For example:

org.forgerock.openidm.script.javascript.JavaScript.level=WARNING

In addition, JavaScript has a useful logging function named console.log(). This function provides an easy way to dump data to the IDM standard output (usually the same output as the OSGi console). The function works well with the JavaScript built-in function JSON.stringify and provides fine-grained details about any given object. For example, the following line will print a formatted JSON structure that represents the HTTP request details to STDOUT.

console.log(JSON.stringify(context.http, null, 4));

These logging functions apply only to JavaScript scripts. To use the logging functions in Groovy scripts, the following lines must be added to the Groovy scripts:

import org.slf4j.*;
logger = LoggerFactory.getLogger('logger');

The script engine supports the following log functions:

logger.debug(string message, object... params)

Logs a message at DEBUG level.

Parameters
message

string

The message format to log. Params replace {} in your message.

params

object

Arguments to include in the message.

Returns

A null value if successful.

Throws

An exception is thrown if the message could not be logged.

logger.error(string message, object... params)

Logs a message at ERROR level.

Parameters
message

string

The message format to log. Params replace {} in your message.

params

object

Arguments to include in the message.

Returns

A null value if successful.

Throws

An exception is thrown if the message could not be logged.

logger.info(string message, object... params)

Logs a message at INFO level.

Parameters
message

string

The message format to log. Params replace {} in your message.

params

object

Arguments to include in the message.

Returns

A null value if successful.

Throws

An exception is thrown if the message could not be logged.

logger.trace(string message, object... params)

Logs a message at TRACE level.

Parameters
message

string

The message format to log. Params replace {} in your message.

params

object

Arguments to include in the message.

Returns

A null value if successful.

Throws

An exception is thrown if the message could not be logged.

logger.warn(string message, object... params)

Logs a message at WARN level.

Parameters
message

string

The message format to log. Params replace {} in your message.

params

object

Arguments to include in the message.

Returns

A null value if successful.

Throws

An exception is thrown if the message could not be logged.

Copyright © 2010-2024 ForgeRock, all rights reserved.