User sign-up with email verification

Build a public sign-up endpoint, verify users' email addresses with one-time codes, and enable password reset.

Creating users needs an API key, so sign-up runs in a function. In this recipe you build:

  • POST /fn-execute/auth/sign-up: creates a user and returns a session.
  • POST /fn-execute/auth/email: sends a verification code to the user's email.
  • POST /fn-execute/auth/email/verify: confirms the code.
  • Password reset, which Spica serves directly once it is enabled.

1. Configure email

Start the API with SMTP settings (see Mailer & SMS):

Terminal
--mailer-host=smtp.example.com --mailer-port=587 \
--mailer-user=apikey --mailer-pass=<password> \
--mailer-from="Acme <no-reply@acme.com>"

Enable email verification and password reset in the user configuration, together with a password policy:

Terminal
curl -X PUT https://api.example.com/api/config/user \
  -H "Authorization: IDENTITY <token>" -H "Content-Type: application/json" \
  -d '{
    "password": {"minLength": 8, "minNumber": 1},
    "providerVerificationConfig": [{"provider": "email", "strategy": "Otp"}],
    "resetPasswordProvider": [{"provider": "email", "strategy": "Otp"}],
    "verificationProcessMaxAttempt": 5,
    "rateLimits": {"createUser": {"limit": 20, "ttl": 60}, "providerVerification": {"limit": 5, "ttl": 300}}
  }'

2. Create an API key for the function

Create an API key named Auth function with UserFullAccess, and store it as a secret named SPICA_API_KEY.

3. Write the function

function/auth/schema.yaml
name: auth
description: Public sign-up and email verification
language: javascript
timeout: 20
triggers:
  signUp:
    type: http
    active: true
    options:
      method: Post
      path: /auth/sign-up
      rateLimit: {limit: 10, ttl: 60000}
  sendEmailCode:
    type: http
    active: true
    options:
      method: Post
      path: /auth/email
      authenticate: [USER]
  verifyEmailCode:
    type: http
    active: true
    options:
      method: Post
      path: /auth/email/verify
      authenticate: [USER]
secrets: [<SPICA_API_KEY secret id>]
function/auth/package.json
{"name": "auth", "version": "0.0.1", "dependencies": {"@spica-devkit/auth": "^0.22.1"}}
function/auth/index.mjs
import * as Auth from "@spica-devkit/auth";

Auth.initialize({apikey: process.env.SPICA_API_KEY});

const EMAIL = /^[^@\s]+@[^@\s]+\.[^@\s]+$/;

export async function signUp(req, res) {
  const {email, password} = req.body ?? {};

  if (!EMAIL.test(email ?? "") || typeof password != "string" || password.length < 8) {
    return res.status(400).send({message: "A valid email and a password of at least 8 characters are required."});
  }

  try {
    const user = await Auth.signUp({username: email, password});
    const session = await Auth.signIn(email, password);
    return res.status(201).send({userId: user._id, token: session.token});
  } catch (error) {
    const status = error?.statusCode ?? error?.status ?? 500;
    return res.status(status == 400 ? 409 : 500).send({message: "Could not create the account."});
  }
}

async function currentUser(req) {
  const token = (req.headers.get("authorization") ?? "").replace(/^USER /, "");
  return Auth.verifyToken(token);
}

export async function sendEmailCode(req, res) {
  const user = await currentUser(req);
  await Auth.addEmail(user._id, user.username, "Otp");
  return {message: "Code sent"};
}

export async function verifyEmailCode(req, res) {
  const user = await currentUser(req);
  const {code} = req.body ?? {};
  try {
    return await Auth.verifyEmail(user._id, String(code), "Otp");
  } catch {
    return res.status(400).send({message: "Invalid or expired code."});
  }
}

Attaching an email to a user requires passport:user:update, which users don't have on themselves. The function checks the caller's token and then acts with its API key.

4. Use it from your app

JavaScript
const API = "https://api.example.com/api";

const {token} = await fetch(`${API}/fn-execute/auth/sign-up`, {
  method: "POST",
  headers: {"Content-Type": "application/json"},
  body: JSON.stringify({email: "grace@example.com", password: "graceHopper1"})
}).then(r => r.json());

await fetch(`${API}/fn-execute/auth/email`, {method: "POST", headers: {Authorization: `USER ${token}`}});

await fetch(`${API}/fn-execute/auth/email/verify`, {
  method: "POST",
  headers: {Authorization: `USER ${token}`, "Content-Type": "application/json"},
  body: JSON.stringify({code: "123456"})
});
JSON
{"userId": "6b0b529fa5611972c29c2700", "token": "eyJhbGciOiJIUzI1NiIs..."}

Signing up twice with the same email returns 409, and invalid input returns 400.

5. Password reset

With resetPasswordProvider configured, the app calls Spica directly, without a token:

JavaScript
await fetch(`${API}/passport/user/forgot-password/start`, {
  method: "POST",
  headers: {"Content-Type": "application/json"},
  body: JSON.stringify({username: "grace@example.com", provider: "email"})
});

await fetch(`${API}/passport/user/forgot-password/verify`, {
  method: "POST",
  headers: {"Content-Type": "application/json"},
  body: JSON.stringify({username: "grace@example.com", code: "123456", newPassword: "aNewPassword9", provider: "email"})
});

Next steps