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
request-AdminSignupRequest
Returns
AdminSignupResponse- Created user and optional generated password
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
request-AdminSignupSocialRequest
Returns
AdminSignupSocialResponse- Created user and social account info
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
GetUsersResponse- Paginated user list
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
| Parameter | Type | Description |
|---|---|---|
sub | string | User UUID |
Returns
AuthUser| null- The user, ornullwhen 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
| Parameter | Type | Description |
|---|---|---|
params.email | string | Email address to look up |
params.requireEmailVerified | boolean | Optional. Only match accounts whose email is already verified |
Returns
AuthUser| null- The matching user, ornullwhen no account matches
Example
const user = await client.admin.getUserByEmail({ email: 'user@example.com' });
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
| Parameter | Type | Description |
|---|---|---|
sub | string | Target user UUID |
attributes | UpdateProfileRequest | Attributes to change |
Returns
AuthUser- Updated user
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
| Parameter | Type | Description |
|---|---|---|
sub | string | Target user UUID |
status.isEmailVerified | boolean | Optional. Mark the email verified or unverified |
status.isPhoneVerified | boolean | Optional. Mark the phone verified or unverified |
Returns
AuthUser- Updated user
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
| Parameter | Type | Description |
|---|---|---|
sub | string | User UUID |
Returns
DeleteUserResponse- Deletion confirmation with cascade counts
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
| Parameter | Type | Description |
|---|---|---|
sub | string | User UUID |
reason | string | Optional reason for disabling. |
Returns
DisableUserResponse- Disable confirmation with revoked session count
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
| Parameter | Type | Description |
|---|---|---|
sub | string | User UUID |
Returns
EnableUserResponse- Enable confirmation with updated user
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
| Parameter | Type | Description |
|---|---|---|
sub | string | User UUID |
Returns
| Property | Type | Description |
|---|---|---|
success | boolean | Success 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
| Parameter | Type | Description |
|---|---|---|
sub | string | Target user UUID |
newPassword | string | New password |
options.mustChangePassword | boolean | Require a change at next login. Defaults to true |
options.revokeSessions | boolean | Revoke the user's active sessions. Defaults to true |
Returns
| Property | Type | Description |
|---|---|---|
success | boolean | Success confirmation |
mustChangePassword | boolean | Whether the user must change the password next login |
sessionsRevoked | number | Number 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,
});
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
request-AdminResetPasswordRequest
Returns
AdminResetPasswordResponse- Reset confirmation with delivery details
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
| Parameter | Type | Description |
|---|---|---|
sub | string | User UUID |
Returns
GetUserSessionsResponse- User sessions
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
| Parameter | Type | Description |
|---|---|---|
sub | string | Target user UUID |
sessionId | string | Session to revoke |
Returns
| Property | Type | Description |
|---|---|---|
success | boolean | Whether the session was revoked |
wasCurrentSession | boolean | Whether that session was the caller's own |
Example
const { sessions } = await client.admin.getUserSessions(sub);
await client.admin.revokeUserSession(sub, sessions[0].sessionId);
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
| Parameter | Type | Description |
|---|---|---|
sub | string | User UUID |
forgetDevices | boolean | If true, also revokes all trusted devices. Default: false. |
Returns
| Property | Type | Description |
|---|---|---|
revokedCount | number | Number 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
| Parameter | Type | Description |
|---|---|---|
sub | string | Target 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
| Parameter | Type | Description |
|---|---|---|
sub | string | Target user UUID |
deviceId | number | Device 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
| Parameter | Type | Description |
|---|---|---|
sub | string | Target user UUID |
Returns
RevokeAllTrustedDevicesResponse-{ revokedCount: number }
Example
const { revokedCount } = await client.admin.revokeAllUserTrustedDevices(sub);
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
| Parameter | Type | Description |
|---|---|---|
sub | string | User UUID |
Returns
MFAStatus- MFA status
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
| Parameter | Type | Description |
|---|---|---|
sub | string | User UUID |
Returns
| Property | Type | Description |
|---|---|---|
devices | MFADevice[] | Array of user's MFA devices |
Each device contains:
| Property | Type | Description |
|---|---|---|
id | number | Device ID |
type | string | Device type (totp, sms, email, passkey) |
name | string | Device name |
isPreferred | boolean | Whether this is the preferred device |
isActive | boolean | Whether the device is active |
createdAt | Date | Device 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
| Parameter | Type | Description |
|---|---|---|
deviceId | number | MFA device ID |
Returns
| Property | Type | Description |
|---|---|---|
removedDeviceId | number | ID of the removed device |
removedMethod | string | Type of the removed device |
mfaDisabled | boolean | Whether 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
| Parameter | Type | Description |
|---|---|---|
sub | string | User UUID |
deviceId | number | Device ID to set as preferred |
Returns
| Property | Type | Description |
|---|---|---|
message | string | Success 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
| Parameter | Type | Description |
|---|---|---|
sub | string | User UUID |
exempt | boolean | true to exempt from MFA, false to require |
reason | string | Optional reason for exemption. |
Returns
| Property | Type | Description |
|---|---|---|
mfaExempt | boolean | Whether the user is now exempt from MFA |
mfaExemptReason | string | null | Recorded reason, or null when not exempt |
mfaExemptGrantedAt | Date | null | When 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
params-AdminAuditHistoryRequest- Audit history request params
Returns
AuditHistoryResponse- Paginated audit events
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
| Parameter | Type | Description |
|---|---|---|
params.eventType | string | Event type to filter on |
params.page | number | Optional. Page number (1-indexed) |
params.limit | number | Optional. Records per page |
params.startDate | string | Date | Optional. Window start |
params.endDate | string | Date | Optional. Window end |
Returns
AuditHistoryResponse- Paginated events
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
| Parameter | Type | Description |
|---|---|---|
params.sub | string | Optional. Restrict to one user; omit to search all |
params.limit | number | Optional. Maximum events to return |
Returns
AuditHistoryResponse- Flagged events
Example
const flagged = await client.admin.getSuspiciousActivity({ limit: 100 });
getRiskAssessmentHistory()
Fetch a user's risk assessment history.
async getRiskAssessmentHistory(params: GetRiskAssessmentHistoryRequest): Promise<AuditHistoryResponse>
Parameters
| Parameter | Type | Description |
|---|---|---|
params.sub | string | Target user UUID |
params.limit | number | Optional. Maximum results |
Returns
AuditHistoryResponse- Recorded assessments
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
| Parameter | Type | Description |
|---|---|---|
request.sub | string | Target user UUID |
request.expiresInDays | number | null | Expiry in days, or null for never (when permitted) |
request.name | string | Optional. Label |
request.allowedIps | string[] | 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
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
| Parameter | Type | Description |
|---|---|---|
sub | string | Target 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
| Parameter | Type | Description |
|---|---|---|
sub | string | Target user UUID |
keyId | string | Key to update |
updates.name | string | Optional. New label |
updates.allowedIps | string[] | 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
| Parameter | Type | Description |
|---|---|---|
sub | string | Target user UUID |
keyId | string | Key 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
| Parameter | Type | Description |
|---|---|---|
sub | string | Target user UUID |
keyId | string | Key to delete |
Returns
DeleteApiKeyResponse-{ success: boolean }
Example
await client.admin.deleteApiKey(sub, keyId);
Related APIs
- NAuthClient - Main client class
- NAuthClientConfig - Configuration options
- NAuthClientError - Error handling