Iris UI Integration
Run the Iris UI sign-in, sign-up, account and organization blocks on an Entro Auth client.
Iris UI is a component registry: you copy its blocks into your app. Its auth blocks take async handlers and know nothing about the backend. @entro314labs/entro-auth-iris is the other half, the handlers that call an Entro Auth client.
| Block | Handlers | What it covers |
|---|---|---|
SignIn | signInHandlers | Emailed code, password (by email or username), sign-in link, passkey, single sign-on, the two-factor step |
LoginCentered | signInHandlers | A full-page login: passkey first, emailed code for sign in and sign up, single sign-on |
SignupForm | signUpHandlers | Create an account, confirm its address by link or code, single sign-on, a passkey in place of a password |
ResetPassword | resetPasswordHandlers | The page a reset email opens |
AccountProfile | loadAccountProfile, accountProfileHandlers | Photo, name, address and its change |
AccountSecurity | loadAccountSecurity, accountSecurityHandlers | Password, two-factor, passkeys, sessions, connected accounts, deleting the account |
OrganizationMembers | loadOrganizationMembers, organizationMembersHandlers | Members, roles, invitations |
OrganizationSwitcher | loadOrganizations, organizationSwitcherHandlers | The active organization, and switching it |
Installation
Add the blocks with the shadcn CLI, and the handlers from npm:
npx shadcn@latest add https://irisui.dev/r/sign-in.json https://irisui.dev/r/login-centered.json https://irisui.dev/r/signup-form.json https://irisui.dev/r/reset-password.json https://irisui.dev/r/account-profile.json https://irisui.dev/r/account-security.json https://irisui.dev/r/organization-members.json https://irisui.dev/r/organization-switcher.jsonnpm install @entro314labs/entro-auth-irisSign in
Name the methods your server has set up. The block offers those and no others.
"use client";
import { signInHandlers } from "@entro314labs/entro-auth-iris";
import { SignIn } from "@/components/iris/blocks/sign-in/sign-in";
import { authClient } from "@/lib/auth-client";
const handlers = signInHandlers(authClient, {
methods: ["password", "email-code", "social"],
resetPasswordURL: "/reset-password",
callbackURL: "/dashboard",
errorCallbackURL: "/sign-in",
});
export default function SignInPage() {
return (
<SignIn
{...handlers}
providers={["Google", "Facebook"]}
labels={{ title: "Sign in to Acme", member: "Acme member" }}
onSignIn={() => location.assign("/dashboard")}
/>
);
}Each method needs its server plugin and its client plugin:
| Method | Server | Client |
|---|---|---|
email-code | emailOTP | emailOTPClient |
password | emailAndPassword: { enabled: true } | none |
password, by username | username | usernameClient, and username on the block |
magic-link | magicLink | magicLinkClient |
passkey | passkey | passkeyClient |
social | socialProviders | none; pass the block the same providers |
The blocks show the server's own message for a refused sign in, such as a wrong password, not one of their labels. To translate what people read, translate both: the labels, and the server's messages with the i18n plugin.
SignIn and SignupForm are cards with a title of their own. Put them on a page; inside Iris DialogContent, which has a title and a frame as well, they read as a card in a card.
The methods have to be named. An auth client answers for any plugin, installed or not, so the handlers cannot ask it which ones you use.
A full-page login
LoginCentered is the same sign in as a whole page, passkey first. It takes the same handlers for the methods it has, passkey, email-code and social:
<LoginCentered
fullScreen
{...signInHandlers(authClient, { methods: ["passkey", "email-code", "social"] })}
providers={["Google", "Facebook"]}
labels={{ brand: "Acme", title: "Sign in to Acme", welcome: "Welcome to Acme" }}
onSignIn={() => location.assign("/dashboard")}
/>Its sign up is a sign in by emailed code with a new address: the emailOTP plugin creates the account unless disableSignUp is set. An account made this way has no two-factor yet, so it is not asked for a second step.
Two-factor
With the twoFactor plugin and twoFactorClient, a sign in to an account with two-factor on is answered with a second step, whichever way in was used. The block opens it and offers what the account has: a passkey such as a security key (with passkey({ secondFactor: true }) and passkeyClient), the authenticator app, a sent code (when otpOptions.sendOTP is set), and a backup code when the account holds some (they come with an authenticator app or a passkey setup). A passkey is offered first. With passkey({ secondFactor: true }), a passkey sign in to such an account is refused unless the passkey checked a PIN, a fingerprint or a face; the block shows the server's message, which points to the password. An account with two-factor on can therefore still get in by those other methods, so leave out the ones you do not want as a way around it.
A sign in that leaves the page cannot answer the block: single sign-on, and a sign-in link. For an account with two-factor on, the server sends the browser back to callbackURL with twoFactorRedirect=true and the steps the account can take, and no session. That page has to be reachable signed out. secondFactorFromRedirect reads the address and answers what a handler would have:
import { secondFactorFromRedirect } from "@entro314labs/entro-auth-iris";
const owed = secondFactorFromRedirect(window.location.href);
// { secondFactor: ["totp", "otp"] }, or undefined when the sign in went throughPass it to the block as resume, and it opens on the second step, with the email field skipped. method is how the first step was taken, which onSignIn then reports; leave it out when the page cannot tell.
<SignIn {...handlers} resume={owed} onSignIn={() => router.push("/dashboard")} />resume is read when the block first renders, so have the address by then: from searchParams in a server component, or from window.location in a component that renders only in the browser. It needs a version of the block that has the prop; an older copy of sign-in ignores it and shows the email field.
A provider that is not linked to an account with two-factor on does not come back this way: that sign-in is refused, and the address carries error=PROVIDER_NOT_LINKED. See A Provider That Is Not Linked Yet.
A refused single sign-on lands on errorCallbackURL with the reason in error: PROVIDER_NOT_LINKED, account_not_linked (an account with that address exists and the provider may not be attached to it by signing in), or what the provider itself said. Name your sign-in page there and say it in your own words; without the option the browser lands on the server's own error page. signUpHandlers takes the same option.
Do not set twoFactorPage on twoFactorClient. The client would send the browser there, away from the block's own second step.
Forgot password
resetPasswordURL adds "Forgot password?" to the password step. Set emailAndPassword.sendResetPassword on the server; the link it sends lands on your reset page with a token:
"use client";
import { resetPasswordHandlers } from "@entro314labs/entro-auth-iris";
import { ResetPassword } from "@/components/iris/blocks/reset-password/reset-password";
import { authClient } from "@/lib/auth-client";
export default function ResetPasswordPage() {
const token = new URLSearchParams(location.search).get("token");
return (
<ResetPassword
{...resetPasswordHandlers(authClient, token)}
onSignIn={() => location.assign("/sign-in")}
/>
);
}A link that was used or ran out arrives without a token, and the block says so.
Sign up
"use client";
import { signUpHandlers } from "@entro314labs/entro-auth-iris";
import { SignupForm } from "@/components/iris/blocks/signup-form/signup-form";
import { authClient } from "@/lib/auth-client";
const handlers = signUpHandlers(authClient, {
confirmEmail: "code",
social: true,
callbackURL: "/welcome",
errorCallbackURL: "/sign-up",
});
export default function SignUpPage() {
return (
<SignupForm
{...handlers}
providers={["Google", "Facebook"]}
onSignUp={() => location.assign("/welcome")}
/>
);
}confirmEmail says how a new address is confirmed when the server has requireEmailVerification on. Leave it out when accounts are ready at once.
"code": theemailOTPplugin withsendVerificationOnSignUpandoverrideDefaultEmailVerification. The block asks for the code."link":emailVerification.sendVerificationEmailwithsendOnSignUp. The block says where the link went.
onSignUp is called once the account is ready. Whether the person is signed in by then is the server's choice: without requireEmailVerification a new account is signed in at once, and with it, confirming the address signs in only when emailVerification.autoSignInAfterVerification is on. Otherwise send them to sign in.
The form also collects a product updates choice. It is stored only when you map it to a user field:
signUpHandlers(authClient, {
fields: ({ productUpdates }) => ({ productUpdates }),
});with a matching user.additionalFields.productUpdates on the server.
A passkey in place of a password
An account can be made with no password at all. A code by email proves the address, which a passkey does not, and the session that code opens adds the passkey.
<SignupForm
credential="passkey"
{...signUpHandlers(authClient, { credential: "passkey" })}
onSignUp={() => location.assign("/welcome")}
/>The form asks for a name and an address. Submitting it sends a sign-in code; typing the code signs in, which creates the account; and the block's last step offers "Create a passkey" beside "Not now". The passkey is made from that button, because a browser opens its passkey sheet only from a press. onSignUp is called after the step, whichever way it ends.
- The server needs
emailOTPwith sign up left on (nodisableSignUp) andpasskey. The client needsemailOTPClientandpasskeyClient.confirmEmailis not read in this mode, and thefieldsyou map are stored when the code creates the account. - The step can be skipped, and a passkey is lost with its device. The emailed code is the way back in, so the sign-in page has to offer it:
signInHandlers(authClient, { methods: ["passkey", "email-code"] }). - An address that already has an account is signed into that account, and the passkey is added there. Where the account has two-factor on, the code opens no session: the code step says to sign in, and nothing is added. That sentence is English unless you pass
existingAccountMessage. - The captcha plugin does not cover the code request unless told to. List
/email-otp/send-verification-otpin itsendpoints, or anybody can have codes sent to any address.
By invitation
With the waitlist plugin on the server and waitlistClient on the client, sign up is closed to people without an invitation. The Waitlist block is the page they are sent to instead:
import { waitlistHandlers } from "@entro314labs/entro-auth-iris";
import { Waitlist } from "@/components/iris/waitlist";
<Waitlist
{...waitlistHandlers(authClient)}
onSignIn={() => router.push("/sign-in")}
/>The link your sendInvitation emails leads to a page that opens the invitation and shows the sign up, starting with the invited address:
import { openInvitation, signUpHandlers } from "@entro314labs/entro-auth-iris";
const token = new URLSearchParams(location.search).get("token") ?? "";
const { email } = await openInvitation(authClient, token); // throws for a token that no longer works
<SignupForm email={email} {...signUpHandlers(authClient)} />Without an opened invitation, SignupForm shows the server's refusal above its button. SignIn with an emailed code works on the invitation page too: its first sign in for the invited address creates the account.
Account profile
loadAccountProfile(authClient) answers the name, the address, the photo and whether the address is verified; accountProfileHandlers(authClient, { changeEmail: true, callbackURL, onChange }) stores a new name and asks for a new address. Use them as the security page below does. changeEmail needs user.changeEmail.enabled on the server; the address changes once its confirmation link is opened, so the block keeps showing the old one until then.
The auth server stores a photo as a URL, and carries it in the session cookie. To let people change theirs, pass uploadPhoto, which stores the file wherever you keep files and answers the URL it is served from:
accountProfileHandlers(authClient, {
uploadPhoto: async (file) => {
const body = new FormData();
body.set("file", file);
const response = await fetch("/api/avatar", { method: "POST", body });
if (!response.ok) throw new Error("That photo could not be stored.");
return (await response.json()).url;
},
onChange: reload,
});A data: URL is refused: it would not fit in the cookie.
Account security
The block draws the data it is given, so the page loads it, and loads it again after a change:
"use client";
import type { AccountSecurityData, AccountSecurityOptions } from "@entro314labs/entro-auth-iris";
import { accountSecurityHandlers, loadAccountSecurity } from "@entro314labs/entro-auth-iris";
import { useCallback, useEffect, useState } from "react";
import { AccountSecurity } from "@/components/iris/blocks/account-security/account-security";
import { authClient } from "@/lib/auth-client";
const sections: AccountSecurityOptions["sections"] = [
"password",
"two-factor",
"sessions",
"connections",
];
export default function SecurityPage() {
const [data, setData] = useState<AccountSecurityData>({});
const reload = useCallback(() => {
void loadAccountSecurity(authClient, { sections }).then(setData);
}, []);
useEffect(reload, [reload]);
return (
<AccountSecurity
{...data}
{...accountSecurityHandlers(authClient, { sections, onChange: reload })}
providers={["Google", "Facebook"]}
/>
);
}| Section | Server | Client |
|---|---|---|
password | emailAndPassword: { enabled: true } | none |
two-factor | twoFactor | twoFactorClient |
passkeys | passkey | passkeyClient |
sessions | none | none |
connections | socialProviders | none; pass the block the same providers |
delete-account | user: { deleteUser: { enabled: true } } | none; organizationClient where the server has confirmSoleOwnerDeletion |
Two-factor is turned on by the first code from the authenticator app. The block shows the setup address as a QR code, the same key to type in, and the backup codes. An account that already has two-factor on keeps the codes it saved: enable answers none, and the block says the saved codes still work.
To offer a passkey as the second step as well, name the methods. It needs passkey({ secondFactor: true }) on the server and passkeyClient:
const options: AccountSecurityOptions = {
sections,
twoFactorMethods: ["totp", "passkey"],
};Connecting a provider leaves for the provider's page and comes back to callbackURL. When the provider's account cannot be connected, it comes back to errorCallbackURL with the reason in error: email_does_not_match (another address than the account's) or account_already_linked_to_different_user. Name the page the block is on for both, and say the reason there:
const options: AccountSecurityOptions = {
sections,
callbackURL: "/account/security",
errorCallbackURL: "/account/security",
};Pass the same options to loadAccountSecurity and accountSecurityHandlers. The block then asks which second step to turn on. A passkey is offered only to an account that has one; its setup shows the backup codes and a button that runs the passkey ceremony, and two-factor is on once the passkey has been used. Sessions are named from their user agent ("Chrome on macOS"), with the address and the date of their last use; formatDate changes how the date reads, and formatDevice how the name does: it is given the browser and the system, either of them missing when it could not be told, and answers the words to show.
Deleting the account
Name the delete-account section and the block gets a last section, ruled in red, with one button. It asks before it deletes, and it asks a second time where the server holds the deletion of an organization's only owner (confirmSoleOwnerDeletion): the organizations are listed, the person types a phrase to go on, and the handler records the acknowledgement and deletes.
const options: AccountSecurityOptions = {
sections: [...sections, "delete-account"],
// The session is gone with the account: go somewhere that needs none.
onAccountDeleted: () => window.location.assign("/"),
// Only where the server confirms a deletion by email: where its link lands.
deletedCallbackURL: "/goodbye",
};A session that signed in too long ago is asked "is it you?" first, as for any other change. Where the server sends a confirmation link (sendDeleteAccountVerification), the block says the link is on its way and the account is deleted when it is opened. It needs a current copy of the block and of lib/auth-flow.
Organization members
With the organization plugin and organizationClient, the block shows the person's active organization:
"use client";
import type { OrganizationMembersData } from "@entro314labs/entro-auth-iris";
import {
loadOrganizationMembers,
organizationMembersHandlers,
} from "@entro314labs/entro-auth-iris";
import { useCallback, useEffect, useState } from "react";
import { OrganizationMembers } from "@/components/iris/blocks/organization-members/organization-members";
import { authClient } from "@/lib/auth-client";
export default function MembersPage() {
const [data, setData] = useState<OrganizationMembersData>({ members: [] });
const reload = useCallback(() => {
void loadOrganizationMembers(authClient, { invitations: true }).then(setData);
}, []);
useEffect(reload, [reload]);
const mine = data.members.find((member) => member.you);
const manages = mine?.role === "owner" || mine?.role === "admin";
return (
<OrganizationMembers
{...data}
{...(manages
? organizationMembersHandlers(authClient, { onChange: reload })
: {})}
/>
);
}Without the handlers the block is a plain list, which is what a member should see. The server checks every change against the person's role either way. Pass invitations: true only for people who may read invitations, and organizationId to show an organization other than the active one. With custom roles, pass the block your roles.
Switching organization
loadOrganizations(authClient) answers the person's organizations and the one their session is in; organizationSwitcherHandlers(authClient, { onChange }) switches it. The members page above follows, since it shows the active organization.
<OrganizationSwitcher
{...data}
{...organizationSwitcherHandlers(authClient, { onChange: reload })}
personal
/>personal offers the session outside any organization. When the server refuses a switch, because the person is no longer a member, it also takes the session out of its organization, so onChange is called after a refusal as well.
Errors
A handler throws the server's message as an Error, and the block shows it beside the field it belongs to. To reword or translate the messages, use the i18n plugin on the server, and the blocks' labels for their own words.
Changes that need a recent sign-in
The server refuses some changes from a session that signed in longer ago than session.freshAge (one day by default): connecting or disconnecting a provider, adding a passkey, managing two-factor without a password, and a change of address the current address does not confirm. It answers SESSION_NOT_FRESH.
The AccountSecurity block answers that in place. loadAccountSecurity tells it how the account can prove who is asking (identityWays), and accountSecurityHandlers gives it onConfirmIdentity. The block opens "First, is it you?" over the page, and once it is answered makes the change again, so nobody has to sign out and start over:
| The account | What is asked |
|---|---|
| Has a password, two-factor off | The password (renewSession), or a code by email when you set emailCode |
| Two-factor on | A passkey when it has one and you offer it, the authenticator's code, a backup code |
| No password and no two-factor | A code by email when you set emailCode; without it the block shows the refusal |
An account with two-factor on is never asked for its password here: the server takes its second step and nothing less. It needs a current copy of the block and of lib/auth-flow: a copy from before the block could ask shows the refusal as before, and one from before email-code no longer typechecks against the data of loadAccountSecurity.
An account made through a provider or with a passkey has no password to give. Set emailCode to let it answer with a code sent to its own address: the server needs the emailOTP plugin and the client emailOTPClient. The handlers then also give the block onSendIdentityCode, and the code goes out when the person asks for it, not when the question opens.
const options = { sections: ["passkeys", "connections"], emailCode: true };To handle the refusal your own way, pass onSessionNotFresh. The handler then calls it, the block does not ask, and the server's message shows as any other:
const options: AccountSecurityOptions = {
sections,
onChange: reload,
onSessionNotFresh: () => router.push("/sign-in?return=/account/security"),
};accountProfileHandlers takes the same option for "Change email". Reading the page needs no recent sign-in: the sessions section lists them by id, without their tokens.