Skip to content

Sys.User

Sys.User gives app code the user who is making the current call, so it can check their Roles and Permissions. Server-side code can also look up, create, change and delete users and store per-user settings. Client-side code can log the End user in and out and let them change their own account.

The current user is a different object on each side:

  • On the server side, Sys.User.currentUser is a User. Check Roles with hasEffectiveRole() and Permissions with hasPermission().
  • On the client side, it is a UserRecord. Check Roles with hasRole() and Permissions with hasPermission().

Both take the qualified name of a Role or Permission, which is what This.$Roles.<RoleName> and This.$Permissions.<PermissionName> hold.

Availability: Everywhere

getUserById(userId: UserIdType, failIfNotFound?: boolean): Promise<User>

Gets a user by ID. The returned User is a copy without password data.

ParameterTypeDescription
userIdUserIdTypeID of the user.
failIfNotFoundbooleanOptional. Whether to throw if there is no such user. With false, the promise resolves to undefined instead. Default: true.

Returns: Promise<User> · Availability: Server

getUserByUsername(userName: string, failIfNotFound?: boolean): Promise<User>

Gets a user by user name. The returned User is a copy without password data.

ParameterTypeDescription
userNamestringUser name, compared exactly.
failIfNotFoundbooleanOptional. Whether to throw if there is no such user. With false, the promise resolves to undefined instead. Default: true.

Returns: Promise<User> · Availability: Server

getAllUsers(filterPredicate?: (user: User) => boolean): Promise<User[]>

Gets all users that are not deleted, sorted by user name, as copies without password data.

ParameterTypeDescription
filterPredicate(user: User) => booleanOptional. Keeps only the users for which it returns true. Default: all users.
const approvers = await Sys.User.getAllUsers((user) => user.hasEffectiveRole(This.$Roles.Approver))

Returns: Promise<User[]> · Availability: Server

getAllUserRecords(filterPredicate?: (user: User) => boolean, options?: UserRecordOptions): Promise<UserRecord[]>

Gets all users that are not deleted as UserRecord objects, which contain only the data chosen in options. Use it to hand user data to the client.

ParameterTypeDescription
filterPredicate(user: User) => booleanOptional. Keeps only the users for which it returns true. Default: all users.
optionsUserRecordOptionsOptional. Which data to include besides ID, user name and names, as an object with the fields below or '*' for all. Default: none.

UserRecordOptions fields

FieldTypeRequiredDescription
includeEmailbooleanOptionalInclude the e-mail address.
includePhonebooleanOptionalInclude the mobile phone number.
includeRolesbooleanOptionalInclude the effective Role names in roleNames.
includePermissionsbooleanOptionalInclude the effective Permission names in permissionNames.
includeGroupsbooleanOptionalInclude the group names in groupNames.
includeManagerboolean | UserRecordOptionsOptionalInclude the user’s manager as a nested UserRecord. true includes the manager’s e-mail and phone if they are included for the user; an options object chooses the manager’s data.

Note

hasRole() and hasPermission() on a UserRecord throw if its Roles or Permissions were not included.

Returns: Promise<UserRecord[]> · Availability: Server

findUser(idOrUsernameOrEmailOrFullname: string): Promise<User>

Finds a user by trying, in this order: ID, user name, e-mail address (ignoring case) and full name (first and last name separated by a space). Deleted users are included.

ParameterTypeDescription
idOrUsernameOrEmailOrFullnamestringThe value to look for.

Returns: Promise<User>, or undefined if nothing matches · Availability: Server

// server-side
searchUser(query: string, paging?: any): Promise<{ matches: UserIdAndName[]; totalCount: number }>
// client-side
searchUser(query: string, paging?: PagingDefinition): Promise<{ matches: UserIdAndName[]; totalCount: number }>

Searches users by text, for example for a user picker. The query is split at spaces, and a user matches if every part is the start of a word in their user name, first name, last name, e-mail address or ID, ignoring case. Results are sorted by full name. An empty query matches nobody. On the client side, the search runs on the server and requires a logged-in End user.

ParameterTypeDescription
querystringSearch text, for example ann mül.
pagingPagingDefinitionOptional. Which page of results to return, as pageSize and pageIndex (from 0). Default: the first 20 matches.

Returns: Promise<{ matches: UserIdAndName[]; totalCount: number }>, the page of matches as userId and name, and the number of all matches · Availability: Both

// server-side
isUsernameAvailable(userName: string): boolean
// client-side
isUsernameAvailable(userName: string): Promise<boolean>

Checks whether no user has this user name yet. On the client side, the check runs on the server and works without login.

ParameterTypeDescription
userNamestringThe user name to check.

Note

On the server side, an empty user name returns '' instead of false.

Returns: boolean on the server side, Promise<boolean> on the client side · Availability: Both

// server-side
registerUser(user: User, password: string, generatePassword: boolean): Promise<User>
// client-side
registerUser(user: User, password: string, generatePassword: boolean): Promise<string>

Creates a user account and, if the user has an e-mail address, sends them a registration e-mail containing their user name and password through the default mail server. Only userName, firstName, lastName, email and mobilePhone are taken from user; the new user has no Roles, Permissions or groups.

On the client side, this is self-registration: it works without login, but only if registering users is allowed in the system’s security settings, and it fails if the user name is taken.

ParameterTypeDescription
userUserThe new user’s data. Must be a User instance.
passwordstringThe password. Ignored if generatePassword is true. Must meet the password policy.
generatePasswordbooleanWhether Lowgile generates a password. The user must then change it at first login, and user.email is required.

Returns: the new User without password data on the server side; the new user’s ID on the client side · Availability: Both

// server-side
updateUser(user: User): Promise<void>
// client-side
updateUser(user: UserRecordUpdate): Promise<UserRecord>

Saves changes to a user.

  • On the server side, it saves the whole User, including Roles, Permissions, groups and status. A user with an id that doesn’t exist makes it throw. A user without id is created, with a generated password that is not sent to anyone.
  • On the client side, it changes the logged-in End user’s own account. Only the fields userName, firstName, lastName, email and mobilePhone may be passed, all optional; other fields make the call fail. The result is the updated account, which also becomes currentUser.

Both throw if the new user name is already taken.

ParameterTypeDescription
userUser (server-side) or UserRecordUpdate (client-side)The user, or the fields to change.

Returns: Promise<void> on the server side, Promise<UserRecord> on the client side · Availability: Both

deleteUser(userOrId: User | UserIdType): Promise<void>

Deletes a user from the database. This removes the account completely rather than setting its status to deleted. Throws if the user doesn’t exist.

ParameterTypeDescription
userOrIdUser | UserIdTypeThe user, or their ID.

Returns: Promise<void> · Availability: Server

synchronizeUsersFromIdpProvider(options: SychronizeUsersFromIdpProviderOptions): Promise<User[]>

Creates and updates users from the Microsoft Entra ID tenant of an identity provider, using the Microsoft Graph API with the identity provider’s client credentials.

ParameterTypeDescription
optionsSychronizeUsersFromIdpProviderOptionsWhich identity provider and which users to synchronize.

SychronizeUsersFromIdpProviderOptions fields

FieldTypeRequiredDescription
clientIdstringOptionalClient ID of the identity provider to use. Default: the only identity provider used for SSO login; throws if there is none or more than one.
tenantIdstringOptionalEntra ID tenant to read from. Default: the identity provider’s tenant.
includeInternalUsersbooleanRequiredWhether to include the tenant’s member users that have at least one license assigned.
includeExternalUsersbooleanOptionalWhether to include guest users.
includeNonHumanInternalUsersbooleanOptionalWhether to include member users without any license, such as shared mailboxes and service accounts.
deleteNoLongerExistingUsersbooleanOptionalWhether to set the status of Lowgile users of this identity provider that were not synchronized this time to 'deleted'.
synchronizeRolesbooleanOptionalWhether to take over the values of the users’ app role assignments for the identity provider’s application as identity provider Roles.
assignRoles(user: User) => string[]OptionalReturns the qualified Role names to give each synchronized user.
synchronizeManagerbooleanOptionalWhether to take over each user’s manager.
filterFn(graphUser: GraphUser) => booleanOptionalKeeps only the Graph users for which it returns true.

Returns: Promise<User[]>, the synchronized users · Availability: Server

getUserConfig(userOrId: User | UserIdType, moduleId: ModuleIdType, boId: BusinessObjectIdType, createDefaultValueFn?: () => Promise<any>): Promise<any>

Reads a value stored for one user under a module ID and a key, such as a user’s saved filter for a Screen. The value is stored as JSON.

ParameterTypeDescription
userOrIdUser | UserIdTypeThe user, or their ID.
moduleIdModuleIdTypeModule ID the value belongs to.
boIdBusinessObjectIdTypeKey of the value within the module, usually a Business Object ID.
createDefaultValueFn() => Promise<any>Optional. Called if no value is stored yet; its result is stored and returned.

Note

If no value is stored and createDefaultValueFn is not given, the call throws a TypeError instead of returning undefined. Pass a function that returns undefined to get undefined.

Returns: Promise<any> · Availability: Server

setUserConfig(userOrId: User | UserIdType, moduleId: ModuleIdType, boId: BusinessObjectIdType, value: any): Promise<void>

Stores a value for one user under a module ID and a key, replacing any earlier value. Read it back with getUserConfig().

ParameterTypeDescription
userOrIdUser | UserIdTypeThe user, or their ID.
moduleIdModuleIdTypeModule ID the value belongs to.
boIdBusinessObjectIdTypeKey of the value within the module.
valueanyThe value. It is stored as JSON, so class instances come back as plain objects.

Returns: Promise<void> · Availability: Server

updateUserPassword(userOrIdOrUsername: User | UserIdType | string, newPassword: string, failIfNotFound?: boolean): Promise<void>

Sets a new password for a user without knowing the old one. A user who must change their password, or is blocked, becomes active again.

ParameterTypeDescription
userOrIdOrUsernameUser | UserIdType | stringThe user, their ID or their user name.
newPasswordstringThe new password. Must meet the password policy.
failIfNotFoundbooleanOptional. Whether to throw if there is no such user. Default: true.

Returns: Promise<void> · Availability: Server

checkUserPassword(userOrIdOrUsername: User | UserIdType, password: string): Promise<boolean>

Checks whether a password is a user’s current password. A user name also works in place of the ID.

ParameterTypeDescription
userOrIdOrUsernameUser | UserIdTypeThe user, their ID or their user name.
passwordstringThe password to check.

Returns: Promise<boolean>, false also if the user doesn’t exist · Availability: Server

getUserIdentityToken(userOrId: User | UserIdType, identityProviderId: string): Promise<UserIdentityTokenRecord>

Gets the access token that an identity provider issued when the user logged in with SSO, for calling APIs on the user’s behalf. A token that expires within 60 seconds is refreshed first if possible.

ParameterTypeDescription
userOrIdUser | UserIdTypeThe user, or their ID.
identityProviderIdstringID of the identity provider.

The result has the fields accessToken, identityProviderId and scopes (string[]).

Note

If the user has no token for this identity provider, or it has expired and can’t be refreshed, the promise resolves to null, although the declared type does not include null.

Returns: Promise<UserIdentityTokenRecord> · Availability: Server

updatePassword(oldPassword: string, newPassword: string): Promise<boolean>

Changes the logged-in End user’s password.

ParameterTypeDescription
oldPasswordstringThe current password.
newPasswordstringThe new password. Must meet the password policy.

Returns: Promise<boolean>, false if the change failed · Availability: Client

login(userName: string, password: string, mfaToken?: string): Promise<ClientLoginResponse>

Logs the End user in with user name and password, and with a multi-factor token in the second step. The call does not throw if the login fails; check the response.

ParameterTypeDescription
userNamestringUser name.
passwordstringPassword.
mfaTokenstringOptional. The multi-factor token, for the second step of a login that requires one.

ClientLoginResponse fields

FieldTypeRequiredDescription
nextStageLoginStageRequired'successful' when logged in; 'mfa' if a multi-factor token is needed next; 'passwordChangeNeeded' if the password must be changed. If a step fails, it is that step ('credentials' or 'mfa') and error is set.
errorstringOptionalWhy the login failed.
hasPhonebooleanOptionalWhether the user can receive a token by text message.
hasAuthenticatorbooleanOptionalWhether the user has an authenticator app set up.
userUserRecordOptionalThe logged-in user.
refreshTokenstringOptionalToken Lowgile uses to renew the login.
expiresAtnumberOptionalWhen the login expires.
let response = await Sys.User.login(userName, password)
if (response.nextStage == 'mfa') {
response = await Sys.User.login(userName, password, mfaToken)
}
if (response.nextStage != 'successful') Sys.App.showError(response.error)

Returns: Promise<ClientLoginResponse> · Availability: Client

logout(): Promise<void>

Logs the End user out.

Returns: Promise<void> · Availability: Client

forceRenewLogin(): Promise<ClientLoginResponse>

Renews the login immediately instead of waiting for it to near expiry. The renewed login also has up-to-date user data, for example after the End user’s Roles were changed.

Returns: Promise<ClientLoginResponse> · Availability: Client

// server-side
get currentUser(): User;
// client-side
get currentUser(): UserRecord;
// shared code
const currentUser: UserRecord | User | null

The user making the current call: on the server side, the user the request or Process step runs as; on the client side, the logged-in End user.

In shared code the type is a union, so check which kind of object you have before using methods that only one of them has:

const user = Sys.User.currentUser
const isApprover = !!user && ('hasEffectiveRole' in user ? user.hasEffectiveRole(This.$Roles.Approver) : user.hasRole(This.$Roles.Approver))

Note

If no user is logged in, the value is undefined, although the declared types on the server and client side do not include it. Use ?. when the code can run without login.

Type: User on the server side, UserRecord on the client side · Availability: Everywhere

// server-side
get sessionId(): any;
// client-side
get sessionId(): string;

ID of the current session, read from the session cookie. undefined if there is no session cookie, for example in a server-side call that was not made by a browser.

Type: string · Availability: Everywhere

get ipAddress(): string;

IP address the current request came from, or undefined if the current call is not handling a request.

Type: string · Availability: Server

A user account, as Sys.User.currentUser returns it on the server side and as the server-side lookup functions return it. Its main fields are id, userName, firstName, lastName, email, mobilePhone, status ('active', 'passwordChangeNeeded', 'blocked', 'inactive' or 'deleted'), groups, managerUserId, roles and permissions (directly assigned), and effectiveRoles and effectivePermissions.

A user’s effective Roles are the directly assigned ones, those from the identity provider, and the child Roles of all of these. Their effective Permissions are the directly assigned ones and those of their effective Roles.

const user = Sys.User.currentUser
if (!user?.hasPermission(This.$Permissions.ApproveLargeOrders)) {
throw new Error('You are not allowed to approve large orders')
}

Availability: Everywhere

getName(): string

Returns the full name: first name and last name separated by a space.

Returns: string · Availability: Everywhere

hasEffectiveRole(role: UserRole | string): boolean

Checks whether the user has a Role, directly or inherited. This is the usual Role check.

ParameterTypeDescription
roleUserRole | stringThe qualified Role name, such as This.$Roles.Approver.

Returns: boolean · Availability: Everywhere

hasDirectRole(role: UserRole | string): boolean

Checks whether the Role is assigned to the user directly, not from the identity provider and not inherited.

ParameterTypeDescription
roleUserRole | stringThe qualified Role name, such as This.$Roles.Approver.

Returns: boolean · Availability: Everywhere

hasIdpRole(role: UserIdpRole | string): boolean

Checks whether the user has the Role from their identity provider.

ParameterTypeDescription
roleUserIdpRole | stringThe qualified Role name, such as This.$Roles.Approver.

Returns: boolean · Availability: Everywhere

hasSystemRole(roleName: SystemRoleName): boolean

Checks whether the user has a Lowgile system Role. The only system Role is 'Admin'.

ParameterTypeDescription
roleNameSystemRoleNameName of the system Role, without the System. prefix.

Returns: boolean · Availability: Everywhere

getRoleNames(filterForTenantId?: string): string[]

Returns the qualified names of the user’s effective Roles, without duplicates.

ParameterTypeDescription
filterForTenantIdstringOptional. Returns only the Roles that apply to this tenant. Default: all.

Returns: string[] · Availability: Everywhere

getRoleInheritanceSources(role: UserRole): string[]

Explains where an effective Role that is not assigned directly comes from: From identity provider or From other roles. Returns an empty list for a directly assigned Role or one the user doesn’t have.

ParameterTypeDescription
roleUserRoleThe Role.

Returns: string[] · Availability: Everywhere

hasPermission(permission: UserPermission | string): boolean

Checks whether the user has a Permission, directly or through their Roles. Same as hasEffectivePermission().

ParameterTypeDescription
permissionUserPermission | stringThe qualified Permission name, such as This.$Permissions.ApproveLargeOrders.

Returns: boolean · Availability: Everywhere

hasEffectivePermission(permission: UserPermission | string): boolean

Checks whether the user has a Permission, directly or through their Roles.

ParameterTypeDescription
permissionUserPermission | stringThe qualified Permission name, such as This.$Permissions.ApproveLargeOrders.

Returns: boolean · Availability: Everywhere

hasDirectPermission(permission: UserPermission | string): boolean

Checks whether the Permission is assigned to the user directly, not through a Role.

ParameterTypeDescription
permissionUserPermission | stringThe qualified Permission name.

Returns: boolean · Availability: Everywhere

hasSystemPermission(permissionName: SystemPermissionName): boolean

Checks whether the user has a Lowgile system Permission, such as 'SeeAllProcessTasks' or 'EditUsers'.

ParameterTypeDescription
permissionNameSystemPermissionNameName of the system Permission, without the System. prefix.

Returns: boolean · Availability: Everywhere

getPermissionNames(filterForTenantId?: string): string[]

Returns the qualified names of the user’s effective Permissions, without duplicates.

ParameterTypeDescription
filterForTenantIdstringOptional. Returns only the Permissions that apply to this tenant. Default: all.

Returns: string[] · Availability: Everywhere

isInGroup(groupName: string): boolean

Checks whether the user belongs to a group.

ParameterTypeDescription
groupNamestringName of the group.

Returns: boolean · Availability: Everywhere

isActive(): boolean

Checks whether the user’s status is 'active'.

Returns: boolean · Availability: Everywhere

canLogin(): boolean

Checks whether the user may log in: their status is 'active' or 'passwordChangeNeeded'.

Returns: boolean · Availability: Everywhere

canResetPassword(): boolean

Checks whether the user’s password may be reset: they can log in, or are 'blocked'.

Returns: boolean · Availability: Everywhere

mapToUserRecord(options?: UserRecordOptions, getManager?: (subordinate: User) => User | undefined): UserRecord

Creates a UserRecord with the data chosen in options, for example to send it to the client.

ParameterTypeDescription
optionsUserRecordOptionsOptional. Which data to include; see getAllUserRecords(). Default: none.
getManager(subordinate: User) => User | undefinedOptional. Returns a user’s manager. Needed for includeManager.

Returns: UserRecord · Availability: Everywhere

cloneWithoutPassword(): User

Returns a shallow copy of the user without password data.

Returns: User · Availability: Everywhere

deepClone(): User

Returns a copy of the user with copies of its Roles and password data.

Returns: User · Availability: Everywhere

toUserIdAndName(): any

Returns the user’s ID and full name as an object with userId and name.

Returns: UserIdAndName · Availability: Everywhere

init(): void

Sets roles and permissions to empty lists if they are not set.

Returns: void · Availability: Everywhere

A reduced, read-only view of a user, as Sys.User.currentUser returns it on the client side. It has the fields id, userName, firstName, lastName, and, depending on how it was created, email, mobilePhone, roleNames, permissionNames, groupNames and manager. On the client side, currentUser includes all of them, and roleNames and permissionNames hold the effective Roles and Permissions.

if (Sys.User.currentUser?.hasRole(This.$Roles.Approver)) {
// show the approval buttons
}

Availability: Everywhere

getName(): string

Returns the full name: first name and last name separated by a space.

Returns: string · Availability: Everywhere

hasRole(roleName: string): boolean

Checks whether roleNames contains a Role.

ParameterTypeDescription
roleNamestringThe qualified Role name, such as This.$Roles.Approver.

Returns: boolean · Availability: Everywhere

hasSystemRole(roleName: string): boolean

Checks whether the user has a Lowgile system Role, such as 'Admin'.

ParameterTypeDescription
roleNamestringName of the system Role, without the System. prefix.

Returns: boolean · Availability: Everywhere

hasPermission(permissionName: string): boolean

Checks whether permissionNames contains a Permission.

ParameterTypeDescription
permissionNamestringThe qualified Permission name, such as This.$Permissions.ApproveLargeOrders.

Returns: boolean · Availability: Everywhere

hasSystemPermission(permissionName: string): boolean

Checks whether the user has a Lowgile system Permission, such as 'SeeAllProcessTasks'.

ParameterTypeDescription
permissionNamestringName of the system Permission, without the System. prefix.

Returns: boolean · Availability: Everywhere

toUserIdAndName(): any

Returns the user’s ID and full name as an object with userId and name.

Returns: UserIdAndName · Availability: Everywhere