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:
@@ -9,15 +9,13 @@ import (
|
||||
"regexp"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgerrcode"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"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"
|
||||
)
|
||||
|
||||
@@ -26,8 +24,6 @@ import (
|
||||
// the frontend for live validation.
|
||||
var usernameRe = regexp.MustCompile(`^[a-zA-Z0-9_-]{3,32}$`)
|
||||
|
||||
const minPasswordLength = 8
|
||||
|
||||
type registerReq struct {
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
@@ -80,8 +76,7 @@ func (h *handlers) handleRegister(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
|
||||
}
|
||||
|
||||
@@ -135,7 +130,7 @@ func (h *handlers) handleRegister(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
// Hash password.
|
||||
hash, err := bcrypt.GenerateFromPassword([]byte(req.Password), bcrypt.DefaultCost)
|
||||
hash, err := hashPassword(req.Password)
|
||||
if err != nil {
|
||||
h.logger.Error("register: hash password failed", "err", err)
|
||||
writeErr(w, apierror.Internal(err))
|
||||
@@ -158,8 +153,7 @@ func (h *handlers) handleRegister(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 {
|
||||
if db.IsUniqueViolation(err) {
|
||||
writeErr(w, apierror.Conflict("username_taken", "username is already taken"))
|
||||
return
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user