Skip to content

Account management

Account management flows often need mailbox verification too. A common example is changing the email address on an existing account: create a challenge for the new mailbox, verify the code, then update the account.

import { Passlock, isChallengeRateLimitedError } from "@passlock/server";
// get these from your development tenancy settings
const tenancyId = "myTenancyId";
const apiKey = "myApiKey";
const passlock = new Passlock({ tenancyId, apiKey });
const user = await requireSignedInUser();
const newEmail = "new-address@example.com";
const result = await passlock.createMailboxChallenge({
email: newEmail,
purpose: "email-change",
userId: String(user.id),
invalidateOthers: true,
});
if (result.success) {
// message contains rendered HTML and plain-text email content.
// result.value.challenge.code is also available if you prefer to render your own email.
const { challengeId, secret, message, email } = result.value.challenge;
// save this in the user's session or a secure HTTP only cookie
await savePendingEmailChange({
challengeId,
secret,
userId: user.id,
email,
});
await sendCodeEmail({ email, message });
} else if (isChallengeRateLimitedError(result.error)) {
return showRateLimit(result.error.retryAfterSeconds);
} else {
throw new Error(result.error.message);
}
Choose your code style

Verify the new mailbox and update the account

Section titled “Verify the new mailbox and update the account”
import { Passlock } from "@passlock/server";
const passlock = new Passlock({ tenancyId: "myTenancyId", apiKey: "myApiKey" });
const user = await requireSignedInUser();
// fetch from the user's session or secure cookie
const pending = await loadPendingEmailChange(user.id);
const result = await passlock.verifyMailboxChallenge({
challengeId: pending.challengeId,
secret: pending.secret,
code: form.code,
});
if (result.success) {
const { challenge } = result.value;
if (challenge.purpose !== "email-change") {
throw new Error("Unexpected challenge purpose");
}
if (challenge.userId !== String(user.id)) {
throw new Error("Unexpected user");
}
await updateUserEmail(user.id, challenge.email);
await clearPendingEmailChange(user.id);
await sendEmailChangeNotice(user.email);
} else {
return showVerificationError(result.error);
}
Choose your code style

The same endpoints are available over raw HTTP if you are not using @passlock/server. See the REST API mailbox challenge reference.