add auth
This commit is contained in:
@@ -0,0 +1,56 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
// CookieName is the single httpOnly cookie that carries the JWT.
|
||||
const CookieName = "spsays_auth"
|
||||
|
||||
// CookieOptions captures the per-environment knobs for the auth cookie.
|
||||
type CookieOptions struct {
|
||||
Domain string // empty in dev; ".prabhupadasays.org" in prod for subdomain sharing
|
||||
Secure bool // true in production (HTTPS-only)
|
||||
}
|
||||
|
||||
// Set writes the JWT into a Secure, httpOnly, SameSite=Lax cookie.
|
||||
// SameSite=Lax + same-registrable-domain (prabhupadasays.org / api.prabhupadasays.org)
|
||||
// is enough for cross-subdomain auth without resorting to SameSite=None.
|
||||
func Set(w http.ResponseWriter, token string, expires time.Time, opts CookieOptions) {
|
||||
http.SetCookie(w, &http.Cookie{
|
||||
Name: CookieName,
|
||||
Value: token,
|
||||
Path: "/",
|
||||
Domain: opts.Domain,
|
||||
Expires: expires,
|
||||
MaxAge: int(time.Until(expires).Seconds()),
|
||||
HttpOnly: true,
|
||||
Secure: opts.Secure,
|
||||
SameSite: http.SameSiteLaxMode,
|
||||
})
|
||||
}
|
||||
|
||||
// Clear overwrites the auth cookie with an immediately-expired one.
|
||||
func Clear(w http.ResponseWriter, opts CookieOptions) {
|
||||
http.SetCookie(w, &http.Cookie{
|
||||
Name: CookieName,
|
||||
Value: "",
|
||||
Path: "/",
|
||||
Domain: opts.Domain,
|
||||
Expires: time.Unix(0, 0),
|
||||
MaxAge: -1,
|
||||
HttpOnly: true,
|
||||
Secure: opts.Secure,
|
||||
SameSite: http.SameSiteLaxMode,
|
||||
})
|
||||
}
|
||||
|
||||
// Read pulls the raw JWT out of the request cookie. Returns "" if missing.
|
||||
func Read(r *http.Request) string {
|
||||
c, err := r.Cookie(CookieName)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
return c.Value
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
// Package auth provides JWT issuance + verification for the BFF.
|
||||
//
|
||||
// Tokens carry these claims:
|
||||
//
|
||||
// sub user id (UUID string)
|
||||
// tv token_version snapshot — middleware rejects if it doesn't match the
|
||||
// current value on the user row. Bumping the user's token_version
|
||||
// invalidates every JWT ever issued to that user (used on password
|
||||
// change and forced logout).
|
||||
// iat issued-at
|
||||
// exp expiry
|
||||
package auth
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
)
|
||||
|
||||
// Claims is the JWT payload we sign + verify.
|
||||
type Claims struct {
|
||||
UserID string `json:"sub"`
|
||||
TokenVersion int `json:"tv"`
|
||||
jwt.RegisteredClaims
|
||||
}
|
||||
|
||||
// Issuer issues and verifies tokens with a single shared HMAC secret.
|
||||
type Issuer struct {
|
||||
secret []byte
|
||||
ttl time.Duration
|
||||
}
|
||||
|
||||
// NewIssuer returns an Issuer configured with the given HMAC secret and TTL.
|
||||
// The TTL is applied to every token issued via Issue().
|
||||
func NewIssuer(secret string, ttl time.Duration) *Issuer {
|
||||
return &Issuer{secret: []byte(secret), ttl: ttl}
|
||||
}
|
||||
|
||||
// Issue mints a signed JWT for the given user.
|
||||
func (i *Issuer) Issue(userID string, tokenVersion int) (string, time.Time, error) {
|
||||
exp := time.Now().Add(i.ttl)
|
||||
claims := &Claims{
|
||||
UserID: userID,
|
||||
TokenVersion: tokenVersion,
|
||||
RegisteredClaims: jwt.RegisteredClaims{
|
||||
IssuedAt: jwt.NewNumericDate(time.Now()),
|
||||
ExpiresAt: jwt.NewNumericDate(exp),
|
||||
},
|
||||
}
|
||||
tok := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
||||
signed, err := tok.SignedString(i.secret)
|
||||
if err != nil {
|
||||
return "", time.Time{}, fmt.Errorf("sign jwt: %w", err)
|
||||
}
|
||||
return signed, exp, nil
|
||||
}
|
||||
|
||||
// ErrInvalidToken is returned by Parse for any verification failure.
|
||||
var ErrInvalidToken = errors.New("invalid or expired token")
|
||||
|
||||
// Parse validates the token's signature + expiry and returns the claims.
|
||||
// Callers must additionally compare claims.TokenVersion against the user's
|
||||
// current token_version (the JWT alone can't tell us whether the user has
|
||||
// since bumped their version).
|
||||
func (i *Issuer) Parse(raw string) (*Claims, error) {
|
||||
claims := &Claims{}
|
||||
tok, err := jwt.ParseWithClaims(raw, claims, func(t *jwt.Token) (any, error) {
|
||||
if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {
|
||||
return nil, fmt.Errorf("unexpected signing method: %v", t.Header["alg"])
|
||||
}
|
||||
return i.secret, nil
|
||||
})
|
||||
if err != nil || !tok.Valid {
|
||||
return nil, ErrInvalidToken
|
||||
}
|
||||
return claims, nil
|
||||
}
|
||||
|
||||
// TTL returns the configured token lifetime. Handlers use it to set cookie
|
||||
// Max-Age so the cookie and the JWT expire in lockstep.
|
||||
func (i *Issuer) TTL() time.Duration { return i.ttl }
|
||||
@@ -0,0 +1,103 @@
|
||||
// Package mailer is a thin SMTP wrapper used by the auth flows.
|
||||
//
|
||||
// The stdlib `net/smtp` is sufficient for our needs (password reset +
|
||||
// email verification — low volume, plain-MIME). We keep one interface
|
||||
// (Mailer) so handlers can be tested with an in-memory implementation
|
||||
// and so we can swap to a transactional provider later (Resend, SES)
|
||||
// without touching the call sites.
|
||||
package mailer
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/smtp"
|
||||
"strings"
|
||||
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
// Mailer is the small surface auth services depend on.
|
||||
type Mailer interface {
|
||||
Send(to, subject, htmlBody string) error
|
||||
}
|
||||
|
||||
// Config carries the per-environment SMTP knobs.
|
||||
type Config struct {
|
||||
Host string
|
||||
Port int
|
||||
Username string
|
||||
Password string
|
||||
From string // "Name <addr@host>" or just "addr@host"
|
||||
}
|
||||
|
||||
// Configured returns true if enough SMTP creds are present to send mail.
|
||||
// Used by the auth service to decide whether to send-or-log.
|
||||
func (c Config) Configured() bool { return c.Host != "" && c.From != "" }
|
||||
|
||||
// SMTP is the production Mailer. Connects per call (low volume → fine).
|
||||
type SMTP struct {
|
||||
cfg Config
|
||||
logger *zap.Logger
|
||||
}
|
||||
|
||||
// New returns an SMTP mailer if creds are present, otherwise a NoopLogger
|
||||
// that logs the message body to zap (useful in dev — the password-reset
|
||||
// link shows up in your server logs).
|
||||
func New(cfg Config, logger *zap.Logger) Mailer {
|
||||
if !cfg.Configured() {
|
||||
logger.Warn("SMTP not configured — mailer will log messages instead of sending")
|
||||
return &NoopLogger{logger: logger}
|
||||
}
|
||||
return &SMTP{cfg: cfg, logger: logger}
|
||||
}
|
||||
|
||||
// Send delivers a single HTML email. Plain-text alternative is omitted —
|
||||
// the templates are short and modern clients render HTML fine.
|
||||
func (m *SMTP) Send(to, subject, htmlBody string) error {
|
||||
addr := fmt.Sprintf("%s:%d", m.cfg.Host, m.cfg.Port)
|
||||
auth := smtp.PlainAuth("", m.cfg.Username, m.cfg.Password, m.cfg.Host)
|
||||
|
||||
var msg strings.Builder
|
||||
msg.WriteString("From: ")
|
||||
msg.WriteString(m.cfg.From)
|
||||
msg.WriteString("\r\n")
|
||||
msg.WriteString("To: ")
|
||||
msg.WriteString(to)
|
||||
msg.WriteString("\r\n")
|
||||
msg.WriteString("Subject: ")
|
||||
msg.WriteString(subject)
|
||||
msg.WriteString("\r\n")
|
||||
msg.WriteString("MIME-Version: 1.0\r\n")
|
||||
msg.WriteString("Content-Type: text/html; charset=UTF-8\r\n\r\n")
|
||||
msg.WriteString(htmlBody)
|
||||
|
||||
// Most relays on port 587 want STARTTLS + AUTH. Port 465 = implicit TLS,
|
||||
// not handled here — add only if needed.
|
||||
if err := smtp.SendMail(addr, auth, fromAddr(m.cfg.From), []string{to}, []byte(msg.String())); err != nil {
|
||||
return fmt.Errorf("smtp send: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// fromAddr extracts the bare address from a "Name <addr>" string. SendMail's
|
||||
// `from` argument is the envelope-from, which must be the bare address.
|
||||
func fromAddr(s string) string {
|
||||
if i := strings.LastIndex(s, "<"); i >= 0 {
|
||||
if j := strings.LastIndex(s, ">"); j > i {
|
||||
return s[i+1 : j]
|
||||
}
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// NoopLogger satisfies Mailer by writing the message into the application
|
||||
// logger. Use it in development so you can copy reset links from the console.
|
||||
type NoopLogger struct{ logger *zap.Logger }
|
||||
|
||||
func (n *NoopLogger) Send(to, subject, htmlBody string) error {
|
||||
n.logger.Info("📧 mailer (not sent — SMTP unconfigured)",
|
||||
zap.String("to", to),
|
||||
zap.String("subject", subject),
|
||||
zap.String("body", htmlBody))
|
||||
return nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user