Docs
Contents

User Management

Overview and use cases

Full lifecycle management of users in a project (administrator view): create / query / update / disable / delete users, manage login identities, sessions, MFA factors, push targets and labels, and issue short-lived tokens for Custom Token login. Use cases: backend account operations, automated onboarding, Custom Token issuance, session governance.

Prerequisites

Usage workflow

  1. Create user: users.create({ userId, email, phone, password, name }) (email, phone, password, name all optional) (password at least 8 characters; ID.unique() or a custom ID); for migrating accounts with pre-hashed passwords use createArgon2User / createBcryptUser / createMD5User / createPHPassUser.

  2. Query: users.list({ queries, search, total }) (queries, search, total all optional) (supports keyword search and pagination); users.get(userId) for a single lookup.

  3. Update: updateEmail / updatePassword / updatePhone / updateName / updatePrefs; status and verification: updateStatus (disable / enable), updateEmailVerification / updatePhoneVerification.

  4. Identities and labels: listIdentities to view bound OAuth / external identities, deleteIdentity to unlink; labels are used for label-based role authorization (Role.label) and are maintained via the management plane.

  5. Session governance: listSessions / createSession / deleteSession / deleteSessions. For sessions created server-side, the secret is not in the response body and only lands in the a_session_<projectId> Cookie; when a user-state client is needed, read that Cookie and then Client().setSession(secret).

  6. Custom Token issuance: after the business backend completes external identity verification, call users.createToken({ userId }) and hand the one-time secret to the frontend account.createSession({ userId, secret }) to exchange for a full Session (see the flow in authentication.md).

  7. User JWT: users.createJWT issues short-lived JWTs for users (server-side orchestration scenarios).

  8. MFA management: listMfaFactors / deleteMfaAuthenticator / createMfaRecoveryCodes / getMfaRecoveryCodes / updateMfaRecoveryCodes — administrators reset authenticators / recovery codes on behalf of users.

  9. Push targets: createTarget / listTargets / getTarget / updateTarget / deleteTarget (used with Messaging's user-targeted delivery).

  10. Audit: listLogs for user-level operation logs; listMemberships for the teams this user has joined.

Key parameters and returns

CallKey parametersReturns
createuserId, email (optional), phone (optional), password (optional), name (optional)Models.User ($id, email, labels, status…)
listqueries (optional; Query.limit/offset/orderDesc etc.), search (optional), total (optional)UserList (users + total)
createTokenuserIdToken (one-time secret, short-lived)
createSessionuserIdSession (secret only in the Cookie)
createJWTuserId{ jwt }
updatePrefsuserId, prefs objectUser

On the Java side, typed models are returned synchronously; in-row business data defaults to Map<String,Object>, and Type can be passed to deserialize into POJOs; on the Python side, the methods are snake_case isomorphs.

Errors and boundaries

SDK Category Differences

Examples by language

The following provides examples by language, item by item along the usage workflow; each card can switch languages (synced across the page).

Create and query

This page has no Web / Console tabs: Client SDK has no user management capabilities (cannot list users / modify others); account self-service operations are covered in profile.md; Console SDK likewise does not handle project user management. This card covers both creation (including pre-hashed password migration import) and querying.

import { Client, Users, ID, Query } from 'agentbase-node-sdk';

const client = new Client()
    .setEndpoint(process.env.APPBASE_ENDPOINT!)   // Must include /v1
    .setProject(process.env.APPBASE_PROJECT_ID!)
    .setKey(process.env.APPBASE_API_KEY!);        // users.read / users.write minimum scope
const users = new Users(client);

const user = await users.create({
    userId: ID.unique(),           // or custom ID; duplicate email/phone/userId returns 409
    email: 'user@example.com',
    password: '<password>',        // Plaintext, at least 8 characters; hashed server-side
    name: 'Example User',
});
const page = await users.list({ queries: [Query.limit(25)], search: 'user@example.com' });
const one = await users.get('<userId>');
// Pre-hashed password migration import: createArgon2User / createBcryptUser / createMD5User / createPHPassUser (pass the source system's hash string, the server does not re-hash)

Update, ban and delete

updateStatus bans (false) take effect immediately; updatePrefs merges and writes preferences; updateEmail does not automatically rewrite the email verification state. Deleting a user is irreversible: it cascades to delete all of their Sessions, OAuth identities, message targets and team memberships, and the ID can be reused after deletion.

await users.updateEmail({ userId: '<userId>', email: 'new@example.com' });
await users.updateStatus({ userId: '<userId>', status: false });   // Block; true re-enables
await users.updatePrefs({ userId: '<userId>', prefs: { theme: 'dark' } });
await users.delete({ userId: '<userId>' });   // Irreversible; cascades to delete Sessions, identities, targets, and team memberships

Custom Token and JWT issuance

createToken issues a one-time, short-lived secret for users (by default 6 characters and 900 seconds, in OTP form); the frontend exchanges it via account.createSession({ userId, secret }) for a full Session; createJWT issues short-lived JWTs for existing Sessions (default 900 seconds, maximum 3600).

const token = await users.createToken({ userId: '<userId>' });   // { secret, expire }; secret appears only once, delivered via a controlled channel
const jwt = await users.createJWT({ userId: '<userId>' });       // { jwt }; issued for an existing Session

Identities and labels

listIdentities is a project-level identity view (for investigating the same third-party account bound by multiple users); after deleteIdentity unlinks an identity, that user can no longer log in with the corresponding third-party account; labels are the basis for label:<name> permission decisions, and updates follow whole-replacement semantics (labels not listed are removed).

const identities = await users.listIdentities({ queries: [Query.limit(25)] });   // Project-level OAuth / external identity view
await users.deleteIdentity({ identityId: '<identityId>' });      // Unlink third-party login
await users.updateLabels('<userId>', ['admin', 'premium']);      // Full replacement; tags not listed are removed

Session governance

For sessions created server-side, the secret is not in the response body and only lands in the a_session_<projectId> Cookie; when a user-state client is needed, read that Cookie and then load the Session.

const sessions = await users.listSessions({ userId: '<userId>' });   // Multi-device login view, useful for auditing abnormal logins
const created = await users.createSession({ userId: '<userId>' });   // Server-side login (no password verification); secret is only in the Cookie
await users.deleteSession({ userId: '<userId>', sessionId: '<sessionId>' });   // Sign out a single device (e.g., lost device)
await users.deleteSessions({ userId: '<userId>' });                  // Force sign-out across all clients, often combined with a password reset

MFA management

Administrators reset authenticators and recovery codes on behalf of users: after deleting a TOTP authenticator, the user must re-bind or switch to another factor; recovery codes are generated on first use (409 is returned if they already exist), and regeneration wholly overwrites the old codes.

const factors = await users.listMfaFactors({ userId: '<userId>' });        // totp / phone / email / recoveryCode
await users.deleteMfaAuthenticator({ userId: '<userId>', type: 'totp' });  // Delete a TOTP authenticator
const codes = await users.createMfaRecoveryCodes({ userId: '<userId>' });  // First-time generation; returns 409 if it already exists
const current = await users.getMfaRecoveryCodes({ userId: '<userId>' });   // Read the currently valid recovery codes
await users.updateMfaRecoveryCodes({ userId: '<userId>' });                // Regenerates and fully overwrites the old code

Push Targets

Message targets (providerType: email email / sms E.164 phone number / push push token) are delivery endpoints referenced by Messaging for targeted delivery; a user can have multiple targets.

const target = await users.createTarget({
    userId: '<userId>',
    targetId: ID.unique(),
    providerType: 'email',            // email / sms / push
    identifier: 'user@example.com',   // Email / E.164 phone number / push token
    providerId: 'sendgrid',           // Optional; if not passed, the first provider of the same type is used
    name: 'Ada 主邮箱',
});
const targets = await users.listTargets({ userId: '<userId>' });
const one = await users.getTarget({ userId: '<userId>', targetId: '<targetId>' });
await users.updateTarget({ userId: '<userId>', targetId: '<targetId>', name: 'Ada 备用邮箱' });
await users.deleteTarget({ userId: '<userId>', targetId: '<targetId>' });

Audit and memberships

User-level operation logs (login, authentication changes and other events) are used for security auditing; memberships are a read-only view of that user's presence across all teams; for the same data on the team side, see teams.mdx.

const logs = await users.listLogs({ userId: '<userId>' });                  // Activity logs such as logins and auth changes
const memberships = await users.listMemberships({ userId: '<userId>' });    // Memberships across all teams

Example Guide