This guide covers the withInvitations mixin from @adonisplus/persona/invitations. You will learn how to:

  • Create the invitations table and apply the mixin to the model people join
  • Invite people by email, and resend or revoke their invitations
  • Show an invite page and accept an invitation
  • Let people sign in or sign up through an invitation

Most apps let users bring other people in, for example into a team, a workspace or a project. The withInvitations mixin handles the invitation itself: who was invited, the secret link they receive, when it expires, and accepting it safely.

A few terms appear throughout this guide:

  • An invitation is a pending offer to one email address to join one record.
  • The invitable is the model of the record people join, for example Workspace.
  • The invitee is the person who owns the invited email address.
  • The inviter is the record that sent the invitation. It can belong to any model, usually a user.

The mixin goes on the invitable model, not on your User model. This guide uses a Workspace model as the example, but the same steps work for any model.

The mixin owns the invitation, its token and its expiry. When an invitee accepts, it checks their email and uses up the token. Your app stays in charge of:

  • Sending the invite email.
  • Deciding who can invite people.
  • Checking that the email doesn't already belong to a member.
  • Creating the membership record when the invitee accepts.

The table only stores a hash of each token. Accepting finds the row and deletes it in a single query, and fails unless exactly one row was deleted. So a token works only once, even when two requests try to accept it at the same moment. An invitation lives only until it is accepted or revoked, and is then deleted. Inviting the same email again updates the existing invitation in place. Your membership records are the history of who joined.

The mixin needs one new table, and you apply it to the invitable model.

  1. Generate a migration for the invitations table. Persona doesn't ship migrations.

    Terminal
    node ace make:migration create_invitations
    database/migrations/xxxx_create_invitations.ts
    import { BaseSchema } from '@adonisjs/lucid/schema'
    
    export default class extends BaseSchema {
      protected tableName = 'invitations'
    
      async up() {
        this.schema.createTable(this.tableName, (table) => {
          table.increments('id')
          table
            .integer('workspace_id')
            .unsigned()
            .notNullable()
            .references('id')
            .inTable('workspaces')
            .onDelete('CASCADE')
          table.string('email', 254).notNullable()
          table.text('metadata').notNullable()
          table.string('inviter_type').nullable()
          table.string('inviter_id').nullable()
          table.string('hash', 80).notNullable()
          table.timestamp('expires_at', { precision: 6, useTz: true }).notNullable()
          table.timestamp('created_at', { precision: 6, useTz: true }).notNullable()
          table.timestamp('updated_at', { precision: 6, useTz: true }).notNullable()
          table.unique(['workspace_id', 'email'])
        })
      }
    
      async down() {
        this.schema.dropTable(this.tableName)
      }
    }
    

    A few of these columns need a closer look.

    workspace_idinteger
    The foreign key to the invitable. The mixin derives its name from the model's naming strategy, for example workspace_id for Workspace. Use the foreignKey option if your column has a different name.
    emailstring(254)
    The invited email address, stored in lower case. The unique index on the invitable and the email keeps one invitation per email in each workspace.
    metadatatext
    Your app's data for the invitation, such as the role, stored as a JSON string. A text column works on every database Lucid supports.
    inviter_type and inviter_idstring, nullable
    The table of the inviter's model and its primary key, for example users and 42. inviter_id is a string, so it can hold an integer or a UUID.
    hashstring(80)
    The hash of the token's secret. The token itself is never stored.
  2. Apply the withInvitations mixin to the invitable model with compose, and pass it the type of your metadata. The mixin stores the metadata as it is and returns it with that type, without inspecting it.

    app/models/workspace.ts
    import Membership from '#models/membership'
    import { WorkspaceSchema } from '#database/schema'
    import { compose } from '@adonisjs/core/helpers'
    import { hasMany } from '@adonisjs/lucid/orm'
    import type { HasMany } from '@adonisjs/lucid/types/relations'
    import { withInvitations } from '@adonisplus/persona/invitations'
    
    export type InvitationMetadata = { role: 'admin' | 'member' } 
    
    export default class Workspace extends compose(
      WorkspaceSchema,
      withInvitations<InvitationMetadata>() 
    ) {
      @hasMany(() => Membership)
      declare memberships: HasMany<typeof Membership>
    }
    

    To change the defaults, pass a config object.

    app/models/workspace.ts
    import { WorkspaceSchema } from '#database/schema'
    import { compose } from '@adonisjs/core/helpers'
    import { withInvitations } from '@adonisplus/persona/invitations'
    
    export type InvitationMetadata = { role: 'admin' | 'member' }
    
    export default class Workspace extends compose(
      WorkspaceSchema,
      withInvitations<InvitationMetadata>({
        expiresIn: '3 days',
        table: 'workspace_invitations',
        foreignKey: 'team_id',
      })
    ) {}
    
    expiresInstring | number

    How long an invitation stays valid, as a number of seconds or a time expression such as '3 days'.

    Defaults to '7 days'.

    tablestring

    The table that stores the invitations.

    Defaults to "invitations".

    foreignKeystring

    The column that holds the invitable's primary key.

    Defaults to the foreign key from the model's naming strategy, for example "workspace_id" for Workspace.

An invitation has two sides, and each one is its own resource.

  • A workspace's invitations. Members invite people, resend invitations and revoke them from the workspace settings. These routes sit inside the workspace scope, at /w/:slug/settings/invitations.
  • The invite that the invitee opens from the email. The invitee isn't a member yet, so these routes sit outside the workspace scope, at /invites/:token. The invitee can view the invite and accept it. There is no decline action.

The invite is looked up by its token rather than through a signed URL, because the token is already the secret.

The URL identifies the workspace by its slug. A middleware looks up the workspace through the signed-in user's memberships, so a workspace the user doesn't belong to is not found and returns a 404. Every invitation action then works through ctx.workspace, so an invitation from another workspace is never found.

app/middleware/current_workspace_middleware.ts
import Workspace from '#models/workspace'
import type { HttpContext } from '@adonisjs/core/http'
import type { NextFn } from '@adonisjs/core/types/http'

export default class CurrentWorkspaceMiddleware {
  async handle(ctx: HttpContext, next: NextFn) {
    const user = ctx.auth.getUserOrFail()

    ctx.workspace = await Workspace.query()
      .where('slug', ctx.params.slug)
      .whereHas('memberships', (query) => query.where('user_id', user.id))
      .firstOrFail()

    return next()
  }
}

declare module '@adonisjs/core/http' {
  interface HttpContext {
    workspace: Workspace
  }
}

Register it as a named middleware in start/kernel.ts under the name currentWorkspace.

The invite method creates an invitation for an email address and returns the invitation together with its token. The token holds the secret for the link in the email. If the workspace already has an invitation for that email, pending or expired, invite updates it in place with a new token, a new expiry and the new metadata. The invitation keeps its id and moves to the top of the list, and the old link stops working.

Persona never sends email itself. Send the invite email with @adonisjs/mail, and put token.value!.release() in the /invites/:token link inside the mail class.

WorkspacePolicy is your app's Bouncer policy. It decides who can manage invitations, for example only admins. Persona leaves that decision to you. The store action also rejects an email that already belongs to a member.

app/controllers/invitations_controller.ts
import type { HttpContext } from '@adonisjs/core/http'
import mail from '@adonisjs/mail/services/main'
import WorkspacePolicy from '#policies/workspace_policy'
import { invitationValidator } from '#validators/invitation'
import InvitationNotification from '#mails/invitation_notification'

export default class InvitationsController {
  async store({ auth, bouncer, request, response, session, workspace }: HttpContext) {
    await bouncer.with(WorkspacePolicy).authorize('manageInvitations', workspace)
    const { email, role } = await request.validateUsing(invitationValidator)

    const member = await workspace
      .related('memberships')
      .query()
      .whereHas('user', (query) => query.whereRaw('lower(email) = ?', [email]))
      .first()

    if (member) {
      session.flash('error', 'This person is already a member')
      return response.redirect().back()
    }

    const { invitation, token } = await workspace.invite(email, {
      inviter: auth.getUserOrFail(),
      metadata: { role },
    })

    await mail.sendLater(new InvitationNotification(invitation, token))

    session.flash('success', 'Invitation sent')
    return response.redirect().back()
  }
}
app/validators/invitation.ts
import vine from '@vinejs/vine'

export const invitationValidator = vine.create({
  email: vine.string().trim().email().toLowerCase(),
  role: vine.enum(['admin', 'member']),
})

workspace.invitations lists, resends and revokes a workspace's invitations. Every method is scoped to that workspace.

The pending method returns the pending invitations, newest first, and leaves out expired ones. To show expired invitations as well, for example so an admin can resend them, use all. It returns both pending and expired invitations, newest first. Call isExpired() on an invitation to tell them apart.

const invitations = await workspace.invitations.all()
const expired = invitations.filter((invitation) => invitation.isExpired())
app/controllers/invitations_controller.ts
import type { HttpContext } from '@adonisjs/core/http'
import WorkspacePolicy from '#policies/workspace_policy'
import InvitationTransformer from '#transformers/invitation_transformer'

export default class InvitationsController {
  async index({ bouncer, inertia, workspace }: HttpContext) {
    await bouncer.with(WorkspacePolicy).authorize('manageInvitations', workspace)
    const invitations = await workspace.invitations.pending()

    return inertia.render('workspaces/settings/invitations', {
      invitations: InvitationTransformer.transform(invitations),
    })
  }
}

An invitation is not a Lucid model, so its transformer takes Persona's Invitation type, parameterized with your metadata type.

app/transformers/invitation_transformer.ts
import { inject } from '@adonisjs/core'
import type { HttpContext } from '@adonisjs/core/http'
import { BaseTransformer } from '@adonisjs/core/transformers'
import type { InvitationMetadata } from '#models/workspace'
import type { Invitation } from '@adonisplus/persona/invitations'

export default class InvitationTransformer extends BaseTransformer<
  Invitation<InvitationMetadata>
> {
  @inject()
  toObject({ i18n }: HttpContext) {
    return {
      id: String(this.resource.identifier),
      email: this.resource.email,
      role: this.resource.metadata.role,
      expiresAt: {
        raw: this.resource.expiresAt.toISOString(),
        formatted: i18n.formatDate(this.resource.expiresAt, { dateStyle: 'medium' }),
      },
    }
  }
}

An invitation's inviterType and inviterId properties identify the inviter. Persona defines no relation for it, so map the table name back to your model to load the inviter.

const inviter = invitation.inviterType === 'users' ? await User.find(invitation.inviterId) : null

The resend method gives an invitation a new token and a new expiry, and returns them. The old link stops working, because only the token's hash is stored. Send the invite email again with the new token.

Pass true as the second argument to throttle resends. While the throttle window is open, resend returns null and creates no new token. The window starts at the invitation's last change and lasts 60 seconds by default. Pass a duration as the third argument to change it. Two resends of the same invitation at the same time run one after the other, so only one of them gets past the throttle.

If the workspace has no invitation with that id, for example because it was accepted or revoked, resend throws E_INVITATION_NOT_FOUND. You don't need to look the invitation up first.

A throttled resend sends no email, but it still shows the same "Invitation sent again" message.

app/controllers/invitations_controller.ts
import type { HttpContext } from '@adonisjs/core/http'
import mail from '@adonisjs/mail/services/main'
import WorkspacePolicy from '#policies/workspace_policy'
import InvitationNotification from '#mails/invitation_notification'

export default class InvitationsController {
  async update({ bouncer, params, response, session, workspace }: HttpContext) {
    await bouncer.with(WorkspacePolicy).authorize('manageInvitations', workspace)

    const resent = await workspace.invitations.resend(params.id, true)
    if (resent) {
      await mail.sendLater(new InvitationNotification(resent.invitation, resent.token))
    }

    session.flash('success', 'Invitation sent again')
    return response.redirect().back()
  }
}

find, resend and revoke all work on expired invitations too, so an admin can renew or remove an invite after it expires.

The revoke method deletes an invitation and returns it, and its link stops working. It returns null when there is no invitation with that id.

app/controllers/invitations_controller.ts
import { errors } from '@adonisjs/lucid'
import type { HttpContext } from '@adonisjs/core/http'
import WorkspacePolicy from '#policies/workspace_policy'

export default class InvitationsController {
  async destroy({ bouncer, params, response, workspace }: HttpContext) {
    await bouncer.with(WorkspacePolicy).authorize('manageInvitations', workspace)

    if (!(await workspace.invitations.revoke(params.id))) {
      throw new errors.E_ROW_NOT_FOUND()
    }

    return response.redirect().back()
  }
}

revoke accepts an optional callback as its second argument. The callback receives the invitation and the transaction of the delete. If the callback throws, the invitation is kept.

Expiry is lazy. An expired invitation stays in the table, but pending, findInvitation and acceptInvitation ignore it, and inviting the same email again reuses it. The clearExpired method deletes a workspace's expired invitations and returns how many it deleted.

const clearedCount = await workspace.invitations.clearExpired()

To clean up every workspace at once, for example from a scheduled command, call the static clearExpiredInvitations method on the model. It deletes the expired invitations of every workspace and returns how many it deleted.

const clearedCount = await Workspace.clearExpiredInvitations()

The link in the email opens the invite page. The static findInvitation method returns the pending invitation for a token without using the token up. It returns null for a wrong or expired token.

The page has three states:

  • The signed-in invitee. The page shows the workspace name, the inviter's name, the role and an accept button.
  • A guest. The page shows the workspace name, the inviter's name, and links to sign up and sign in. Both links carry the token.
  • An invalid invite. A wrong, expired or already used link shows this state, and so does a signed-in user with a different email.
app/controllers/invites_controller.ts
import User from '#models/user'
import Workspace from '#models/workspace'
import type { HttpContext } from '@adonisjs/core/http'
import InviteTransformer from '#transformers/invite_transformer'

export default class InvitesController {
  async show({ auth, inertia, params }: HttpContext) {
    await auth.check()
    const invitation = await Workspace.findInvitation(params.token)

    if (!invitation) {
      return inertia.render('invites/show', { state: 'invalid' })
    }

    if (auth.user && auth.user.email.toLowerCase() !== invitation.email) {
      return inertia.render('invites/show', { state: 'invalid' })
    }

    const workspace = await Workspace.findOrFail(invitation.invitableId)
    const inviter =
      invitation.inviterType === 'users' && invitation.inviterId
        ? await User.find(invitation.inviterId)
        : null

    return inertia.render('invites/show', {
      state: auth.user ? 'invited' : 'guest',
      token: params.token,
      invite: InviteTransformer.transform(invitation, { workspace, inviter }),
    })
  }
}

The invite is its own resource, so it has its own transformer. The workspace and the inviter are passed in as the second argument, because a transformer never queries the database.

app/transformers/invite_transformer.ts
import type User from '#models/user'
import { BaseTransformer } from '@adonisjs/core/transformers'
import type { Invitation } from '@adonisplus/persona/invitations'
import type Workspace from '#models/workspace'
import type { InvitationMetadata } from '#models/workspace'

export default class InviteTransformer extends BaseTransformer<Invitation<InvitationMetadata>> {
  #workspace: Workspace
  #inviter: User | null

  constructor(
    resource: Invitation<InvitationMetadata>,
    related: { workspace: Workspace; inviter: User | null }
  ) {
    super(resource)
    this.#workspace = related.workspace
    this.#inviter = related.inviter
  }

  toObject() {
    return {
      workspaceName: this.#workspace.name,
      inviterName: this.#inviter?.fullName ?? null,
      role: this.resource.metadata.role,
    }
  }
}

The invite page's sign-in link carries the token, for example /login?invite=<token>, and the sign-in page sends it back with the form. After sign-in, the controller builds the invite page URL from the token. It never takes a return URL from the request. Add invite: vine.string().optional() to the sign-in validator.

app/controllers/session_controller.ts
import User from '#models/user'
import type { HttpContext } from '@adonisjs/core/http'
import { loginValidator } from '#validators/user'

export default class SessionController {
  async store({ auth, request, response }: HttpContext) {
    const { email, password, invite } = await request.validateUsing(loginValidator)
    const user = await User.verifyCredentials(email, password)

    await auth.use('web').login(user)

    if (invite) {
      return response.redirect().toRoute('invites.show', [invite])
    }

    return response.redirect().toRoute('dashboard')
  }
}

The static acceptInvitation method takes the token, the signed-in user's email and a callback. It always checks the email, uses up the token, and runs the callback inside the accept's transaction. Create the membership in the callback. If the callback throws, the invitation is kept and the invitee can try again. acceptInvitation returns whatever the callback returns.

app/controllers/invites_controller.ts
import Workspace from '#models/workspace'
import type { HttpContext } from '@adonisjs/core/http'

export default class InvitesController {
  async update({ auth, params, response, session }: HttpContext) {
    const user = auth.getUserOrFail()

    const workspace = await Workspace.acceptInvitation(
      params.token,
      user.email,
      async (invitation, trx) => {
        const invitedWorkspace = await Workspace.findOrFail(invitation.invitableId, { client: trx })
        await invitedWorkspace
          .related('memberships')
          .firstOrCreate({ userId: user.id }, { role: invitation.metadata.role })

        return invitedWorkspace
      }
    )

    session.flash('success', `You joined ${workspace.name}`)
    return response.redirect().toRoute('workspaces.show', { slug: workspace.slug })
  }
}

The user lands in the workspace, and the layout shows the You joined <workspace> flash message as a toast. The role comes from the metadata, typed with the type you gave the mixin. A user who is already a member keeps their existing membership and role.

A wrong, expired or used token throws E_INVALID_INVITATION_TOKEN. A different email throws E_INVITATION_EMAIL_MISMATCH, and the invitation is kept.

A guest without an account follows the invite page's sign-up link, for example /signup?invite=<token>. The sign-up page locks the email field to the invited email.

app/controllers/signup_controller.ts
import Workspace from '#models/workspace'
import type { HttpContext } from '@adonisjs/core/http'

export default class SignupController {
  async create({ inertia, request }: HttpContext) {
    const token = request.input('invite')
    const invitation = token ? await Workspace.findInvitation(token) : null

    return inertia.render('auth/signup', {
      invite: invitation ? { token, email: invitation.email } : null,
    })
  }
}

On submit, create the user and accept the invitation in a single transaction, and pass that transaction to acceptInvitation with the client option. If the accept fails, the transaction rolls back and no account is created. The email check runs here too, so tampering with the email field makes the accept fail.

app/controllers/signup_controller.ts
import User from '#models/user'
import Workspace from '#models/workspace'
import db from '@adonisjs/lucid/services/db'
import type { HttpContext } from '@adonisjs/core/http'
import { inviteSignupValidator } from '#validators/user'

export default class SignupController {
  async store({ auth, request, response, session }: HttpContext) {
    const { email, password, invite } = await request.validateUsing(inviteSignupValidator)

    const { user, workspace } = await db.transaction(async (trx) => {
      const newUser = await User.create({ email, password }, { client: trx })

      const invitedWorkspace = await Workspace.acceptInvitation(
        invite,
        newUser.email,
        async (invitation, invitationTrx) => {
          const found = await Workspace.findOrFail(invitation.invitableId, { client: invitationTrx })
          await found
            .related('memberships')
            .create({ userId: newUser.id, role: invitation.metadata.role })

          return found
        },
        { client: trx }
      )

      return { user: newUser, workspace: invitedWorkspace }
    })

    await auth.use('web').login(user)
    session.flash('success', `You joined ${workspace.name}`)
    return response.redirect().toRoute('workspaces.show', { slug: workspace.slug })
  }
}

Note

If your app uses the email management mixin, you can mark the email as verified at this point. The invitee opened a link sent to this address, so accepting proves they own it. Create the user with unverifiedEmail: null to make the account active right away. Keep in mind that anyone with a forwarded invite link can create the account for the invited email.

Register a workspace's invitation routes behind the current workspace middleware, and the invite routes outside it. Guests can open the invite page, but accepting requires a signed-in user.

start/routes.ts
import router from '@adonisjs/core/services/router'
import { middleware } from '#start/kernel'
import { controllers } from '#generated/controllers'

router
  .group(() => {
    router
      .resource('invitations', controllers.Invitations)
      .only(['index', 'store', 'update', 'destroy'])
      .where('id', router.matchers.number())
  })
  .prefix('w/:slug/settings')
  .use([middleware.auth(), middleware.currentWorkspace()])

router
  .resource('invites', controllers.Invites)
  .only(['show', 'update'])
  .params({ invites: 'token' })
  .use(['update'], middleware.auth())

The routes are:

InvitationsController, behind the current workspace middleware
GET     /w/:slug/settings/invitations        index     the pending list
POST    /w/:slug/settings/invitations        store     invite, or invite the same email again
PUT     /w/:slug/settings/invitations/:id    update    resend
DELETE  /w/:slug/settings/invitations/:id    destroy   revoke

InvitesController
GET     /invites/:token                      show      the invite page
PUT     /invites/:token                      update    accept

Resend is the update action, because inviting, resending and revoking cover the whole life of an invitation.

The invitations module throws three errors, each with the status 400. See Errors for the response each request type gets.

E_INVALID_INVITATION_TOKENstatus 400
Thrown by acceptInvitation when the token is wrong, expired or already used. This includes the token of an invitation that was revoked, replaced or resent.
E_INVITATION_EMAIL_MISMATCHstatus 400
Thrown by acceptInvitation when the email doesn't match the invited email. The invitation is kept.
E_INVITATION_NOT_FOUNDstatus 400
Thrown by resend when the invitable has no invitation with that id, for example because it was accepted or revoked. Its message is "This invitation no longer exists".

The withInvitations mixin adds the following to model instances.

invitemethod

Invites an email address to join the invitable and returns { invitation, token }. An existing invitation for the same email, pending or expired, is updated in place. It keeps its id, and its old token stops working. inviter is optional and metadata is required.

const { invitation, token } = await workspace.invite('jane@example.com', {
  inviter: user,
  metadata: { role: 'member' },
})
invitationsgetter

The invitable's invitations. Every method is scoped to the invitable and runs in its transaction.

const pendingInvitations = await workspace.invitations.pending()
const allInvitations = await workspace.invitations.all()
const foundInvitation = await workspace.invitations.find(id)
const resentInvitation = await workspace.invitations.resend(id, true, '2 minutes')
const revokedInvitation = await workspace.invitations.revoke(id)
const clearedCount = await workspace.invitations.clearExpired()
  • pending() returns the pending invitations, newest first.
  • all() returns the pending and expired invitations, newest first.
  • find(id) returns the invitation with that id, even when it has expired, or null.
  • resend(id, shouldThrottle?, throttleDuration?) returns { invitation, token }, or null while the throttle window is open. It throws E_INVITATION_NOT_FOUND when there is no invitation with that id.
  • revoke(id, callback?) deletes an invitation and returns it, or returns null.
  • clearExpired() deletes the invitable's expired invitations and returns how many it deleted.
invitationsDbInvitationsProvider
The provider instance the mixin defines on the model. The instance methods delegate to it, so you rarely need to call it directly.
findInvitationstatic method

Returns the pending invitation for a token without using the token up. Returns null when the token is wrong or expired.

const invitation = await Workspace.findInvitation(token)
acceptInvitationstatic method

Accepts the invitation for a token and an email, uses up the token, and returns the callback's value. The callback runs inside the accept's transaction. Pass { client: trx } to run the accept inside your own transaction. Throws E_INVALID_INVITATION_TOKEN and E_INVITATION_EMAIL_MISMATCH.

const result = await Workspace.acceptInvitation(token, user.email, async (invitation, trx) => {
  // Create the membership with { client: trx }, and return a value
})

await Workspace.acceptInvitation(token, user.email, callback, { client: trx })
clearExpiredInvitationsstatic method

Deletes the expired invitations of every record of the model and returns how many it deleted. Call it from a scheduled command to keep the table small.

const clearedCount = await Workspace.clearExpiredInvitations()

Every Invitation object has the following properties.

identifierstring | number | BigInt
The primary key of the invitation row.
invitableIdstring | number | BigInt
The primary key of the invitable.
emailstring
The invited email address, in lower case.
metadataMetadata
The invitation's metadata, typed with the type you gave the mixin.
inviterTypestring | null
The table of the inviter's model, for example users.
inviterIdstring | null
The inviter's primary key, as a string.
expiresAtDate
When the invitation expires.
createdAtDate
When the invitation was created.
updatedAtDate
When the invitation last changed, for example on a resend.

isExpired() returns true once the invitation has expired.

The token that invite and resend return is an InvitationToken. Send token.value!.release() to the invitee. Only its hash is stored.