Email and password
23 files5 packagesNo dependencies
This pack adds email and password authentication to your API as JSON endpoints. It fits the guard your app already authenticates with, access tokens or session, enhancing your existing login and signup rather than replacing them. Every new account confirms its email address before it is treated as active.
- Email verification for new signups, with a resend endpoint and a
403on unverified access. - Rate-limited login that penalises repeated failed attempts, and a throttled signup.
- Password and email rules that you choose, with an endpoint that serves the password policy to your clients.
- A branded, MJML-based confirmation email that links to your frontend.
Apply the authentication pack with Flow. Start a new session in your selected coding agent and execute the following slash command inside it.
$ npx @adonisplus/flow apply --pack=auth --agent=claude
$ npx @adonisplus/flow apply --pack=auth --agent=codex
$ npx @adonisplus/flow apply --pack=auth --agent=cursor
$ npx @adonisplus/flow apply --pack=auth --agent=opencode
After applying, Flow will make the following changes to your app:
- Discover your default guard, access tokens or session, and enhance the login and signup controllers you already have.
- Land the backend as shipped, from the migrations and model mixin through the validators, the email-verifications controller, routes, middleware, and mailer.
- Configure mail and the limiter, install Edge for the email templates, and point the verification link at your
FRONTEND_URL. - Run the tests, drive the endpoints, and hand you a brief for the frontend to build against.
Delta will differ
Flow adapts the pack to your app, so the exact set of created and edited files depends on what you already have, including which guard you authenticate with. This is the shape of an apply onto the API starter kit.
Migrations
xxxx_add_unverified_email_to_users.tsdatabase/migrations/xxxx_add_unverified_email_to_users.tsAdds theunverified_emailcolumn to the users table.createdxxxx_create_email_verification_tokens.tsdatabase/migrations/xxxx_create_email_verification_tokens.tsCreates theemail_verification_tokenstable.created
Model
user.tsapp/models/user.tsAdds thewithManagedEmail()mixin.edited
Validators
user.tsapp/validators/user.tsAdds the login and signup validators.editedpassword_policy.tsapp/validators/password_policy.tsThe password policy, with the rules you chose.created
Controllers & responses
email_verifications_controller.tsapp/controllers/email_verifications_controller.tsResends the activation email and consumes the verification token, answering204.createdsession_controller.tsapp/controllers/session_controller.tsAdds the rate-limited login and theauthenticatedstatus. For a token guard, this lands on your access-token controller instead.editednew_account_controller.tsapp/controllers/new_account_controller.tsSets the unverified email, mints a token, sends the activation email, and answers201.editedpassword_policy_controller.tsapp/controllers/password_policy_controller.tsServes the password policy as JSON.createduser_transformer.tsapp/transformers/user_transformer.tsExposesunverifiedEmailin the serialized user.edited
Middleware
verified_account_middleware.tsapp/middleware/verified_account_middleware.tsAnswers403with anunverified_emailerror for unverified accounts.created
Mailers & email templates
account_activation_provision.tsapp/mails/account_activation_provision.tsThe activation email, linking to yourFRONTEND_URL.createdemail_layout.edgeresources/views/components/email_layout.edgeShared MJML layout for the emails.createdaccount_activation.edgeresources/views/emails/account_activation.edgeBody of the activation email.created
Routes & config
routes.tsstart/routes.tsAdds the verification and password-policy routes, and throttles signup.editedmail.tsconfig/mail.tsMail configuration, with thebrandNameglobal and thefromaddress.createdlimiter.tsstart/limiter.tsLimiter configuration, with theformsThrottledefinition.createdapp.tsconfig/app.tsExposesappFrontendUrlfromFRONTEND_URL.editedenv.tsstart/env.tsValidates theFRONTEND_URLenvironment variable.edited
Factories & tests
user_factory.tsdatabase/factories/user_factory.tsUser factory with averifiedstate for the tests.createdlogin.spec.tstests/functional/auth/login.spec.tsLogin and logout specs for your guard.createdsignup.spec.tstests/functional/auth/signup.spec.tsSignup specs for your guard.createdemail_verification.spec.tstests/functional/auth/email_verification.spec.tsEmail verification specs.created
Configuration
Section titled "Configuration"Verification is backed by the withManagedEmail() mixin on the User model, which stores each token in a database table. Pass an options object to the mixin to change its defaults.
expiresInstring | number1 day.tablestringemail_verification_tokens.tokenSecretLengthnumber40.export default class User extends compose(
UserSchema,
withAuthFinder(hash),
withManagedEmail({ expiresIn: '2 hours' })
) {}Password policy
Section titled "Password policy"Flow asks which password and email rules you want before it writes the validators. It records the password rules as one policy in app/validators/password_policy.ts. The signup validator checks each new password against it, and each later endpoint that sets a password reuses it. The login validator checks only the format, so accounts made before the rules can still log in.
minLengthnumber8.maxLengthnumber32. Keep it generous, so passphrases and password managers are not cut off.minScorenumber0 to 4, estimated from its length and the variety of its characters. Defaults to 0, which turns the check off.lettersbooleanfalse.mixedCasebooleanfalse.numbersbooleanfalse.symbolsboolean!, #, or a space. Defaults to false.export const passwordPolicy = definePasswordPolicy({
minLength: 8,
maxLength: 32,
minScore: 3,
})Two more checks are rules on the validator. Both are off by default.
- The leaked-password check,
uncompromised(), rejects a password that appears in a known data leak. It asks the Have I Been Pwned service, and only the first five characters of the password hash leave the server. When the service cannot be reached, the password is accepted. - The disposable-email check,
nonDisposable(), rejects a signup email from a throwaway provider. It uses a list in the package and makes no outgoing request. Existing users with such an address can still log in.
const newEmail = () => email().nonDisposable()
const password = () => vine.string().passwordPolicy(passwordPolicy).uncompromised() Password policy endpoint
Section titled "Password policy endpoint"GET /password-policy returns the policy as JSON. The route is public, because guests need it on the signup screen. A client passes the data value to checkPassword(password, policy) from @adonisplus/persona/password_policy, which returns the strength score and the state of each rule. The leaked-password check runs only on the server, so the client still handles a 422.
Verification is two email columns, not a boolean
Section titled "Verification is two email columns, not a boolean"The mixin tracks verification with two columns:
emailis the confirmed address.unverifiedEmailis one still waiting on confirmation.
Signup writes the same value to both, so the two agree and the account reads as unverified. Confirming the address moves it into email and clears unverifiedEmail, so they diverge and the account reads as active. hasInactiveAccount exposes this state, and VerifiedAccountMiddleware gates on it.
Verification tokens
Section titled "Verification tokens"Tokens live in the email_verification_tokens table, one row per outstanding token, linked to the user by tokenable_id. The mixin generates a token when you ask for one and verifies it when the link comes back, storing only its hash so a leaked row cannot be turned back into a working link.
Resend throttling
Section titled "Resend throttling"Resending is throttled to one token a minute. Inside that window the endpoint does nothing and answers exactly as it would have, so the timing stays invisible to callers.
Rate-limited credentials
Section titled "Rate-limited credentials"Login runs the credential check through two limiter keys:
- one scoped per IP, and
- a stricter one per IP-and-email that adds a 20-minute block after five failures, which slows a targeted guess at a single account.
Both run through penalize, which spends the budget only when credentials fail, so a valid login is always free.
const ipKey = `login_${request.ip()}`
const emailKey = `login_${request.ip()}_${payload.email}`
const loginLimiter = limiter.multi([
{ duration: '1 min', requests: 10, key: ipKey },
{ duration: '1 min', requests: 5, blockDuration: '20 mins', key: emailKey },
])
const [error, user] = await loginLimiter.penalize(() => {
return User.verifyCredentials(payload.email, payload.password)
})Signup takes a simpler guard, formsThrottle, a named limiter capped at ten requests a minute per route and IP.
export const formsThrottle = limiter.define('forms', (ctx) => {
return limiter
.allowRequests(10)
.every('1 minute')
.usingKey(`${ctx.route?.name ?? 'global'}_${ctx.request.ip()}`)
})Flow 1.1.0
Section titled "Flow 1.1.0"- Setup now runs
node ace configure @adonisplus/persona, which registers Persona's password and email validation rules with VineJS. Before, the pack skipped this step. - The tests now use the route names of the API starter kit, so they pass in a fresh app.
Flow 0.2.0
Section titled "Flow 0.2.0"- Added the pack.