[data-reveal]{opacity:1!important;transform:none!important}
AntelopeJS DMS
DocumentationUsers

Users

The `User` table and `UserModel`, password hashing and policy, `sanitizeUser`, the account mail functions, and `announceRegistration`.

Overview

The User table is the identity record the rest of this interface points at. The authentication decorators resolve a request to a user, the token generators sign for one, and Session rows reference one. The table, its constant and its model live in @antelopejs/interface-dms/auth/db. The sanitizer and the mail functions live in @antelopejs/interface-dms/auth.

typescript
import { sanitizeUser } from "@antelopejs/interface-dms/auth";
import {
  USERS_TABLE_NAME,
  User,
  UserModel,
} from "@antelopejs/interface-dms/auth/db";

The user table

User extends Table.with(HashModifier) and is registered as the users table in the DMS core schema. Its rows are shared across tenants, and you obtain its model without a tenant instance. USERS_TABLE_NAME holds the table name, "users".

FieldTypeDescription
_idstringPrimary key.
createdAtDateSet on insert by the creation-time decorator. Indexed.
updatedAtDateSet on write by the update-time decorator. Indexed.
emailstringLogin identifier. Indexed.
namestringDisplay name.
avatarImageValue | nullProfile picture as an image value ({ key, alt? }) in the default storage, downscaled in the browser to a square of at most 100 by 100 pixels.
languagestringPreferred language or locale, for example "en" or "fr". Indexed.
timeZonestring | null, optionalIANA time zone that dates and times are shown in, for example "Europe/Brussels".
weekStartUserWeekStart | null, optionalFirst day of the week in calendars and date pickers: 0 Sunday, 1 Monday, 6 Saturday.
timeFormatUserTimeFormat | null, optionalClock used for times: "h23" for a 24-hour clock, "h12" for a 12-hour clock.
dateFormatUserDateFormat | null, optionalHow full dates are written: "numeric" (01/10/2026) or "text" (1 Oct 2026).
passwordstring | nullHashed by HashModifier. Reads back as the hash, not the plaintext. null for accounts with no password.
passwordChangedAtDate | nullWhen the user last set the password, by a change or a recovery. null for an account that never changed it since the field was added.
authKeystringPer-user secret that is part of the JWT signing secret. Rotating it invalidates every token already issued to the user.
isValidatedbooleanWhether the email address has been validated. Indexed.
validationTokenstring | nullCurrent email-validation code. Indexed.
validationRequestedAtDate | nullWhen the validation code was issued, for expiry and rate limiting.
forgotPasswordTokenstring | nullCurrent password-reset code. Indexed.
forgotPasswordRequestedAtDate | nullWhen the reset code was issued, for expiry and rate limiting.
ownerbooleanPlatform owner flag. AuthOwnerOnly checks it. See Authentication.
lastActiveAtDate | nullThe last time the user made a request with a valid access token. The DMS writes it at most once a minute, so it is accurate to that interval. null until the first authenticated request.
twoFactorMethodsstring[]Second factors enabled on the account.
twoFactorSecretstring | nullActive TOTP secret.
twoFactorPendingSecretstring | nullTOTP secret that awaits confirmation during enrollment.
twoFactorTotpLastStepnumber | null, optionalThe 30-second time step of the last TOTP code accepted. A code from that step or an earlier one is refused, so each code works once. Unset until a code is accepted.
twoFactorBackupCodesstring[]Remaining single-use backup codes.
twoFactorBackupCodesGeneratedAtDate | nullWhen the current set of backup codes was generated.
twoFactorBackupCodesSavedAtDate | nullWhen the user confirmed they kept the current backup codes, by download, copy or acknowledgment. null until then.
twoFactorEmailCodestring | nullHash of the current emailed second-factor code, never the code itself. The hash is the hex SHA-256 of JSON.stringify([userId, code]).
twoFactorEmailCodeRequestedAtDate | nullWhen the emailed code was issued, for expiry and rate limiting.

UserWeekStart, UserTimeFormat and UserDateFormat are exported next to User. ImageValue comes from @antelopejs/interface-dms/types.

The indexed fields are createdAt, updatedAt, email, language, isValidated, validationToken and forgotPasswordToken. You can look a user up by these fields through getAll on the underlying table or getBy on the model. UserModel.getByEmail works this way.

Store and check a password

password carries the @Hashed decorator, and the table composes HashModifier. Assign a plaintext value on write, and the modifier hashes it on the way into the database. Read it back, and you get the hash.

typescript
import {
  normalizeEmail,
  type UserModel,
} from "@antelopejs/interface-dms/auth/db";
import randomstring from "randomstring";

const AUTH_KEY_LENGTH = 64;

export async function createUser(
  userModel: UserModel,
  name: string,
  email: string,
  password: string,
) {
  const ids = await userModel.insert({
    createdAt: new Date(),
    updatedAt: new Date(),
    name,
    email: normalizeEmail(email),
    password, // hashed by the modifier on insert
    authKey: randomstring.generate({ length: AUTH_KEY_LENGTH }),
    owner: false,
    language: "en",
  });
  return ids[0];
}

To check a candidate password, call testHashAsync on the loaded row. The mixin hashes the candidate on the thread pool, with the salt and the cost that the stored hash holds, and compares the result with the stored hash.

typescript
import { HTTPResult } from "@antelopejs/interface-api";
import type { UserModel } from "@antelopejs/interface-dms/auth/db";

const UNAUTHORIZED = 401;

export async function checkCredentials(
  userModel: UserModel,
  email: string,
  password: string,
) {
  const user = await userModel.getByEmail(email);
  if (!user || !(await user.testHashAsync("password", password))) {
    throw new HTTPResult(UNAUTHORIZED, "error.invalid_credentials");
  }
  return user;
}

A successful sign-in through /auth/login also writes the password again when isHashOutdated("password") reports an older hash on the row.

Emails are stored trimmed and lowercased. getByEmail normalizes its argument itself. Before you write an email, normalize it with normalizeEmail, exported next to UserModel.

Query users with UserModel

UserModel extends BasicDataModel(User, USERS_TABLE_NAME). It has the standard get, getBy, getAll, insert, update and delete operations, plus three lookups of its own.

MethodSignatureDescription
getByEmail(email: string) => Promise<User | undefined>The user with this email, or undefined. The email is trimmed and lowercased, then looked up through the email index.
getOwners() => Promise<User[]>Every user with owner === true.
countOwnersExcluding(excludedIds: string[]) => Promise<number>How many owners remain once the given user ids are set aside. Pass an empty array to count all owners.

countOwnersExcluding serves the last-owner check. Before you remove the owner flag from a set of users, count who would remain, and refuse the operation if the answer is zero.

typescript
import { HTTPResult } from "@antelopejs/interface-api";
import type { UserModel } from "@antelopejs/interface-dms/auth/db";

const CONFLICT = 409;

export async function demoteOwners(userModel: UserModel, userIds: string[]) {
  const remaining = await userModel.countOwnersExcluding(userIds);
  if (remaining === 0) {
    throw new HTTPResult(CONFLICT, "error.last_owner");
  }

  for (const id of userIds) {
    await userModel.update(id, { owner: false });
  }
}

Invalidate every token for a user

authKey is part of the signing secret of every token issued for the user. Replacing it makes all outstanding access, refresh, two-factor and tenant-assignment tokens fail validation at once. Combine it with SessionModel.deleteByUserId from Tokens and sessions to sign a user out everywhere.

typescript
import type {
  SessionModel,
  User,
  UserModel,
} from "@antelopejs/interface-dms/auth/db";
import randomstring from "randomstring";

const AUTH_KEY_LENGTH = 64;

export async function signOutEverywhere(
  userModel: UserModel,
  sessionModel: SessionModel,
  user: User,
) {
  await sessionModel.deleteByUserId(user._id);
  user.authKey = randomstring.generate({ length: AUTH_KEY_LENGTH });
  await userModel.update(user);
}

userModel.update(user) takes the primary key from the object. The two-argument form update(id, partial) updates a subset of fields.

Strip secrets before responding

A User loaded from the database carries authentication secrets. sanitizeUser returns a copy without them. Return that copy over HTTP.

typescript
sanitizeUser(user: User): Promise<Partial<User>>

It removes these fields:

  • authKey;
  • validationToken and validationRequestedAt;
  • forgotPasswordToken and forgotPasswordRequestedAt;
  • twoFactorSecret, twoFactorPendingSecret, twoFactorTotpLastStep and twoFactorBackupCodes;
  • twoFactorEmailCode and twoFactorEmailCodeRequestedAt.

It also removes the keys the deployment lists in the userSensitiveKeys setting of its authentication configuration. A dotted key such as profile.secret removes a nested property. Because the removed set is configurable, the return type is Partial<User>. Treat every field as possibly absent.

typescript
import { Controller, Get } from "@antelopejs/interface-api";
import {
  AuthRawUser,
  sanitizeUser,
} from "@antelopejs/interface-dms/auth";
import type { User } from "@antelopejs/interface-dms/auth/db";

export class MeController extends Controller("/api/me") {
  @Get("")
  me(@AuthRawUser() user: User): Promise<Partial<User>> {
    return sanitizeUser(user);
  }
}

Send account emails

Four functions send the account emails the authentication flows depend on. Each returns a promise that resolves once the mail provider accepts the message, and rejects when the provider reports a failure. Decide at each call site whether to await it or send it in the background.

FunctionSignatureSends
send2FAEmail(user: User, code: string) => Promise<void>The emailed second-factor code, to user.email.
sendEmailValidationEmail(user: User) => Promise<void>The email-validation message, with the validationToken currently stored on the user.
sendEmailForgotEmail(user: User) => Promise<void>The password-reset message, with the forgotPasswordToken currently stored on the user.
sendAdminInviteEmail(email: string, token: string, inviteeName?: string, context?: AdminInviteEmailContext) => Promise<void>An invite with a signup link built from token, to an address that has no user row yet. inviteeName addresses the invitee by name when the invite carried one.

AdminInviteEmailContext has three optional fields. Without them, the invite email keeps its generic wording.

FieldTypeDescription
workspaceNamestringThe workspace the invitee joins.
inviterNamestringWho sent the invitation.
languagestringThe invitee's language (en, fr, and others). English when the language is not supported.

sendEmailValidationEmail and sendEmailForgotEmail read the code from the user. Generate the code, persist it, and only then send.

typescript
import { sendEmailForgotEmail } from "@antelopejs/interface-dms/auth";
import type { UserModel } from "@antelopejs/interface-dms/auth/db";
import randomstring from "randomstring";

const RESET_CODE_LENGTH = 6;

export async function requestPasswordReset(
  userModel: UserModel,
  email: string,
) {
  const user = await userModel.getByEmail(email);
  if (!user) return; // answer identically whether or not the address exists

  user.forgotPasswordToken = randomstring.generate({
    length: RESET_CODE_LENGTH,
    capitalization: "uppercase",
  });
  user.forgotPasswordRequestedAt = new Date();
  await userModel.update(user);

  await sendEmailForgotEmail(user);
}

sendAdminInviteEmail takes a bare address and a token instead of a User, because an invitee has no user row until they sign up. The invite record, its token and its expiry belong to the Core domain, whose inviteUserToTenant sends this email for you.

Password policy

@antelopejs/interface-dms/auth/password exports the policy every DMS flow applies when a password is set. A password needs at least PASSWORD_MIN_LENGTH (8) characters, with at least one uppercase letter, one digit, and one of @$!%*?&. It may contain only ASCII letters, digits and those special characters. PASSWORD_PATTERN holds the character rules without the length.

typescript
isPasswordCompliant(password: string): boolean

isPasswordCompliant is a pure function, not an interface call, so it works without the DMS loaded. Call it from any flow you own that stores a password, such as a public signup, before you hash the password. Your module then accepts exactly the passwords the DMS accepts.

Announce a registration

announceRegistration runs what must happen once an account has joined a tenant. It sends the welcome notification and the collaborator notification to the platform owners, then fires the USER_REGISTERED hook with tenantId, userId, email and name.

typescript
announceRegistration(
  userModel: UserModel,
  user: User,
  tenantId: string,
): Promise<void>

Call it from any registration flow you own: a module with its own signup, or a SaaS transactional flow once provisioning has committed. The DMS password signup and a provider login that consumes an invitation both go through it. Notifications and automations therefore run the same way, whichever flow created the account.

The hook only observes. Registration is already complete when it runs, so a failing subscriber is logged and does not fail the request. Failing the request would leave a user whose account exists but whose retry token is gone. The notifications are sent in the background, and a failure there is logged, not propagated.

Next steps

External identities covers binding a user to the accounts they own on a login provider.