Files
minstrel/internal/api/me_password.go
T
bvandeusen 965df28127 refactor(server): audit.WriteOrLog wrapper; migrate 13 sites (T5)
Add audit.WriteOrLog: a one-line wrapper around Write that logs at
Warn and swallows the error, matching the package contract that
audit failures must not break user-facing operations.

Migrate the 13 call sites across 7 files in internal/api/ from the
3-line "if err != nil { logger.Warn(...) }" shape to a single call.
audit.Write stays exported for tests + any future caller that
needs strict semantics.

Adds three tests: success (no log), failure-via-closed-pool (Warn
record with action+err keys), and nil-logger (no panic). Tests
skip when MINSTREL_TEST_DATABASE_URL is unset, matching the
existing harness convention.
2026-05-07 21:33:14 -04:00

70 lines
2.1 KiB
Go

package api
import (
"encoding/json"
"net/http"
"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/dbq"
)
type changePasswordReq struct {
CurrentPassword string `json:"current_password"`
NewPassword string `json:"new_password"`
}
// handleChangePassword implements PUT /api/me/password. Self-service:
// the caller proves they know their current password before they can
// set a new one. Distinct from the admin-driven reset path.
func (h *handlers) handleChangePassword(w http.ResponseWriter, r *http.Request) {
user, ok := auth.UserFromContext(r.Context())
if !ok {
writeErr(w, apierror.Unauthorized("auth_required", ""))
return
}
var req changePasswordReq
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeErr(w, apierror.BadRequest("invalid_body", ""))
return
}
if len(req.NewPassword) < minPasswordLength {
writeErr(w, apierror.BadRequest("password_too_short", "password must be at least 8 chars"))
return
}
q := dbq.New(h.pool)
current, err := q.GetUserByID(r.Context(), user.ID)
if err != nil {
h.logger.Error("change password: lookup failed", "err", err)
writeErr(w, apierror.Internal(err))
return
}
if err := bcrypt.CompareHashAndPassword([]byte(current.PasswordHash), []byte(req.CurrentPassword)); err != nil {
writeErr(w, apierror.Unauthorized("wrong_password", ""))
return
}
hash, err := bcrypt.GenerateFromPassword([]byte(req.NewPassword), bcrypt.DefaultCost)
if err != nil {
h.logger.Error("change password: hash failed", "err", err)
writeErr(w, apierror.Internal(err))
return
}
if err := q.ChangeUserPassword(r.Context(), dbq.ChangeUserPasswordParams{
ID: user.ID,
PasswordHash: string(hash),
}); err != nil {
h.logger.Error("change password: update failed", "err", err)
writeErr(w, apierror.Internal(err))
return
}
audit.WriteOrLog(r.Context(), h.pool, h.logger, user.ID, user.ID, audit.ActionPasswordChangeSelf, nil)
w.WriteHeader(http.StatusNoContent)
}