---
title: Scripting function reference
description: If you need to request specific resource versions, refer to REST API versioning.
component: pingidm
version: 8.1
page_id: pingidm:scripting-guide:scripting-func-ref
canonical_url: https://docs.pingidentity.com/pingidm/8.1/scripting-guide/scripting-func-ref.html
keywords: ["Scripting", "Router", "Configuration", "Functions"]
section_ids:
  openidm_functions: openidm functions
  global-utility-functions: Global utility functions
  logger-functions: Log functions
---

# Scripting function reference

|   |                                                                                                                                    |
| - | ---------------------------------------------------------------------------------------------------------------------------------- |
|   | If you need to request specific resource versions, refer to [REST API versioning](../rest-api-reference/rest-api-versioning.html). |

Functions (access to managed objects, system objects, and configuration objects) within IDM are accessible to scripts using the `openidm` object that's included in the top-level scope provided to each script. IDM also provides a `logger` object and utility functions available globally in the script execution context.

|   |                                                                                                                                                                                                                                                                                                                                    |
| - | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|   | 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):```groovy
openidm.query("managed/user", ["_queryFilter" : "/userName sw \"user.1\""], ["userName", "_id"])
``` |

## `openidm` functions

The script engine supports the following functions:

> **Collapse: 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 couldn't be created.
>
> * Example
>
>   ```javascript
>   openidm.create("managed/user", ID, JSON object);
>   ```

> **Collapse: 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`:
>
>     ```json
>     [
>         {
>             "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`:
>
>     ```json
>     {
>         "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's a value that doesn't exist for that property in the current object) the patch request is silently ignored.
>
>     A `replace` operation replaces the entire field value. For array or multivalued relationship fields (such as `/roles`), this means the entire array is replaced, not just a single element. To swap a single element in an array, use a `remove` operation followed by an `add` operation.
>
> * 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 couldn't be updated.
>
> * Examples
>
>   Patching an object to add a value to an array:
>
>   ```javascript
>   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:
>
>   ```javascript
>   openidm.patch("managed/user/" + user._id, null, [{"operation":"remove", "field":"marital_status", "value":"single"}]);
>   ```
>
>   Patching an object to remove a specific value from a multivalued relationship array:
>
>   ```javascript
>   openidm.patch("managed/user/" + user._id, null, [{
>     "operation": "remove",
>     "field": "/roles",
>     "value": {
>       "_ref": "managed/role/" + role._id,
>       "_refResourceCollection": "managed/role",
>       "_refResourceId": role._id,
>       "_refProperties": {
>         "_id": "ef85ae74-6675-4f76-8bc3-19ac226cc703",
>         "_rev": "778e7955-cd0a-43c2-a714-7076d83fb710-132"
>       }
>     }
>   }]);
>   ```
>
>   Patching an object to replace a field value:
>
>   ```javascript
>   openidm.patch("managed/user/" + user._id, null, [{"operation":"replace", "field":"/password", "value":"Passw0rd"}]);
>   ```
>
>   Patching an object to increment an integer value:
>
>   ```javascript
>   openidm.patch("managed/user/" + user._id, null, [{"operation":"increment","field":"/age","value":1}]);
>   ```

> **Collapse: 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
>
>   ```javascript
>   openidm.read("managed/user/"+userId, null, ["*", "manager"]);
>   ```

> **Collapse: 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 isn't 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 couldn't 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.
>
>   ```javascript
>   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);
>   ```

> **Collapse: 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 isn't 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 couldn't be deleted.
>
> * Example
>
>   ```javascript
>   openidm.delete('managed/user/'+ user._id, user._rev);
>   ```

> **Collapse: openidm.query(resourceName, params, fields)**
>
> This function performs a query on the specified resource object. Learn more in [Construct queries](../objects-guide/queries.html#constructing-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.
>
>     ```javascript
>     reconAudit = openidm.query("audit/recon", {
>         "_queryFilter": queryFilter,
>         "_pageSize": limit,
>         "_pagedResultsOffset": offset,
>         "_pagedResultsCookie": string,
>         "_sortKeys": "-timestamp"
>     });
>     ```
>
>     You can find more information about `_queryFilter` syntax in [Common filter expressions](../objects-guide/queries.html#query-filters). Learn more in [Page query results](../objects-guide/queries.html#paging-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:
>
>     ```javascript
>     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.
>
>     ```json
>     {
>       "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 couldn't be processed.
>
> * Examples
>
>   The following sample query uses a `_queryFilter` to query the managed user repository:
>
>   ```javascript
>   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:
>
>   ```javascript
>   openidm.query("managed/user", {"_queryId": "for-userName", "uid": request.additionalParameters.uid });
>   ```

> **Collapse: 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 isn't covered by the standard methods for a resource (create, read, update, delete, patch, or query). In general, you shouldn't 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](../rest-api-reference/preface.html), 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 describes the purpose of the endpoint. Learn more about custom endpoints in [Create custom endpoints to launch scripts](script-custom-endpoints.html). 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:
>
>         ```javascript
>         {
>             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:
>
>         ```javascript
>         {
>             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:
>
>         ```javascript
>         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:
>
>       ```javascript
>       openidm.action("policy/" + fullResourcePath, "validateObject", request.content, { "external" : "true" });
>       ```
>
>     * Actions supported on the reconciliation resource (`recon`)
>
>       recon, reconById, cancel
>
>       For example:
>
>       ```javascript
>       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:
>
>       ```javascript
>       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:
>
>       ```javascript
>       openidm.action("script", "eval", getConfig(scriptConfig), {});
>       ```
>
>     * Actions supported on the synchronization resource (`sync`)
>
>       getLinkedResources, notifyCreate, notifyDelete, notifyUpdate, performAction
>
>       For example:
>
>       ```javascript
>       openidm.action('sync', 'performAction', content, params);
>       ```
>
>     * Actions supported on system resources (`system/*`)
>
>       availableConnectors, createCoreConfig, createFullConfig, test, testConfig, liveSync, authenticate, script
>
>       For example:
>
>       ```javascript
>       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:
>
>       ```javascript
>       var params = {
>           "_key":"contractorOnboarding"
>       };
>       openidm.action('workflow/processinstance', 'create', params);
>       ```
>
>       On `workflow/taskinstance` claim, create, complete
>
>       For example:
>
>       ```javascript
>       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 can't 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 can't be run, an object containing an `error` property is returned.

> **Collapse: 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 couldn't be encrypted.

> **Collapse: 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 couldn't 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.

> **Collapse: 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's encrypted.
>
> * Returns
>
>   Boolean, `true` if the value is encrypted, and `false` if it isn't encrypted.
>
> * Throws
>
>   An exception is thrown if the server is unable to detect whether the value is encrypted, for any reason.

> **Collapse: 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`\[[1](#_footnotedef_1 "View footnote.")] | * `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`\[[1](#_footnotedef_1 "View footnote.")] | * `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 couldn't be hashed for any reason.
>
> * Examples
>
>   * Groovy (Map)
>
>     ```groovy
>     openidm.hash(\"dummy\", \"BCRYPT\", [\"cost\": 10]);
>     ```
>
>   * Groovy (JSON value)
>
>     ```groovy
>     JsonValue v = new JsonValue( [\"cost\": 10]); return openidm.hash(\"dummy\", \"BCRYPT\", v);
>     ```
>
>   * JavaScript
>
>     ```javascript
>     openidm.hash(\"dummy\", \"BCRYPT\", {\"cost\": 10})
>     ```

> **Collapse: 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.

> **Collapse: 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
>
>     The hashed value (as a `$crypto` object) to compare against the hash of 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 couldn't be hashed.
>
> * Example
>
>   JavaScript
>
>   ```javascript
>   (function () {
>       var body = request.content; (1)
>
>       if (request.method === 'create') {
>           // POST
>           // SHA256HashedPassword = openidm.hash(body.password, "SHA-256");
>           var hashedValue = {
>               "$crypto": {
>                   "value": {
>                       "algorithm": "SHA-256",
>                       "data": "QVjOMKdAifIxKC5y/bl4SXdlUx79EHLegucBF3SXEUP7LVKlXuluJH0J5y33a648"
>                   },
>                   "type": "salted-hash"
>               }
>           };
>           var SHA256HashedPassword = openidm.matches(body.password, hashedValue); (2)
>           return {
>               body: SHA256HashedPassword (2)
>           };
>       }
>   }());
>   ```
>
> |       |                                                                                                                                                                                                                    |
> | ----- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
> | **1** | Learn more about available fields for the request object in [Create custom endpoints to launch scripts](script-custom-endpoints.html).                                                                             |
> | **2** | The `openidm.matches` function references the full `$crypto` object value instead of a hashed string, and its boolean result is stored in `SHA256HashedPassword` and returned in the `body` field of the response. |
>
> > **Collapse: Show example output**
> >
> > ```json
> > {
> >   "_id": "",
> >   "body": true  (1)
> > }
> > ```
> >
> > |       |                                                                         |
> > | ----- | ----------------------------------------------------------------------- |
> > | **1** | You must call the full `$crypto` object value to get a `true` response. |

|   |                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| - | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|   | 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.Learn more in [Call a script from the IDM configuration](script-call.html) for more information about `resourceBindings`. |

## Global utility functions

These functions are available globally in the script execution context.

> **Collapse: btoa(stringToEncode)**
>
> Encodes a string in Base64. This is a global script binding that implements the canonical JavaScript `btoa` function.
>
> * Parameters
>
>   * stringToEncode
>
>     string
>
>     The string to Base64 encode. This string should consist of characters that can be represented by a single byte (Latin1 characters). For strings containing multi-byte characters, an error might occur or the output might be unexpected, as standard `btoa` is designed for binary strings.
>
> * Returns
>
>   An ASCII string representing the Base64-encoded version of `stringToEncode`.
>
> * Example
>
>   ```javascript
>   var originalString = "Hello World!";
>   var encodedString = btoa(originalString);
>   encodedString; (1)
>   ```
>
>   |       |                                                                        |
>   | ----- | ---------------------------------------------------------------------- |
>   | **1** | In this example, the returned `encodedString` is `"SGVsbG8gV29ybGQh"`. |

> **Collapse: atob(encodedString)**
>
> Decodes a Base64-encoded string. This is a global script binding that implements the canonical JavaScript `atob` function.
>
> * Parameters
>
>   * encodedString
>
>     string
>
>     The Base64-encoded string to be decoded.
>
> * Returns
>
>   An ASCII string representing the decoded version of `encodedString`.
>
> * Throws
>
>   An exception is typically thrown if the input `encodedString` is not a valid Base64 string.
>
> * Example
>
>   ```javascript
>   var base64String = "SGVsbG8gV29ybGQh";
>   var decodedString = atob(base64String);
>   decodedString; (1)
>   ```
>
>   |       |                                                                    |
>   | ----- | ------------------------------------------------------------------ |
>   | **1** | In this example, the returned `decodedString` is `"Hello World!"`. |

## 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.

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

To set the log level for JavaScript scripts, add an appender with the `<filter class="ThresholdFilter">` tag to your project's `conf/logback.xml` file:

```xml
<filter class="ThresholdFilter">
    <level>DEBUG</level>
</filter>
```

Learn more about log levels in [log levels](../monitoring-guide/server-logs.html#log-levels).

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.

```javascript
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:```groovy
import org.slf4j.*;
logger = LoggerFactory.getLogger('logger');
``` |

The script engine supports the following log functions:

> **Collapse: 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 couldn't be logged.

> **Collapse: 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 couldn't be logged.

> **Collapse: 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 couldn't be logged.

> **Collapse: 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 couldn't be logged.

> **Collapse: 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 couldn't be logged.

***

[1](#_footnoteref_1). This hashing algorithm is not supported by [Bouncy Castle FIPS](../security-guide/security-bouncy-castle-fips.html)
