Single-use reset tokens stored as hashes, short expiry, the same response for every address, revoking sessions after the change, and a Go example on Encore with Postgres and Pub/Sub.

A password reset flow is an account takeover path every app ships deliberately: whoever controls the link controls the account. The mistakes that matter are small, such as a plaintext token, a link valid for a week, an error that confirms an address exists or sessions that survive the reset.
This guide walks through each decision and ends with a Go service using Postgres, a queue for the email and bcrypt.
The user submits an email address and always gets the same answer. If the address matches an account, the backend creates a random token, stores its hash with an expiry and queues an email with a link to the reset page. The page posts the token and the new password back, and the backend claims the token, stores the new password hash and ends the user's existing sessions in one transaction.
The OWASP Forgot Password Cheat Sheet covers the same steps and adds two that are easy to miss: return a consistent message for existing and missing accounts, and keep the response time consistent too, which in practice means doing the slow work (sending email) outside the request.
Use 32 bytes from crypto/rand, encoded with base64url, so the token is unguessable and safe in a URL. Store only a SHA-256 hash in the database, the same way you would never store the password itself, so a database dump does not contain working reset links. Expire tokens after 15 to 60 minutes, mark them used in the statement that validates them, and invalidate older unused tokens when a new one is issued so only the latest email works.
Put the token in the URL fragment (/reset#token=...) rather than the query string. Fragments are never sent to the server, so the token stays out of access logs and proxies, and the reset page reads it with JavaScript and sends it in a POST body together with the new password.
Hash it with a slow, salted algorithm. The OWASP Password Storage Cheat Sheet recommends Argon2id and accepts bcrypt with a work factor of 10 or more, and Go's bcrypt package rejects passwords longer than 72 bytes instead of silently truncating them. For length rules, NIST SP 800-63B favours a minimum length and a check against known breached passwords over composition rules like "one symbol and one digit".
After the change, delete the user's sessions and refresh tokens. If the reset happened because someone else had access, their session should not survive it, and the user signs in again with the new password on their own device.
Reset emails cost money and land in someone's inbox, so cap them per account (for example three per hour) and per IP at the edge, and keep returning the generic response when the cap is hit. Log every request and every completed reset with the user ID, since a burst of resets against one account is a signal worth alerting on.
Encore is a backend framework with built-in infrastructure, so the reset table, the email queue and the provider key are declared in the Go service that uses them. Tokens, users and sessions live in an Encore Postgres database, the email goes through a Pub/Sub topic so the request returns in constant time, and the email provider key is an Encore secret. On deploy, Encore provisions the database and topic in your own AWS or GCP account. Encore provisions an IAM role for the service, or a service account on GCP.
Run in your terminal to get started locally.
-- auth/migrations/1_create_auth.up.sql
CREATE TABLE users (
id BIGSERIAL PRIMARY KEY,
email TEXT NOT NULL UNIQUE,
password_hash TEXT NOT NULL
);
CREATE TABLE password_resets (
token_hash TEXT PRIMARY KEY,
user_id BIGINT NOT NULL REFERENCES users (id),
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
expires_at TIMESTAMPTZ NOT NULL,
used_at TIMESTAMPTZ
);
CREATE INDEX password_resets_user ON password_resets (user_id, created_at);
CREATE TABLE sessions (
token_hash TEXT PRIMARY KEY,
user_id BIGINT NOT NULL REFERENCES users (id),
expires_at TIMESTAMPTZ NOT NULL
);
// auth/reset.go
package auth
import (
"bytes"
"context"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"net/http"
"strings"
"encore.dev/beta/errs"
"encore.dev/pubsub"
"encore.dev/storage/sqldb"
"golang.org/x/crypto/bcrypt"
)
var db = sqldb.NewDatabase("auth", sqldb.DatabaseConfig{Migrations: "./migrations"})
var secrets struct {
ResendAPIKey string
}
type ResetEmail struct {
Email string
Token string
}
var ResetEmails = pubsub.NewTopic[*ResetEmail]("password-reset-emails", pubsub.TopicConfig{
DeliveryGuarantee: pubsub.AtLeastOnce,
})
func hashToken(t string) string {
sum := sha256.Sum256([]byte(t))
return hex.EncodeToString(sum[:])
}
type RequestResetParams struct {
Email string
}
// RequestReset always returns nil, so the response never reveals whether an account exists.
//
//encore:api public method=POST path=/auth/password-reset
func RequestReset(ctx context.Context, p *RequestResetParams) error {
email := strings.ToLower(strings.TrimSpace(p.Email))
var userID int64
err := db.QueryRow(ctx, `SELECT id FROM users WHERE email = $1`, email).Scan(&userID)
if errors.Is(err, sqldb.ErrNoRows) {
return nil
} else if err != nil {
return err
}
var recent int
if err := db.QueryRow(ctx, `SELECT count(*) FROM password_resets
WHERE user_id = $1 AND created_at > now() - interval '1 hour'`, userID).Scan(&recent); err != nil {
return err
}
if recent >= 3 {
return nil
}
raw := make([]byte, 32)
if _, err := rand.Read(raw); err != nil {
return err
}
token := base64.RawURLEncoding.EncodeToString(raw)
tx, err := db.Begin(ctx)
if err != nil {
return err
}
defer tx.Rollback()
if _, err := tx.Exec(ctx, `UPDATE password_resets SET used_at = now()
WHERE user_id = $1 AND used_at IS NULL`, userID); err != nil {
return err
}
if _, err := tx.Exec(ctx, `INSERT INTO password_resets (token_hash, user_id, expires_at)
VALUES ($1, $2, now() + interval '30 minutes')`, hashToken(token), userID); err != nil {
return err
}
if err := tx.Commit(); err != nil {
return err
}
_, err = ResetEmails.Publish(ctx, &ResetEmail{Email: email, Token: token})
return err
}
type ConfirmResetParams struct {
Token string
NewPassword string
}
//encore:api public method=POST path=/auth/password-reset/confirm
func ConfirmReset(ctx context.Context, p *ConfirmResetParams) error {
if len(p.NewPassword) < 12 {
return &errs.Error{Code: errs.InvalidArgument, Message: "password must be at least 12 characters"}
}
hash, err := bcrypt.GenerateFromPassword([]byte(p.NewPassword), 12)
if err != nil {
return &errs.Error{Code: errs.InvalidArgument, Message: "password must be at most 72 bytes"}
}
tx, err := db.Begin(ctx)
if err != nil {
return err
}
defer tx.Rollback()
var userID int64
err = tx.QueryRow(ctx, `UPDATE password_resets SET used_at = now()
WHERE token_hash = $1 AND used_at IS NULL AND expires_at > now()
RETURNING user_id`, hashToken(p.Token)).Scan(&userID)
if errors.Is(err, sqldb.ErrNoRows) {
return &errs.Error{Code: errs.InvalidArgument, Message: "reset link is invalid or expired"}
} else if err != nil {
return err
}
if _, err := tx.Exec(ctx, `UPDATE users SET password_hash = $1 WHERE id = $2`, string(hash), userID); err != nil {
return err
}
if _, err := tx.Exec(ctx, `DELETE FROM sessions WHERE user_id = $1`, userID); err != nil {
return err
}
return tx.Commit()
}
var _ = pubsub.NewSubscription(ResetEmails, "send-reset-email", pubsub.SubscriptionConfig[*ResetEmail]{
Handler: sendResetEmail,
})
func sendResetEmail(ctx context.Context, m *ResetEmail) error {
link := "https://app.example.com/reset#token=" + m.Token
body, _ := json.Marshal(map[string]any{
"from": "Example <security@example.com>",
"to": m.Email,
"subject": "Reset your password",
"html": `<p><a href="` + link + `">Choose a new password</a>. The link expires in 30 minutes.</p>`,
})
req, err := http.NewRequestWithContext(ctx, "POST", "https://api.resend.com/emails", bytes.NewReader(body))
if err != nil {
return err
}
req.Header.Set("Authorization", "Bearer "+secrets.ResendAPIKey)
req.Header.Set("Content-Type", "application/json")
resp, err := http.DefaultClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode >= 300 {
return fmt.Errorf("email provider returned %d", resp.StatusCode)
}
return nil
}
Set the key with encore secret set --type dev,local ResendAPIKey and again with --type prod, then encore run starts Postgres locally and applies the migration. A failed send returns an error, so Pub/Sub retries it with backoff, and the bcrypt hashing runs before the transaction opens so a slow hash never holds row locks. Each reset request, email send and confirm call appears in a trace with the user ID in the logs, which gives you the audit trail for "I never asked for this email" support tickets.
An agent extending this flow, for example to also revoke API tokens on reset, makes that change in the same transaction and the same file, and can run the full request-to-confirm path locally before opening a pull request.
Best fit: Apps that keep their own user table and want reset tokens, sessions and the email queue in their own Postgres database and cloud account.
Keep it short, usually 15 to 60 minutes, and make it single use. The token is a bearer credential for the account until it expires, so a short window limits what a leaked email or browser history can do.
No. Return the same message for every address, such as "If an account exists, we sent a link", and send the email asynchronously so response times do not differ either. Anything else lets an attacker check which addresses have accounts.
Yes, in most apps. A reset often follows a suspected compromise, so delete or expire the user's other sessions and refresh tokens in the same transaction that stores the new password hash.
Store hashed reset tokens in an Encore Postgres database, publish the email to a Pub/Sub topic from the request endpoint and send it from a subscriber. The confirm endpoint claims the token, stores the new bcrypt hash and deletes the user's sessions in one transaction.
Deploy to your cloud on AWS and Google Cloud
without managing infrastructure
Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.