O

ouhammmourachid / saas-starter

Public

Multi-tenant SaaS backend: teams with owner/admin/member roles, email invites, and a subscription status you update from your payment provider's webhook.

  • SaaS starter
  • 0 deploys
  • 0 forks

SaaS Starter: teams, roles, invites and billing status

Multi-tenant SaaS backend: teams with owner/admin/member roles, email invites, and a subscription status you update from your payment provider's webhook.

What you get

  • Creating a team makes you its owner, with an owner membership added automatically
  • Members see only the teams they belong to (API rules via memberships_via_team)
  • Owners invite by email; invite tokens are hidden from the API and accepted at POST /api/invites/{token}/accept
  • Plan and subscription fields can only be changed by the server, never by the client
  • POST /api/billing/webhook updates a team's plan from your payment provider

Collections

teams

FieldTypeNotes
name (required)textTeam name
owner (required)relation → usersSet by a hook to the signed-in user
planselectSet by the billing webhook
subscription_statusselectSet by the billing webhook
current_period_enddateSet by the billing webhook
ActionWho can do it
List / viewmemberships_via_team.user ?= @request.auth.id
Createsigned-in users
Updateowner = @request.auth.id
Deleteowner = @request.auth.id

memberships

Created by hooks only (team creation, invite acceptance).

FieldTypeNotes
team (required)relation → teams
user (required)relation → users
role (required)selectowner, admin or member
ActionWho can do it
List / viewteam.memberships_via_team.user ?= @request.auth.id
Createsuperusers only
Updateteam.owner = @request.auth.id
Deleteteam.owner = @request.auth.id || user = @request.auth.id

invites

FieldTypeNotes
team (required)relation → teams
email (required)emailWho is invited
role (required)selectadmin, member
tokentextGenerated by a hook; hidden from the API
acceptedbool
invited_byrelation → usersSet by a hook
ActionWho can do it
List / viewteam.owner = @request.auth.id
Createsigned-in users
Updatesuperusers only
Deleteteam.owner = @request.auth.id

Hooks

All hooks are in pb_hooks/main.pb.js and commented.

Setup

  • Set Application URL and SMTP in Settings so invite emails send and link to your app (<appURL>/invite/<token>).
  • Set the environment variable BILLING_WEBHOOK_SECRET: Shared secret your webhook caller sends in X-Webhook-Secret

Quick start

import PocketBase from "pocketbase"
const pb = new PocketBase("https://YOUR-INSTANCE.pocketshub.com")

const team = await pb.collection("teams").create({ name: "Acme" })

// Invite someone (owner only). They get an email with a link to /invite/<token>.
await pb.collection("invites").create({ team: team.id, email: "sam@example.com", role: "member" })

// On your /invite/:token page, once Sam is signed in with a verified email:
await pb.send(`/api/invites/${token}/accept`, { method: "POST" })

// Teams the signed-in user belongs to:
const teams = await pb.collection("teams").getFullList()

Notes

  • The billing webhook takes a simple JSON body. Verify your provider's signature (Stripe, Creem, Paddle...) in your own handler, then forward the result here with the shared secret.
  • Accepting an invite needs a verified email that matches the invite.
  • The admin role is stored for your own collections' rules (e.g. team.memberships_via_team.role ?= 'admin'). Out of the box, only the owner can rename the team, invite, and manage members.

License

MIT

teams
  • id
  • name
  • ownersingle
  • plansingle
  • subscription_statussingle
  • current_period_end
  • created
  • updated
memberships
  • id
  • teamsingle
  • usersingle
  • rolesingle
  • created
  • updated
invites
  • id
  • teamsingle
  • email
  • rolesingle
  • tokenHidden
  • accepted
  • invited_bysingle
  • created
  • updated

3 collections, 2 relations. Hover a collection to trace its relations

main.pb.js188 lines
/// <reference path="../pb_data/types.d.ts" />

// ---------------------------------------------------------------------------
// Teams
// ---------------------------------------------------------------------------

// A signed-in user creates a team: they become its owner, on the free plan.
onRecordCreateRequest((e) => {
  if (!e.hasSuperuserAuth()) {
    if (!e.auth) throw new UnauthorizedError("Sign in to create a team.")
    e.record.set("owner", e.auth.id)
    e.record.set("plan", "free")
    e.record.set("subscription_status", "none")
    e.record.set("current_period_end", "")
  }
  e.next()
}, "teams")

// Give the owner an "owner" membership as soon as the team exists.
onRecordAfterCreateSuccess((e) => {
  const membership = new Record(e.app.findCollectionByNameOrId("memberships"))
  membership.set("team", e.record.id)
  membership.set("user", e.record.getString("owner"))
  membership.set("role", "owner")
  e.app.save(membership)
  e.next()
}, "teams")

// Owner and billing fields are set by the server only (billing webhook or dashboard).
onRecordUpdateRequest((e) => {
  if (!e.hasSuperuserAuth()) {
    const original = e.record.original()
    for (const field of ["owner", "plan", "subscription_status", "current_period_end"]) {
      if (original.getString(field) !== e.record.getString(field)) {
        throw new ForbiddenError(`"${field}" can only be changed by the server.`)
      }
    }
  }
  e.next()
}, "teams")

// ---------------------------------------------------------------------------
// Memberships
// ---------------------------------------------------------------------------

onRecordUpdateRequest((e) => {
  if (!e.hasSuperuserAuth()) {
    const original = e.record.original()
    if (
      original.getString("team") !== e.record.getString("team") ||
      original.getString("user") !== e.record.getString("user")
    ) {
      throw new BadRequestError("Only the role of a membership can change.")
    }
    if (original.getString("role") === "owner" || e.record.getString("role") === "owner") {
      throw new ForbiddenError("Team ownership can't be changed through memberships.")
    }
  }
  e.next()
}, "memberships")

onRecordDeleteRequest((e) => {
  if (!e.hasSuperuserAuth() && e.record.getString("role") === "owner") {
    throw new ForbiddenError("The team owner can't be removed from the team.")
  }
  e.next()
}, "memberships")

// ---------------------------------------------------------------------------
// Invites
// ---------------------------------------------------------------------------

// Only the team owner can invite. The token is generated here and never returned by the API.
onRecordCreateRequest((e) => {
  if (!e.hasSuperuserAuth()) {
    if (!e.auth) throw new UnauthorizedError("Sign in to invite people.")
    let team
    try {
      team = e.app.findRecordById("teams", e.record.getString("team"))
    } catch (_) {
      throw new BadRequestError("Team not found.")
    }
    if (team.getString("owner") !== e.auth.id) {
      throw new ForbiddenError("Only the team owner can invite people.")
    }
    e.record.set("invited_by", e.auth.id)
  }
  if (e.record.getString("role") === "owner") {
    throw new BadRequestError("Invite people as admin or member.")
  }
  e.record.set("email", e.record.getString("email").trim().toLowerCase())
  e.record.set("token", $security.randomString(40))
  e.record.set("accepted", false)
  e.next()
}, "invites")

// Email the invite link. Set "Application URL" and SMTP in the dashboard settings.
onRecordAfterCreateSuccess((e) => {
  const esc = (s) =>
    String(s).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;")
  try {
    const team = e.app.findRecordById("teams", e.record.getString("team"))
    const meta = e.app.settings().meta
    const link = `${meta.appURL}/invite/${e.record.getString("token")}`
    e.app.newMailClient().send(
      new MailerMessage({
        from: { address: meta.senderAddress, name: meta.senderName },
        to: [{ address: e.record.getString("email") }],
        subject: `You're invited to join ${team.getString("name")}`,
        html:
          `<p>You've been invited to join <b>${esc(team.getString("name"))}</b>.</p>` +
          `<p><a href="${esc(link)}">Accept the invite</a></p>`,
      }),
    )
  } catch (err) {
    e.app.logger().error("Invite email failed", "invite", e.record.id, "error", String(err))
  }
  e.next()
}, "invites")

// POST /api/invites/{token}/accept  (signed in, verified email that matches the invite)
routerAdd(
  "POST",
  "/api/invites/{token}/accept",
  (e) => {
    const token = e.request.pathValue("token")
    let invite
    try {
      invite = $app.findFirstRecordByFilter("invites", "token = {:token} && accepted = false", { token: token })
    } catch (_) {
      throw new NotFoundError("Invite not found or already used.")
    }
    if (!e.auth.verified()) {
      throw new ForbiddenError("Verify your email address before accepting an invite.")
    }
    if (invite.getString("email") !== e.auth.email().toLowerCase()) {
      throw new ForbiddenError("This invite was sent to a different email address.")
    }

    $app.runInTransaction((txApp) => {
      const teamId = invite.getString("team")
      const existing = txApp.countRecords("memberships", $dbx.hashExp({ team: teamId, user: e.auth.id }))
      if (existing === 0) {
        const membership = new Record(txApp.findCollectionByNameOrId("memberships"))
        membership.set("team", teamId)
        membership.set("user", e.auth.id)
        membership.set("role", invite.getString("role") || "member")
        txApp.save(membership)
      }
      invite.set("accepted", true)
      txApp.save(invite)
    })

    return e.json(200, { team: invite.getString("team") })
  },
  $apis.requireAuth(),
)

// ---------------------------------------------------------------------------
// Billing webhook
// ---------------------------------------------------------------------------

// POST /api/billing/webhook
// Header:  X-Webhook-Secret: <BILLING_WEBHOOK_SECRET>
// Body:    { "team_id": "...", "plan": "pro", "status": "active", "current_period_end": "2027-01-01 00:00:00Z" }
// Call it from your payment provider's webhook handler after you verify the provider's signature.
routerAdd("POST", "/api/billing/webhook", (e) => {
  const secret = $os.getenv("BILLING_WEBHOOK_SECRET")
  const given = e.request.header.get("X-Webhook-Secret")
  if (!secret || !$security.equal(given, secret)) {
    throw new UnauthorizedError("Invalid webhook secret.")
  }

  const body = e.requestInfo().body || {}
  let team
  try {
    team = $app.findRecordById("teams", String(body.team_id || ""))
  } catch (_) {
    throw new NotFoundError("Team not found.")
  }

  if (body.plan) team.set("plan", body.plan)
  if (body.status) team.set("subscription_status", body.status)
  if (body.current_period_end !== undefined) team.set("current_period_end", body.current_period_end)
  $app.save(team)

  return e.json(200, { ok: true })
})