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:
@@ -2,10 +2,12 @@ package api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/apierror"
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/auth"
|
||||
@@ -25,6 +27,27 @@ func requireUser(w http.ResponseWriter, r *http.Request) (dbq.User, bool) {
|
||||
return user, true
|
||||
}
|
||||
|
||||
// minPasswordLength is the shortest password any account may set: at
|
||||
// sign-up, on reset, on change, and when an admin sets one.
|
||||
const minPasswordLength = 8
|
||||
|
||||
// checkNewPassword answers 400 password_too_short and returns false when pw
|
||||
// is too short to set. Every path that sets a password calls it, so the
|
||||
// rule lives in one place.
|
||||
func checkNewPassword(w http.ResponseWriter, pw string) bool {
|
||||
if len(pw) < minPasswordLength {
|
||||
writeErr(w, apierror.BadRequest("password_too_short",
|
||||
fmt.Sprintf("password must be at least %d characters", minPasswordLength)))
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// hashPassword is the one place a password is hashed for storage.
|
||||
func hashPassword(pw string) ([]byte, error) {
|
||||
return bcrypt.GenerateFromPassword([]byte(pw), bcrypt.DefaultCost)
|
||||
}
|
||||
|
||||
// requireURLUUID parses the chi URL parameter named key as a UUID. On
|
||||
// invalid input, writes a 400 envelope and returns ok=false; the caller
|
||||
// MUST return immediately on ok=false.
|
||||
|
||||
Reference in New Issue
Block a user