refactor(api): one password rule, one hash, one unique-violation check (#8002)

The length check and bcrypt call were copied into sign-up, reset,
change and both admin paths; the unique-violation test into three api
handlers and the library. checkNewPassword and hashPassword now sit in
api/prelude.go, and db.IsUniqueViolation serves api and library. The
taken-username and taken-email conflicts now carry a message.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-26 12:45:18 -05:00
co-authored by Claude Opus 5.5
parent cfdd6b916f
commit 074d9ffb0e
10 changed files with 66 additions and 55 deletions
+7 -12
View File
@@ -5,14 +5,12 @@ import (
"net/http"
"time"
"github.com/jackc/pgerrcode"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"golang.org/x/crypto/bcrypt"
"git.fabledsword.com/bvandeusen/minstrel/internal/apierror"
"git.fabledsword.com/bvandeusen/minstrel/internal/audit"
"git.fabledsword.com/bvandeusen/minstrel/internal/auth"
"git.fabledsword.com/bvandeusen/minstrel/internal/db"
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
)
@@ -146,12 +144,11 @@ func (h *handlers) handleAdminCreateUser(w http.ResponseWriter, r *http.Request)
writeErr(w, apierror.BadRequest("username_invalid", "username must be 3-32 chars, alphanumeric + underscore + hyphen"))
return
}
if len(req.Password) < minPasswordLength {
writeErr(w, apierror.BadRequest("password_too_short", "password must be at least 8 chars"))
if !checkNewPassword(w, req.Password) {
return
}
hash, err := bcrypt.GenerateFromPassword([]byte(req.Password), bcrypt.DefaultCost)
hash, err := hashPassword(req.Password)
if err != nil {
writeErrWithLog(w, h.logger, "admin create user: hash failed", apierror.Internal(err))
return
@@ -171,9 +168,8 @@ func (h *handlers) handleAdminCreateUser(w http.ResponseWriter, r *http.Request)
DisplayName: req.DisplayName,
})
if err != nil {
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) && pgErr.Code == pgerrcode.UniqueViolation {
writeErr(w, apierror.Conflict("username_taken", ""))
if db.IsUniqueViolation(err) {
writeErr(w, apierror.Conflict("username_taken", "username is already taken"))
return
}
writeErrWithLog(w, h.logger, "admin create user: insert failed", apierror.Internal(err))
@@ -252,8 +248,7 @@ func (h *handlers) handleAdminResetPassword(w http.ResponseWriter, r *http.Reque
if !decodeBody(w, r, &req) {
return
}
if len(req.Password) < minPasswordLength {
writeErr(w, apierror.BadRequest("password_too_short", "password must be at least 8 chars"))
if !checkNewPassword(w, req.Password) {
return
}
@@ -268,7 +263,7 @@ func (h *handlers) handleAdminResetPassword(w http.ResponseWriter, r *http.Reque
return
}
hash, err := bcrypt.GenerateFromPassword([]byte(req.Password), bcrypt.DefaultCost)
hash, err := hashPassword(req.Password)
if err != nil {
writeErrWithLog(w, h.logger, "admin reset password: hash failed", apierror.Internal(err))
return