Add organizations and roles
For: an app developer whose users work in teams.
What it does: core adds organizations, members with ranked roles, invitations by mail, and an active organization on each session.
Before you start
Section titled “Before you start”- A working setup from a getting started tutorial.
- Users with a verified address. Every organization write refuses an unverified caller. The claim rule tells what verifies an address.
- Add
organizations: {}to the config. With noorganizationskey, the organization routes answer 404. - Set
rankswhen the four default roles do not fit. The table must nameowner.- For rights by name, set
rolesin its place. Roles and permissions tells how.
- For rights by name, set
- Set
limitsfor the counts that your plan sells. Each count is off by default.
import { createAuth, type MailPort, type StorageAdapter } from "@authtempo/core";
export function createOrganizationsAuth(deps: { storage: StorageAdapter; mail: MailPort; secret: string;}) { return createAuth({ baseURL: "https://api.example.com", appURL: "https://app.example.com", trustedOrigins: ["https://app.example.com"], secret: deps.secret, storage: deps.storage, mail: deps.mail, organizations: { // The default rank table, written out: viewer < member < admin < owner. ranks: { viewer: 1, member: 2, admin: 3, owner: 4 }, // The life of an invitation in days. The default is 7. invitationTtlDays: 7, // The link in the invitation mail. The default is <appURL>/?invitation=<token>. invitationLinkBuilder: (token) => `https://app.example.com/join?invitation=${encodeURIComponent(token)}`, // Counts that core keeps. Each is off by default. limits: { perUser: 5, membersPerOrganization: 50, pendingInvitationsPerOrganization: 20 }, }, });}- Call
client.organizations.checkSlug({ slug })to show if the slug is free. - Call
client.organizations.create({ slug, name }). The creator becomesowner. - Call
client.organizations.invitations.invite({ organizationId, email, role }). Core mails the link. - On the page of the link, call
client.organizations.invitations.accept({ token })for the signed-in person. - Call
client.organizations.setActive({ organizationId })when the person picks an organization. - In each route of your app, check the member’s right again with
auth.hasPermission. The active organization is a choice, not a right.
import { describe, expect, it } from "vitest";import { call, harness, linkIn, signIn } from "../support/harness.ts";import { createOrganizationsAuth } from "./organizations.ts";
describe("add organizations and roles", () => { it("creates an organization, invites a member by mail, and lets the member accept", async () => { const h = harness(); const auth = createOrganizationsAuth(h); const ada = await signIn(auth, h, "ada@example.com"); const created = await call( auth, "POST", "/auth/organizations/create", { slug: "team", name: "Team" }, { cookie: ada }, ); expect(created.status).toBe(200); const { organization, member } = (await created.json()) as { organization: { id: string; slug: string }; member: { role: string }; }; expect(member.role).toBe("owner");
const invite = await call( auth, "POST", "/auth/organizations/invite", { organizationId: organization.id, email: "bo@example.com", role: "member" }, { cookie: ada }, ); expect(invite.status).toBe(200); const token = linkIn(h, "bo@example.com").searchParams.get("invitation") ?? "";
const bo = await signIn(auth, h, "bo@example.com"); const accept = await call( auth, "POST", "/auth/organizations/invitations/accept", { token }, { cookie: bo }, ); expect(((await accept.json()) as { member: { role: string } }).member.role).toBe("member"); });
it("refuses a reserved slug", async () => { const h = harness(); const auth = createOrganizationsAuth(h); const ada = await signIn(auth, h, "ada@example.com"); const res = await call( auth, "POST", "/auth/organizations/create", { slug: "admin", name: "Admin" }, { cookie: ada }, ); expect(await res.json()).toEqual({ error: "slug_reserved" }); });});How it behaves
Section titled “How it behaves”- A role string may hold several roles joined by a comma. Its rank is the highest rank present, and an unknown role ranks 0.
- A caller grants or sets only a role at or below the caller’s own rank. A caller never touches a member of a higher rank.
- The last owner cannot leave, be demoted, or be removed.
- A slug is lower case after NFKC, up to 64 characters. The default reserved slugs are
admin,api,auth,internal,operator,ops,platform,system, andwww. - An organization holds one pending invitation for each address. A new invitation replaces the old one, and the old link stops.
- The invitation token is in the mail only. No answer of a route carries it.
- To accept, the caller’s verified address must equal the invited address.
- Invite has two limits:
invite:user:<userId>20 per 15 minutes, andinvite:email:<email>5 per hour. - Accept has one limit:
invitation-accept:ip:<ip>20 per 15 minutes. - The slug check answers the folded slug and
available,taken,reserved, orinvalid. It needs a verified address. availableis a hint, not a hold. The create still answersslug_takenwhen another user takes the slug first.- The slug check, the create, and a rename to a new slug spend one limit:
slug-check:user:<userId>60 per minute. - Teams group the members of an organization. A team has no role of its own.
- A hook point runs your code before or after each organization write.
If it fails
Section titled “If it fails”forbidden_rank: the caller is not a member, or the rank is too low.slug_reservedandslug_taken: pick another slug.last_owner: the write would leave no owner. Promote another member first.conflict: a write at the same time changed the member. Read it again and retry.already_memberandemail_mismatch: the add or the accept does not fit the member.organization_limit,member_limit, andinvitation_limit: a count oflimitsis full.email_unverified: the caller must prove the address first.invalid_tokenandtoken_expired: the invitation is spent, revoked, old, or its inviter lost the rank.rate_limited: too many invitations, accepts, or slug reads.invalid_body: the slug check got an empty slug, a slug over 64 characters, or another key.