Auth library

Contents

Manage principals and authentication

If, while using this API, you are getting authentication errors like "Access denied to user [unknown]" it means that user role in the current context lacks sufficient permissions (for example when executed from inside a service). In this case you must explicitly execute the function in the context of System Administrator role.

Usage

Add the following to your build.gradle file:

dependencies {
  include xplibs.auth
}

Add the import statement to your code:

import authLib from '/lib/xp/auth';

You are now ready to use the API.

Functions

addMembers

Adds members to a principal (group or role).

Parameters

Name Kind Attributes Details

principalKey

string

Key of the group or role to add members to

members

string[]

Keys of users and groups to add

Returns

void

Example

Add members to a specified principal
import {addMembers} from '/lib/xp/auth';

addMembers('role:roleId', ['user:system:user1', 'group:system:group-a']);

changePassword

Changes or clears the password for the specified user.

Parameters

An object with the following keys and their values:

Name Kind Attributes Description

userKey

string

Key of the user to change password for

password

string

<optional>

The new password to set. If null, the password will be cleared.

Returns

void

Example

Change the password of the current user
import {getUser, changePassword} from '/lib/xp/auth';

const user = getUser();

if (user) {
    changePassword({
        userKey: user.key,
        password: 'new-secret-password'
    });
}

createGroup

Creates a group.

Parameters

An object with the following keys and their values:

Name Kind Attributes Description

idProvider

string

Key for id provider where the group will be created

name

string

Group name

displayName

string

<optional>

Group display name

description

string

<optional>

Group description

Returns

object: The created group.

Example

Creating a group named "group-a"
import {createGroup} from '/lib/xp/auth';

const group = createGroup({
    idProvider: 'myIdProvider',
    name: 'group-a',
    displayName: 'Group A',
    description: "description"
});
Sample response
({
    type: "group",
    key: "group:system:group-a",
    displayName: "Group A",
    description: "description"
})

createIdProvider

Creates an ID provider.

Parameters

An object with the following keys and their values:

Name Kind Attributes Description

key

string

ID provider key

displayName

string

ID provider display name

description

string

<optional>

ID provider description

idProviderConfig

object

<optional>

Binds this provider to one application. Without it the provider is incomplete and login plumbing won’t resolve back to an app.

permissions

object[]

<optional>

ID provider permissions

permissions properties

Properties
Name Type Attributes Default Description

principal

string

Principal key

access

string

Permission level: READ, CREATE_USERS, WRITE_USERS, ID_PROVIDER_MANAGER, ADMINISTRATOR

idProviderConfig properties

Properties
Name Type Attributes Default Description

applicationKey

string

Key of the application whose handlers serve requests for this provider.

config

object

<optional>

Per-instance configuration tree passed to the bound application.

Returns

object: The created ID provider.

Example

Creating an ID provider
import {createIdProvider} from '/lib/xp/auth';

const idProvider = createIdProvider({
    key: 'myIdProvider',
    displayName: 'My ID Provider',
    description: 'My ID provider description',
    idProviderConfig: {
        applicationKey: 'com.example.myidprovider',
        config: {
            // app-specific configuration
        }
    },
    permissions: [
        {
            principal: 'role:system.admin',
            access: 'ADMINISTRATOR'
        }
    ]
});
Sample response
({
    key: "myIdProvider",
    displayName: "My ID Provider",
    description: "My ID provider description",
    idProviderConfig: {
        applicationKey: "com.example.myidprovider",
        config: {
            // app-specific configuration
        }
    }
})

createRole

Creates a role.

Parameters

An object with the following keys and their values:

Name Kind Attributes Description

name

string

The name of the role. The key of the role will be role:<name>.

displayName

string

<optional>

Role display name

description

string

<optional>

Role description

Returns

object: The created role.

Example

Creating a role named "aRole"
import {createRole} from '/lib/xp/auth';

const role = createRole({
    name: 'aRole',
    displayName: 'Role Display Name',
    description: 'description'
});
Sample response
({
    type: "role",
    key: "role:aRole",
    displayName: "Role Display Name",
    description: "description"
})

createUser

Creates a user.

Parameters

An object with the following keys and their values:

Name Kind Attributes Description

idProvider

string

Key for id provider where the user will be created

name

string

User login name

displayName

string

<optional>

User display name

email

string

<optional>

User e-mail

Returns

object: The created User.

Example

Creating a user named "userName"
import {createUser} from '/lib/xp/auth';

const user = createUser({
    idProvider: 'myIdProvider',
    name: 'user1',
    displayName: 'The One And Only',
    email: 'user1@enonic.com'
});
Sample response
({
    type: "user",
    key: "user:system:user1",
    displayName: "The One And Only",
    disabled: false,
    email: "user1@enonic.com",
    login: "user1",
    idProvider: "myIdProvider",
    hasPassword: false
})

deletePrincipal

Deletes the principal with the specified key.

Parameters

Name Kind Attributes Details

principalKey

string

Principal key to delete

Returns

boolean: true if the principal was deleted, false otherwise.

Example

Deleting a user
import {deletePrincipal} from '/lib/xp/auth';

const deleted = deletePrincipal('user:myIdProvider:userId');

findPrincipals

Search for principals matching the specified criteria.

Parameters

An object with the following keys and their values. All parameters are optional:

Name Kind Attributes Description

type

string

<optional>

Principal type to look for, one of: 'user', 'group' or 'role'. If not specified all principal types will be included.

idProvider

string

<optional>

Key of the id provider to look for. If not specified, all id providers will be included.

start

number

<optional>

First principal to return from the search results. It can be used for pagination. Default is 0.

count

number

<optional>

A limit on the number of principals to be returned. Default is 10.

name

string

<optional>

Name of the principal to look for

searchText

string

<optional>

Text to look for in any principal field.

Returns

object: The "total" number of principals matching the search, the "count" of principals included, and an array of "hits" containing the principals.

Example

Searching for principals for 'user1'
import {findPrincipals} from '/lib/xp/auth';

const result = findPrincipals({
    idProvider: "user-store",
    start: 0,
    count: 10,
    searchText: "user1"
});
Sample response
({
    total: 1,
    count: 1,
    hits: [
        {
            type: "user",
            key: "user:system:user1",
            displayName: "The One And Only",
            disabled: false,
            email: "user1@enonic.com",
            login: "user1",
            idProvider: "myIdProvider",
            hasPassword: true
        }
    ]
})

findUsers

Search for users matching the specified query.

Parameters

An object with the following keys and their values:

Name Kind Attributes Description

query

string

Query expression

start

number

<optional>

Start index for paging. Default is 0.

count

number

<optional>

Number of users to fetch. Default is 10.

sort

string

<optional>

Sorting expression

includeProfile

boolean

<optional>

If set to true, a full profile of each user will be included in the result. Default is false.

Returns

object: An object containing the total number of hits, the number returned and an array of the hits.

Example

Searching for the first person in the Juve family.
import {findUsers} from '/lib/xp/auth';

const findUsersResult = findUsers({
    count: 1,
    query: "displayName LIKE '*Juve'"
});
Sample response
({
    total: 2,
    count: 1,
    hits: [
        {
            type: "user",
            key: "user:system:jorgen-juve",
            displayName: "Jørgen Juve",
            disabled: false,
            email: "jju@enonic.com",
            login: "jorgen-juve",
            idProvider: "system",
            hasPassword: true
        }
    ]
})
If you want to find a user by key, you have to use _id field in the query parameter.
Find a user by key.
import {findUsers} from '/lib/xp/auth';

const findUsersResult = findUsers({
    count: 1,
    query: "_id = 'user:system:jorgen-juve'"
});

generatePassword

Generates a random secure password that may be suggested to a user.

Parameters

None

Returns

string: A suggestion for a secure password.

Example

Generate a password and return the password string
import {generatePassword} from '/lib/xp/auth';

const pwd = generatePassword();

getIdProviderConfig

Returns the ID provider configuration. Meant to be called from an ID provider implementation.

Parameters

None

Returns

object: An object with all the values in the configuration, or null if no configuration is set.

Example

Reading a value from the ID provider configuration
import {getIdProviderConfig} from '/lib/xp/auth';

const config = getIdProviderConfig<{ field?: string }>();

if (config) {
    log.info('Field value for the current ID provider config = %s', config.field);
}

getIdProviders

Returns all id providers configured on the system. Each entry’s idProviderConfig is present only when the provider is bound to an application; incomplete providers come back without it.

Parameters

None

Returns

object[]: A list of ID providers.

Example

Retrieving all ID providers
import {getIdProviders} from '/lib/xp/auth';

const idProviders = getIdProviders();
Sample response
([
    {
        key: "system",
        displayName: "System Id Provider"
    },
    {
        key: "myIdProvider",
        displayName: "My ID Provider",
        description: "My ID provider description",
        idProviderConfig: {
            applicationKey: "com.example.myidprovider",
            config: {}
        }
    }
])

getMembers

Returns a list of principals that are members of the specified principal.

Parameters

Name Kind Attributes Details

principalKey

string

Principal key (group or role) to retrieve members for

Returns

object[]: A list of users and groups that are members of the principal, or an empty array if none.

Example

Searching for members of the Content Manager group
import {getMembers} from '/lib/xp/auth';

const result = getMembers('group:system:content-managers');
Sample response
[{
    type: "user",
    key: "user:system:user1",
    displayName: "User 1",
    disabled: false,
    email: "user1@enonic.com",
    login: "user1",
    idProvider: "system",
    hasPassword: true
},
{
    type: "user",
    key: "user:system:user2",
    displayName: "User 2",
    disabled: false,
    email: "user2@enonic.com",
    login: "user2",
    idProvider: "system",
    hasPassword: false
}]

getMemberships

Returns the list of principals which the specified principal is a member of.

Parameters

Name Kind Attributes Details

principalKey

string

Principal key (user or group) to retrieve memberships for

transitive

boolean

<optional>

Retrieve transitive memberships. Considered false if not specified.

Returns

object[]: A list of groups and roles that the specified principal is a member of.

Example

Searching for direct memberships of 'user1'
import {getMemberships} from '/lib/xp/auth';

const result = getMemberships('user:system:user1');
Sample response
[{
    type: "role",
    key: "role:system.admin",
    displayName: "Administrator"
}]
Searching for transitive memberships of 'user1'
import {getMemberships} from '/lib/xp/auth';

const result = getMemberships('user:system:user1', true);
Sample response
[
    {
        type: "role",
        key: "role:system.admin.login",
        displayName: "Login to administration console"
    },
    {
        type: "group",
        key: "group:system:content-managers",
        displayName: "Content Managers"
    },
    {
        type: "role",
        key: "role:cms.expert",
        displayName: "CMS Expert"
    },
    {
        type: "role",
        key: "role:cms.project.default.editor",
        displayName: "Default project editor"
    }
]

getPrincipal

Returns the principal with the specified key.

Parameters

Name Kind Attributes Details

principalKey

string

Principal key to look for

Returns

object: The principal as an object, or null if it does not exist.

Example

Retrieving the full principal for 'user1'
import {getPrincipal} from '/lib/xp/auth';

const result = getPrincipal('user:system:user1');
Sample response
({
    type: "user",
    key: "user:system:user1",
    displayName: "User 1",
    disabled: false,
    email: "user1@enonic.com",
    login: "user1",
    idProvider: "system",
    hasPassword: true
})

getProfile

Returns the profile of a user.

Parameters

An object with the following keys and their values:

Name Kind Attributes Details

key

string

Principal key of the user

scope

string

<optional>

Scope of the data to retrieve

Returns

object: Profile data, or null if the user was not found.

Example

Retrieving the profile of 'user1'
import {getProfile} from '/lib/xp/auth';

const result = getProfile({
    key: 'user:system:user1'
});
Sample response
({
    nickName: "User Nick"
})

getUser

Returns the logged-in user. If not logged-in, this will return null.

Parameters

An optional object with the following keys and their values:

Name Kind Attributes Description

includeProfile

boolean

<optional>

If set to true, the user’s profile is included in the result. Default is false.

Returns

object: User data, or null if not logged in.

Example

Retrieving the profile of 'user1'
import {getUser} from '/lib/xp/auth';

const result = getUser();
Sample response
({
    type: "user",
    key: "user:system:user1",
    displayName: "User 1",
    disabled: false,
    email: "user1@enonic.com",
    login: "user1",
    idProvider: "system",
    hasPassword: true
})

hasRole

Checks if the logged-in user has the specified role.

Parameters

Name Kind Attributes Details

role

string

Role name to check for

Returns

boolean: true if the current user has the role, false otherwise.

Example

Checking a role
import {hasRole} from '/lib/xp/auth';

const isAdmin = hasRole('system.admin');

login

Logs in a user through the specified idProvider, with username and password.

Parameters

An object with the following keys and their values:

Name Kind Attributes Details

user

string

Mandatory name of the user to log in

password

string

<optional>

Password for the user. Ignored if skipAuth is set to true, mandatory otherwise.

idProvider

string

<optional>

Name of id provider where the user is stored. If not specified system id provider will be used.

skipAuth

boolean

<optional>

Skip authentication. Default is false if not specified.

sessionTimeout

number

<optional>

Session timeout (in seconds). By default, the value of session.timeout from com.enonic.xp.web.jetty.cfg

scope

string

<optional>

Defines the scope of the login. Valid values are SESSION, REQUEST and NONE. When scope is set to SESSION the login is persistent. If scope is set to REQUEST the login is only valid for the current request. Scope NONE allows to check correctness of username and password without logging into the system. Default is SESSION if not specified.

Returns

object: The login result.

Example

Logging in a user
import {login} from '/lib/xp/auth';

const loginResult = login({
    user: 'user1',
    password: 'myPwd1',
    idProvider: 'myIdProvider'
});
Sample response
({
    authenticated: true,
    user: {
        type: "user",
        key: "user:system:user1",
        displayName: "The One And Only",
        disabled: false,
        email: "user1@enonic.com",
        login: "user1",
        idProvider: "myIdProvider",
        hasPassword: true
    }
})

logout

Logs out the currently logged-in user.

Parameters

None

Returns

void

modifyGroup

Updates an existing group.

Parameters

An object with the following keys and their values:

Name Kind Attributes Details

key

string

Principal key of the group to modify

editor

function

Group editor function to apply to the group

Returns

object: The updated group, or null if the group was not found.

Example

Changing a group
import {modifyGroup} from '/lib/xp/auth';

// Callback to edit the group.
function groupEditor(c) {
    c.displayName = 'Modified display name';
    c.description = 'descriptionX';
    return c;
}

// Modify group with specified key.
const group = modifyGroup({
    key: 'group:system:group-a',
    editor: groupEditor
});
Sample response
({
    type: "group",
    key: "group:system:group-a",
    displayName: "Modified display name",
    description: "descriptionX"
})

modifyProfile

Updates an existing user profile. Will create a new profile, if an existing one with provided scope was not found.

Parameters

An object with the following keys and their values:

Name Kind Attributes Details

key

string

Principal key of the user

scope

string

<optional>

Scope of the data to retrieve and update

editor

function

Profile editor function to apply

Returns

object: The updated profile, or null if the user was not found.

Example

Changing a profile
import {modifyProfile} from '/lib/xp/auth';

// Callback to edit the profile.
function profileEditor(c) {
    if (!c) {
        c = {};
    }
    c.nickName = "User Nick";
    return c;
}

// Modify profile with specified key.
const profileModified = modifyProfile({
    key: 'user:system:user1',
    editor: profileEditor
});
Sample response
({
    nickName: "User Nick"
})

modifyRole

Updates an existing role.

Parameters

An object with the following keys and their values:

Name Kind Attributes Details

key

string

Principal key of the role to modify

editor

function

Role editor function to apply to the role

Returns

object: The updated role, or null if the role was not found.

Example

Changing a role
import {modifyRole} from '/lib/xp/auth';

// Callback to edit the role.
function roleEditor(c) {
    c.displayName = 'Nothing Role';
    c.description = 'This role does not give access to anything!';
    return c;
}

// Modify role with a specified key.
const theRole = modifyRole({
    key: 'role:aRole',
    editor: roleEditor
});
Sample response
({
    type: "role",
    key: "role:aRole",
    displayName: "Nothing Role",
    description: "This role does not give access to anything!"
})

modifyUser

Updates an existing user.

Parameters

An object with the following keys and their values:

Name Kind Attributes Details

key

string

Principal key of the user to modify

editor

function

User editor function to apply to the user

Returns

object: The updated User, or null if the user was not found.

Example

Changing a user
import {modifyUser} from '/lib/xp/auth';

// Callback to edit the user.
function userEditor(c) {
    c.displayName = 'User 1-A';
    c.email = 'user1a@enonic.com';
    return c;
}

// Modify user with a specified key.
const theUser = modifyUser({
    key: 'user:system:user1',
    editor: userEditor
});
Sample response
({
    type: "user",
    key: "user:system:user1",
    displayName: "User 1-A",
    disabled: false,
    email: "user1a@enonic.com",
    login: "user1",
    idProvider: "myIdProvider",
    hasPassword: true
})

removeMembers

Removes members from a principal (group or role).

Parameters

Name Kind Attributes Details

principalKey

string

Key of the group or role to remove members from

members

string[]

Keys of the principals to remove

Returns

void

Example

Remove members from a specified principal
import {removeMembers} from '/lib/xp/auth';

removeMembers('role:roleId', ['user:system:user1', 'group:system:group-a']);

Type Definitions

User

Type

object

Properties

Name Type Description

type

string

The type of principal, always "user" for users

key

string

The unique key of the user

displayName

string

The display name of the user

modifiedTime

string

The last modified time of the user in ISO 8601 format

disabled

boolean

Whether the user is disabled or not

email

string

The email of the user

login

string

The login name of the user

idProvider

string

The id provider where the user is stored

hasPassword

boolean

Whether the user has a password set


Contents

Contents