Authentication Library

Contents

This library contains built-in authentication functions.

If, when using functions of this library, 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 "com.enonic.xp:lib-auth:${xpVersion}"
}

In your JavaScript controller, add a require statement:

const authLib = require('/lib/xp/auth');

You are now ready to use the library functionality.

Functions

addMembers

Adds members to a principal (user or role).

Parameters

Name Kind Details

principalKey

string

Key of the principal to add members to

members

Array.<string>

A list of the new memebers that should be added to the principal

Returns

void

changePassword

Changes password for specified user.

Parameters

An object with the following keys and their values:

Name Description

userKey

The key of the user to change password for

password

The new password

Returns

void

createGroup

Creates a group.

Parameters

An object with the following keys and their values:

Name Kind Description

idProvider

string

Key for id provider where the group will be created

name

string

Group name

displayName

string

Group display name

description

string

A description of the principal

Returns

object : The created group.

Example

Creating a group named "group-a"
var group = authLib.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"
}

createRole

Creates a role.

Parameters

An object with the following keys and their values:

Name Kind Description

name

string

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

displayName

string

Role display name

description

string

A description of the role

Returns

object : The created role.

Example

Creating a role named "aRole"
var role = authLib.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 Description

idProvider

string

Key for id provider where the user will be created

name

string

User login name

displayName

string

User display name

email

string

Optional user e-mail

Returns

object : The created group.

Example

Creating a user named "userName"
var user = authLib.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"
}

deletePrincipal

Deletes the principal with the specified key.

Parameters

Name Kind Details

principalKey

string

Key of the principal to delete

Returns

boolean : true if the principal was deleted, false otherwise

Example

Deleting a user
var deleted = authLib.deletePrincipal('user:myIdProvider:userId');

findPrincipals

Search for principals matching the specified criteria.

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

Name Kind Description

type

string

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

idProvider

string

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

start

string

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

count

string

A limit on the number of principals to be returned

name

string

Name of the principal to look for

searchText

string

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'
var result = authLib.findPrincipals({
    idProvider: "user-store",
    start: 0,
    count: 10,
    searchText: "user1"
});
Sample response
{
    type: "user",
    key: "user:system:user1",
    displayName: "The One And Only",
    disabled: false,
    email: "user1@enonic.com",
    login: "user1",
    idProvider: "myIdProvider"
}

findUsers

Search for users matching the specified query.

An object with the following keys and their values:

Name Kind Description

query

string

Query expression

start

number

Optional start index for paging

count

number

Optional number of users to fetch at a time

sort

string

Optional sorting expression

includeProfile

boolean

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

Returns

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

Example

Searching for the first person in the Juve family.
var findUsersResult = auth.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"
        }
    ]
}
If you want to find a user by key, you have to use _id field in the query parameter.
Find a user by key.
var findUsersResult = auth.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
var pwd = authLib.generatePassword();

getIdProviderConfig

This function returns the ID provider configuration. It is meant to be called from an ID provider controller.

Parameters

None

Returns

object : An object with all the values in the configuration

getMembers

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

Parameters

Name Kind Details

principalKey

string

Principal key to retrieve the members of.

Returns

Array.<object> : A list of objects for each member of the principal or empty array if none.

Example

Searching for members of the Content Manager group
var result = authLib.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"},
 {type:"user",key:"user:system:user2",displayName:"User 2",disabled:false,email:"user2@enonic.com",login:"user2",idProvider:"system"
 }]

getMemberships

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

Parameters

Name Kind Details

principalKey

string

Principal key to retrieve memberships for

transitive

boolean

Retrieve transitive memberships. Considered false if not specified

Returns

Array.<string> : A list of the principals that the specified principal is a member of

Example

Searching for direct memberships of 'user1'
var result = authLib.getMemberships('user:system:user1');
Sample response
[{
    "type": "role",
    "key": "role:system.admin",
    "displayName":"Administrator"
}]
Searching for transitive memberships of 'user1'
var result = authLib.getMemberships('user:system:user1', true);
Sample response
[
    "role:system.admin.login",
    "group:system:content-managers",
    "role:cms.expert",
    "role:cms.cm.app"
]

getPrincipal

Returns the principal with the specified key.

Parameters

Name Kind Details

principalKey

string

Principal key to retrieve memberships for

Returns

object : The principal as an object

Retrieving the full principal for 'user1'
var result = authLib.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"
}

getProfile

Returns the profile of a user.

Parameters

An object with the following keys and their values:

Name Kind Details

principalKey

string

Principal key to retrieve profile for

scope

string

Optional scope setting

Returns

object : Profile data

Example

Retrieving the profile of 'user1'
var result = authLib.getProfile('user:system:user1');
Sample response
{
    nickName: "User Nick"
}

getUser

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

Parameters

None

Returns

object : User data

Example

Retrieving the profile of 'user1'
var result = authLib.getUser();
Sample response
{
    type: "user",
    key: "user:system:user1",
    displayName: "User 1",
    disabled: false,
    email: "user1@enonic.com",
    login: "user1",
    idProvider: "system"
}

hasRole

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

Parameters

Name Kind Details

role

string

The role to check for

Returns

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

Example

Checking a role
var hasRole = auth.hasRole('system.admin');

login

Login a user through the specified idProvider, with userName and password.

Parameters

An object with the following keys and their values:

Name Kind Details

user

string

Mandatory name of the user to log in

password

string

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

idProvider

string

Name of id provider where the user is stored. If not specified it will try all available id providers, in alphabetical order.

skipAuth

boolean

Skip authentication. Default is false if not specified.

sessionTimeout

number

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

scope XP XP 7.3.0 7.3.0

string

Defines the scope of the login. Valid values are SESSION, REQUEST and NONE (starting from version XP XP 7.8.0 7.8.0 ). 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 logged in user

Example

Logging in a user
    var loginResult = authLib.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"
    }
}

logout

Logout the currently logged-in user.

Parameters

None

Returns

void

modifyGroup

Retrieves the group specified and updates it with the changes applied.

Parameters

An object with the following keys and their values:

Name Kind Details

key

string

Principal key of the group to modify

editor

function

Group editor function

Returns

object : The updated group

Example

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

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

modifyProfile

This function retrieves the profile of a user and updates it.

Parameters

An object with the following keys and their values:

Name Kind Details

key

string

Principal key of the user

scope

string

Optional scope setting

editor

function

Profile editor function

Returns

object : The updated profile

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

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

modifyRole

Retrieves the role specified and updates it with the changes applied through an editor.

Parameters

An object with the following keys and their values:

Name Kind Details

key

string

The role key

editor

function

Role editor function

Returns

object : The updated role

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

// Modify role with specified key.
var theRole = authLib.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

Retrieves the user specified and updates it with the changes applied through the editor.

Parameters

An object with the following keys and their values:

Name Kind Details

key

string

The user key

editor

function

User editor function

Returns

object : The updated user

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

// Modify user with specified key.
var theUser = authLib.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"
}

removeMembers

Removes members from a principal (group or role).

Parameters

Name Kind Details

principalKey

string

The principal key of a group or a role to remove members from

members

Array.<string>

Principal keys to remove as members

Returns

void

Remove members from specified principal.
authLib.removeMembers('role:roleId', ['user:system:user1', 'group:system:group-a']);

Contents

Contents