Skip to main content

AdminOperations

Package: @nauth-toolkit/client Type: Class

Admin operations service for user and system management. Provides admin-level operations including user CRUD, password management, session control, MFA management, and audit history.

import { AdminOperations } from '@nauth-toolkit/client';

Access​

Admin operations are accessed via the admin property on NAuthClient:

const client = new NAuthClient({
baseUrl: 'https://api.example.com/auth',
tokenDelivery: 'cookies',
admin: {
pathPrefix: '/admin',
},
});

// Access admin operations
const users = await client.admin.getUsers({ page: 1 });

User Management​

createUser()​

Create a new user (admin operation). Allows creating users with pre-verified email/phone, auto-generated passwords, and force password change flag.

async createUser(request: AdminSignupRequest): Promise<AdminSignupResponse>

Parameters

Returns

Example

const result = await client.admin.createUser({
email: 'user@example.com',
password: 'SecurePass123!',
isEmailVerified: true,
});

// With auto-generated password
const result = await client.admin.createUser({
email: 'user@example.com',
generatePassword: true,
mustChangePassword: true,
});
console.log('Generated password:', result.generatedPassword);

importSocialUser()​

Import social user (admin operation). Imports existing social users from external platforms (e.g., Cognito, Auth0) with social account linkage.

async importSocialUser(request: AdminSignupSocialRequest): Promise<AdminSignupSocialResponse>

Parameters

Returns

Example

const result = await client.admin.importSocialUser({
email: 'user@example.com',
provider: 'google',
providerId: 'google_12345',
providerEmail: 'user@gmail.com',
});

getUsers()​

Get users with filters and pagination.

async getUsers(params?: GetUsersRequest): Promise<GetUsersResponse>

Parameters

  • params - GetUsersRequest - Filter and pagination params. Optional, defaults to {}.

Returns

Example

const result = await client.admin.getUsers({
page: 1,
limit: 20,
isEmailVerified: true,
mfaEnabled: false,
sortBy: 'createdAt',
sortOrder: 'DESC',
});

getUser()​

Get user by sub (UUID).

async getUser(sub: string): Promise<AuthUser | null>

Parameters

ParameterTypeDescription
substringUser UUID

Returns

  • AuthUser | null - The user, or null when no account has that sub

Example

const user = await client.admin.getUser('a21b654c-2746-4168-acee-c175083a65cd');

getUserByEmail()​

Resolve a user by email address.

async getUserByEmail(params: GetUserByEmailRequest): Promise<AuthUser | null>

Parameters

ParameterTypeDescription
params.emailstringEmail address to look up
params.requireEmailVerifiedbooleanOptional. Only match accounts whose email is already verified

Returns

  • AuthUser | null - The matching user, or null when no account matches

Example

const user = await client.admin.getUserByEmail({ email: 'user@example.com' });
note

An account's email can change, and without requireEmailVerified an unverified address matches too. Prefer sub wherever you already hold one.


updateUser()​

Update a user's profile attributes. Omitted fields are left unchanged.

async updateUser(sub: string, attributes: UpdateProfileRequest): Promise<AuthUser>

Parameters

ParameterTypeDescription
substringTarget user UUID
attributesUpdateProfileRequestAttributes to change

Returns

Example

const user = await client.admin.updateUser(sub, { firstName: 'Ada', lastName: 'Lovelace' });

updateVerifiedStatus()​

Set a user's email/phone verified flags directly, without the user completing a verification challenge.

async updateVerifiedStatus(sub: string, status: UpdateVerifiedStatusRequest): Promise<AuthUser>

Parameters

ParameterTypeDescription
substringTarget user UUID
status.isEmailVerifiedbooleanOptional. Mark the email verified or unverified
status.isPhoneVerifiedbooleanOptional. Mark the phone verified or unverified

Returns

Example

// Migrating accounts whose email a previous system already verified
await client.admin.updateVerifiedStatus(sub, { isEmailVerified: true });

deleteUser()​

Delete user with cascade cleanup.

async deleteUser(sub: string): Promise<DeleteUserResponse>

Parameters

ParameterTypeDescription
substringUser UUID

Returns

Example

const result = await client.admin.deleteUser('user-uuid');
console.log('Deleted records:', result.deletedRecords);

disableUser()​

Disable user account (permanent lock).

async disableUser(sub: string, reason?: string): Promise<DisableUserResponse>

Parameters

ParameterTypeDescription
substringUser UUID
reasonstringOptional reason for disabling.

Returns

Example

const result = await client.admin.disableUser('user-uuid', 'Account compromised');
console.log('Revoked sessions:', result.revokedSessions);

enableUser()​

Enable (unlock) user account.

async enableUser(sub: string): Promise<EnableUserResponse>

Parameters

ParameterTypeDescription
substringUser UUID

Returns

Example

const result = await client.admin.enableUser('user-uuid');
console.log('User enabled:', result.user);

Password Management​

forcePasswordChange()​

Force password change on next login.

async forcePasswordChange(sub: string): Promise<{ success: boolean }>

Parameters

ParameterTypeDescription
substringUser UUID

Returns

PropertyTypeDescription
successbooleanSuccess confirmation

Example

await client.admin.forcePasswordChange('user-uuid');

setPassword()​

Set a user's password outright, without their involvement.

async setPassword(
sub: string,
newPassword: string,
options?: AdminSetPasswordOptions
): Promise<AdminSetPasswordResponse>

Parameters

ParameterTypeDescription
substringTarget user UUID
newPasswordstringNew password
options.mustChangePasswordbooleanRequire a change at next login. Defaults to true
options.revokeSessionsbooleanRevoke the user's active sessions. Defaults to true

Returns

PropertyTypeDescription
successbooleanSuccess confirmation
mustChangePasswordbooleanWhether the user must change the password next login
sessionsRevokednumberNumber of sessions revoked

Example

// Temporary password, all sessions revoked
await client.admin.setPassword('a21b654c-2746-4168-acee-c175083a65cd', 'NewSecurePass123!');

// Permanent password, sessions left alone
await client.admin.setPassword('a21b654c-2746-4168-acee-c175083a65cd', 'NewSecurePass123!', {
mustChangePassword: false,
revokeSessions: false,
});
note

Both options default to true, so the two-argument call already issues a temporary password and signs the user out everywhere — no follow-up forcePasswordChange() call is needed.


initiatePasswordReset()​

Initiate password reset workflow (sends code/link to user).

async initiatePasswordReset(request: AdminResetPasswordRequest): Promise<AdminResetPasswordResponse>

Parameters

Returns

Example

const result = await client.admin.initiatePasswordReset({
sub: 'user-uuid',
deliveryMethod: 'email',
baseUrl: 'https://myapp.com/reset-password',
reason: 'User requested password reset',
});
console.log('Code sent to:', result.destination);

Session Management​

getUserSessions()​

Get all sessions for a user.

async getUserSessions(sub: string): Promise<GetUserSessionsResponse>

Parameters

ParameterTypeDescription
substringUser UUID

Returns

Example

const result = await client.admin.getUserSessions('user-uuid');
console.log('Active sessions:', result.sessions);

revokeUserSession()​

Revoke one specific session of a user, leaving their other sessions alone.

async revokeUserSession(sub: string, sessionId: string): Promise<LogoutSessionResponse>

Parameters

ParameterTypeDescription
substringTarget user UUID
sessionIdstringSession to revoke

Returns

PropertyTypeDescription
successbooleanWhether the session was revoked
wasCurrentSessionbooleanWhether that session was the caller's own

Example

const { sessions } = await client.admin.getUserSessions(sub);
await client.admin.revokeUserSession(sub, sessions[0].sessionId);
note

To end every session at once use logoutAllSessions().


logoutAllSessions()​

Logout all sessions for a user (admin-initiated).

async logoutAllSessions(sub: string, forgetDevices?: boolean): Promise<{ revokedCount: number }>

Parameters

ParameterTypeDescription
substringUser UUID
forgetDevicesbooleanIf true, also revokes all trusted devices. Default: false.

Returns

PropertyTypeDescription
revokedCountnumberNumber of sessions revoked

Example

const result = await client.admin.logoutAllSessions('user-uuid', true);
console.log(`Revoked ${result.revokedCount} sessions`);

Trusted Device Management​

Trusted devices are the devices allowed to skip MFA for a user. For the caller's own devices use client.listTrustedDevices().

getUserTrustedDevices()​

List a user's trusted devices. Expired devices are filtered out server-side.

async getUserTrustedDevices(sub: string): Promise<ListTrustedDevicesResponse>

Parameters

ParameterTypeDescription
substringTarget user UUID

Returns

  • ListTrustedDevicesResponse - { trustedDevices: TrustedDeviceInfo[] }

Example

const { trustedDevices } = await client.admin.getUserTrustedDevices(sub);

revokeUserTrustedDevice()​

Revoke one of a user's trusted devices, leaving their others alone.

async revokeUserTrustedDevice(sub: string, deviceId: number): Promise<RevokeTrustedDeviceResponse>

Parameters

ParameterTypeDescription
substringTarget user UUID
deviceIdnumberDevice record id, from getUserTrustedDevices()

Returns

  • RevokeTrustedDeviceResponse - { success: boolean }

Example

await client.admin.revokeUserTrustedDevice(sub, 7);

revokeAllUserTrustedDevices()​

Revoke every trusted device belonging to a user.

async revokeAllUserTrustedDevices(sub: string): Promise<RevokeAllTrustedDevicesResponse>

Parameters

ParameterTypeDescription
substringTarget user UUID

Returns

  • RevokeAllTrustedDevicesResponse - { revokedCount: number }

Example

const { revokedCount } = await client.admin.revokeAllUserTrustedDevices(sub);
note

This removes MFA bypass only; it does not sign the user out. Use logoutAllSessions() for that.


MFA Management​

getMfaStatus()​

Get MFA status for a user.

async getMfaStatus(sub: string): Promise<MFAStatus>

Parameters

ParameterTypeDescription
substringUser UUID

Returns

Example

const status = await client.admin.getMfaStatus('user-uuid');
console.log('MFA enabled:', status.enabled);

getMfaDevices()​

Get all MFA devices for a user.

async getMfaDevices(sub: string): Promise<GetMFADevicesResponse>

Parameters

ParameterTypeDescription
substringUser UUID

Returns

PropertyTypeDescription
devicesMFADevice[]Array of user's MFA devices

Each device contains:

PropertyTypeDescription
idnumberDevice ID
typestringDevice type (totp, sms, email, passkey)
namestringDevice name
isPreferredbooleanWhether this is the preferred device
isActivebooleanWhether the device is active
createdAtDateDevice creation timestamp

Example

const result = await client.admin.getMfaDevices('user-uuid');
console.log('Devices:', result.devices);
// [{ id: 1, name: 'Google Authenticator', type: 'totp', isPreferred: true, ... }]

removeMfaDeviceById()​

Remove a single MFA device by device ID.

async removeMfaDeviceById(deviceId: number): Promise<RemoveMFADeviceResponse>

Parameters

ParameterTypeDescription
deviceIdnumberMFA device ID

Returns

PropertyTypeDescription
removedDeviceIdnumberID of the removed device
removedMethodstringType of the removed device
mfaDisabledbooleanWhether MFA was disabled (last device)

Example

const result = await client.admin.removeMfaDeviceById(123);
console.log('Removed:', result.removedDeviceId);

setPreferredMfaDevice()​

Set a specific device as the user's preferred MFA device.

async setPreferredMfaDevice(
sub: string,
deviceId: number
): Promise<{ message: string }>

Parameters

ParameterTypeDescription
substringUser UUID
deviceIdnumberDevice ID to set as preferred

Returns

PropertyTypeDescription
messagestringSuccess message

Example

// First get devices to find the ID
const devices = await client.admin.getMfaDevices('user-uuid');
const totpDevice = devices.devices.find(d => d.type === 'totp');

// Set as preferred
await client.admin.setPreferredMfaDevice('user-uuid', totpDevice.id);

setMfaExemption()​

Grant or revoke MFA exemption for a user.

async setMfaExemption(
sub: string,
exempt: boolean,
reason?: string
): Promise<SetMfaExemptionResponse>

Parameters

ParameterTypeDescription
substringUser UUID
exemptbooleantrue to exempt from MFA, false to require
reasonstringOptional reason for exemption.

Returns

PropertyTypeDescription
mfaExemptbooleanWhether the user is now exempt from MFA
mfaExemptReasonstring | nullRecorded reason, or null when not exempt
mfaExemptGrantedAtDate | nullWhen the exemption was granted, or null

Example

await client.admin.setMfaExemption('user-uuid', true, 'Service account');

Audit​

getAuditHistory()​

Get audit history for a user.

async getAuditHistory(params: AdminAuditHistoryRequest): Promise<AuditHistoryResponse>

Parameters

Returns

Example

const history = await client.admin.getAuditHistory({
sub: 'user-uuid',
page: 1,
limit: 50,
eventType: 'LOGIN_SUCCESS',
});

getEventsByType()​

Fetch audit events of a single type, across all users.

async getEventsByType(params: GetEventsByTypeRequest): Promise<AuditHistoryResponse>

Parameters

ParameterTypeDescription
params.eventTypestringEvent type to filter on
params.pagenumberOptional. Page number (1-indexed)
params.limitnumberOptional. Records per page
params.startDatestring | DateOptional. Window start
params.endDatestring | DateOptional. Window end

Returns

Example

const failures = await client.admin.getEventsByType({ eventType: 'LOGIN_FAILED', limit: 50 });

getSuspiciousActivity()​

Fetch events the risk engine flagged as suspicious.

async getSuspiciousActivity(params?: GetSuspiciousActivityRequest): Promise<AuditHistoryResponse>

Parameters

ParameterTypeDescription
params.substringOptional. Restrict to one user; omit to search all
params.limitnumberOptional. Maximum events to return

Returns

Example

const flagged = await client.admin.getSuspiciousActivity({ limit: 100 });

getRiskAssessmentHistory()​

Fetch a user's risk assessment history.

async getRiskAssessmentHistory(params: GetRiskAssessmentHistoryRequest): Promise<AuditHistoryResponse>

Parameters

ParameterTypeDescription
params.substringTarget user UUID
params.limitnumberOptional. Maximum results

Returns

Example

const history = await client.admin.getRiskAssessmentHistory({ sub, limit: 20 });

API Key Management​

Administrative key operations act on a target user identified by sub. For the caller's own keys use client.apiKeys.

createApiKey()​

Create an API key on behalf of a user. Bypasses the server's allowUserCreation setting, but still enforces per-user limits, expiry rules, and IP restrictions.

async createApiKey(request: AdminCreateApiKeyRequest): Promise<CreateApiKeyResult>

Parameters

ParameterTypeDescription
request.substringTarget user UUID
request.expiresInDaysnumber | nullExpiry in days, or null for never (when permitted)
request.namestringOptional. Label
request.allowedIpsstring[]Optional. IP / CIDR allowlist

Returns

  • CreateApiKeyResult - { key: string; apiKey: ApiKeyInfo }

Example

const { key } = await client.admin.createApiKey({ sub, expiresInDays: 90 });
// `key` is plaintext and shown only once
warning

The plaintext key is returned exactly once. The server stores only a hash, so a key not captured here cannot be recovered.


listApiKeys()​

List a user's API keys.

async listApiKeys(sub: string): Promise<ListApiKeysResponse>

Parameters

ParameterTypeDescription
substringTarget user UUID

Returns

  • ListApiKeysResponse - { apiKeys: ApiKeyInfo[] }, never containing plaintext

Example

const { apiKeys } = await client.admin.listApiKeys(sub);

updateApiKey()​

Update the label and/or IP allowlist of a user's key. The secret and expiry are immutable.

async updateApiKey(sub: string, keyId: string, updates: UpdateApiKeyRequest): Promise<ApiKeyInfo>

Parameters

ParameterTypeDescription
substringTarget user UUID
keyIdstringKey to update
updates.namestringOptional. New label
updates.allowedIpsstring[]Optional. Replacement allowlist (empty clears)

Returns

  • ApiKeyInfo - Updated key metadata

Example

await client.admin.updateApiKey(sub, keyId, { allowedIps: ['203.0.113.5'] });

revokeApiKey()​

Revoke a user's key, leaving it in place but unusable.

async revokeApiKey(sub: string, keyId: string): Promise<RevokeApiKeyResponse>

Parameters

ParameterTypeDescription
substringTarget user UUID
keyIdstringKey to revoke

Returns

  • RevokeApiKeyResponse - { success: boolean }

Example

await client.admin.revokeApiKey(sub, keyId);

deleteApiKey()​

Permanently delete a user's key.

async deleteApiKey(sub: string, keyId: string): Promise<DeleteApiKeyResponse>

Parameters

ParameterTypeDescription
substringTarget user UUID
keyIdstringKey to delete

Returns

  • DeleteApiKeyResponse - { success: boolean }

Example

await client.admin.deleteApiKey(sub, keyId);