refactor(server/api): writeErr accepts error; migrate admin handlers (1/3)
Rewrite writeErr(w, err) to wrap *apierror.Error via apierror.From,
preserving the existing {"error": {"code", "message"}} wire envelope.
Add writeErrWithLog helper for 500-class errors that need an operator
log line. Migrate all 13 admin_*.go handler files (~76 call sites) to
the new signature; T3 will sweep the remaining api package.
The old 4-arg writeErr is removed, so non-admin call sites in
internal/api will not compile until T3 lands. This is by design — T2
and T3 are paired.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
+39
-52
@@ -12,6 +12,7 @@ import (
|
||||
"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/dbq"
|
||||
@@ -34,8 +35,7 @@ func (h *handlers) handleAdminListUsers(w http.ResponseWriter, r *http.Request)
|
||||
q := dbq.New(h.pool)
|
||||
rows, err := q.ListUsers(r.Context())
|
||||
if err != nil {
|
||||
h.logger.Error("admin: list users failed", "err", err)
|
||||
writeErr(w, http.StatusInternalServerError, "server_error", "")
|
||||
writeErrWithLog(w, h.logger, "admin: list users failed", apierror.Internal(err))
|
||||
return
|
||||
}
|
||||
out := make([]adminUserView, 0, len(rows))
|
||||
@@ -60,17 +60,17 @@ type updateUserAdminReq struct {
|
||||
func (h *handlers) handleUpdateUserAdmin(w http.ResponseWriter, r *http.Request) {
|
||||
caller, ok := auth.UserFromContext(r.Context())
|
||||
if !ok {
|
||||
writeErr(w, http.StatusUnauthorized, "auth_required", "")
|
||||
writeErr(w, apierror.Unauthorized("auth_required", ""))
|
||||
return
|
||||
}
|
||||
targetID, ok := parseUUID(chi.URLParam(r, "id"))
|
||||
if !ok {
|
||||
writeErr(w, http.StatusBadRequest, "invalid_id", "")
|
||||
writeErr(w, apierror.BadRequest("invalid_id", ""))
|
||||
return
|
||||
}
|
||||
var req updateUserAdminReq
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, "invalid_body", "")
|
||||
writeErr(w, apierror.BadRequest("invalid_body", ""))
|
||||
return
|
||||
}
|
||||
|
||||
@@ -86,8 +86,7 @@ func (h *handlers) handleUpdateUserAdmin(w http.ResponseWriter, r *http.Request)
|
||||
if !req.IsAdmin {
|
||||
count, err := q.CountAdmins(r.Context())
|
||||
if err != nil {
|
||||
h.logger.Error("admin: count admins failed", "err", err)
|
||||
writeErr(w, http.StatusInternalServerError, "server_error", "")
|
||||
writeErrWithLog(w, h.logger, "admin: count admins failed", apierror.Internal(err))
|
||||
return
|
||||
}
|
||||
// We need to know whether the target is currently an admin.
|
||||
@@ -95,13 +94,12 @@ func (h *handlers) handleUpdateUserAdmin(w http.ResponseWriter, r *http.Request)
|
||||
// allow it). If they ARE admin and they're the last one, refuse.
|
||||
current, err := q.GetUserByID(r.Context(), targetID)
|
||||
if err != nil {
|
||||
h.logger.Error("admin: get user failed", "err", err)
|
||||
writeErr(w, http.StatusInternalServerError, "server_error", "")
|
||||
writeErrWithLog(w, h.logger, "admin: get user failed", apierror.Internal(err))
|
||||
return
|
||||
}
|
||||
if current.IsAdmin && count <= 1 {
|
||||
writeErr(w, http.StatusConflict, "last_admin",
|
||||
"can't remove the last admin — promote someone else first")
|
||||
writeErr(w, apierror.Conflict("last_admin",
|
||||
"can't remove the last admin — promote someone else first"))
|
||||
return
|
||||
}
|
||||
}
|
||||
@@ -111,8 +109,7 @@ func (h *handlers) handleUpdateUserAdmin(w http.ResponseWriter, r *http.Request)
|
||||
IsAdmin: req.IsAdmin,
|
||||
})
|
||||
if err != nil {
|
||||
h.logger.Error("admin: update user admin failed", "err", err)
|
||||
writeErr(w, http.StatusInternalServerError, "server_error", "")
|
||||
writeErrWithLog(w, h.logger, "admin: update user admin failed", apierror.Internal(err))
|
||||
return
|
||||
}
|
||||
|
||||
@@ -146,33 +143,31 @@ type adminCreateUserReq struct {
|
||||
func (h *handlers) handleAdminCreateUser(w http.ResponseWriter, r *http.Request) {
|
||||
caller, ok := auth.UserFromContext(r.Context())
|
||||
if !ok {
|
||||
writeErr(w, http.StatusUnauthorized, "auth_required", "")
|
||||
writeErr(w, apierror.Unauthorized("auth_required", ""))
|
||||
return
|
||||
}
|
||||
var req adminCreateUserReq
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, "invalid_body", "")
|
||||
writeErr(w, apierror.BadRequest("invalid_body", ""))
|
||||
return
|
||||
}
|
||||
if !usernameRe.MatchString(req.Username) {
|
||||
writeErr(w, http.StatusBadRequest, "username_invalid", "username must be 3-32 chars, alphanumeric + underscore + hyphen")
|
||||
writeErr(w, apierror.BadRequest("username_invalid", "username must be 3-32 chars, alphanumeric + underscore + hyphen"))
|
||||
return
|
||||
}
|
||||
if len(req.Password) < minPasswordLength {
|
||||
writeErr(w, http.StatusBadRequest, "password_too_short", "password must be at least 8 chars")
|
||||
writeErr(w, apierror.BadRequest("password_too_short", "password must be at least 8 chars"))
|
||||
return
|
||||
}
|
||||
|
||||
hash, err := bcrypt.GenerateFromPassword([]byte(req.Password), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
h.logger.Error("admin create user: hash failed", "err", err)
|
||||
writeErr(w, http.StatusInternalServerError, "server_error", "")
|
||||
writeErrWithLog(w, h.logger, "admin create user: hash failed", apierror.Internal(err))
|
||||
return
|
||||
}
|
||||
apiToken, err := auth.MintSessionToken()
|
||||
if err != nil {
|
||||
h.logger.Error("admin create user: mint token failed", "err", err)
|
||||
writeErr(w, http.StatusInternalServerError, "server_error", "")
|
||||
writeErrWithLog(w, h.logger, "admin create user: mint token failed", apierror.Internal(err))
|
||||
return
|
||||
}
|
||||
|
||||
@@ -187,11 +182,10 @@ func (h *handlers) handleAdminCreateUser(w http.ResponseWriter, r *http.Request)
|
||||
if err != nil {
|
||||
var pgErr *pgconn.PgError
|
||||
if errors.As(err, &pgErr) && pgErr.Code == pgerrcode.UniqueViolation {
|
||||
writeErr(w, http.StatusConflict, "username_taken", "")
|
||||
writeErr(w, apierror.Conflict("username_taken", ""))
|
||||
return
|
||||
}
|
||||
h.logger.Error("admin create user: insert failed", "err", err)
|
||||
writeErr(w, http.StatusInternalServerError, "server_error", "")
|
||||
writeErrWithLog(w, h.logger, "admin create user: insert failed", apierror.Internal(err))
|
||||
return
|
||||
}
|
||||
|
||||
@@ -215,12 +209,12 @@ func (h *handlers) handleAdminCreateUser(w http.ResponseWriter, r *http.Request)
|
||||
func (h *handlers) handleAdminDeleteUser(w http.ResponseWriter, r *http.Request) {
|
||||
caller, ok := auth.UserFromContext(r.Context())
|
||||
if !ok {
|
||||
writeErr(w, http.StatusUnauthorized, "auth_required", "")
|
||||
writeErr(w, apierror.Unauthorized("auth_required", ""))
|
||||
return
|
||||
}
|
||||
targetID, ok := parseUUID(chi.URLParam(r, "id"))
|
||||
if !ok {
|
||||
writeErr(w, http.StatusBadRequest, "invalid_id", "")
|
||||
writeErr(w, apierror.BadRequest("invalid_id", ""))
|
||||
return
|
||||
}
|
||||
|
||||
@@ -228,11 +222,10 @@ func (h *handlers) handleAdminDeleteUser(w http.ResponseWriter, r *http.Request)
|
||||
target, err := q.GetUserByID(r.Context(), targetID)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
writeErr(w, http.StatusNotFound, "not_found", "")
|
||||
writeErr(w, &apierror.Error{Status: http.StatusNotFound, Code: "not_found", Message: ""})
|
||||
return
|
||||
}
|
||||
h.logger.Error("admin delete user: lookup failed", "err", err)
|
||||
writeErr(w, http.StatusInternalServerError, "server_error", "")
|
||||
writeErrWithLog(w, h.logger, "admin delete user: lookup failed", apierror.Internal(err))
|
||||
return
|
||||
}
|
||||
|
||||
@@ -240,20 +233,18 @@ func (h *handlers) handleAdminDeleteUser(w http.ResponseWriter, r *http.Request)
|
||||
if target.IsAdmin {
|
||||
count, cerr := q.CountAdmins(r.Context())
|
||||
if cerr != nil {
|
||||
h.logger.Error("admin delete user: count admins failed", "err", cerr)
|
||||
writeErr(w, http.StatusInternalServerError, "server_error", "")
|
||||
writeErrWithLog(w, h.logger, "admin delete user: count admins failed", apierror.Internal(cerr))
|
||||
return
|
||||
}
|
||||
if count <= 1 {
|
||||
writeErr(w, http.StatusConflict, "last_admin",
|
||||
"can't delete the last admin — promote someone else first")
|
||||
writeErr(w, apierror.Conflict("last_admin",
|
||||
"can't delete the last admin — promote someone else first"))
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
if err := q.DeleteUser(r.Context(), targetID); err != nil {
|
||||
h.logger.Error("admin delete user: delete failed", "err", err)
|
||||
writeErr(w, http.StatusInternalServerError, "server_error", "")
|
||||
writeErrWithLog(w, h.logger, "admin delete user: delete failed", apierror.Internal(err))
|
||||
return
|
||||
}
|
||||
|
||||
@@ -274,21 +265,21 @@ type adminResetPasswordReq struct {
|
||||
func (h *handlers) handleAdminResetPassword(w http.ResponseWriter, r *http.Request) {
|
||||
caller, ok := auth.UserFromContext(r.Context())
|
||||
if !ok {
|
||||
writeErr(w, http.StatusUnauthorized, "auth_required", "")
|
||||
writeErr(w, apierror.Unauthorized("auth_required", ""))
|
||||
return
|
||||
}
|
||||
targetID, ok := parseUUID(chi.URLParam(r, "id"))
|
||||
if !ok {
|
||||
writeErr(w, http.StatusBadRequest, "invalid_id", "")
|
||||
writeErr(w, apierror.BadRequest("invalid_id", ""))
|
||||
return
|
||||
}
|
||||
var req adminResetPasswordReq
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, "invalid_body", "")
|
||||
writeErr(w, apierror.BadRequest("invalid_body", ""))
|
||||
return
|
||||
}
|
||||
if len(req.Password) < minPasswordLength {
|
||||
writeErr(w, http.StatusBadRequest, "password_too_short", "password must be at least 8 chars")
|
||||
writeErr(w, apierror.BadRequest("password_too_short", "password must be at least 8 chars"))
|
||||
return
|
||||
}
|
||||
|
||||
@@ -296,26 +287,23 @@ func (h *handlers) handleAdminResetPassword(w http.ResponseWriter, r *http.Reque
|
||||
// Verify target exists for a useful 404.
|
||||
if _, err := q.GetUserByID(r.Context(), targetID); err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
writeErr(w, http.StatusNotFound, "not_found", "")
|
||||
writeErr(w, &apierror.Error{Status: http.StatusNotFound, Code: "not_found", Message: ""})
|
||||
return
|
||||
}
|
||||
h.logger.Error("admin reset password: lookup failed", "err", err)
|
||||
writeErr(w, http.StatusInternalServerError, "server_error", "")
|
||||
writeErrWithLog(w, h.logger, "admin reset password: lookup failed", apierror.Internal(err))
|
||||
return
|
||||
}
|
||||
|
||||
hash, err := bcrypt.GenerateFromPassword([]byte(req.Password), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
h.logger.Error("admin reset password: hash failed", "err", err)
|
||||
writeErr(w, http.StatusInternalServerError, "server_error", "")
|
||||
writeErrWithLog(w, h.logger, "admin reset password: hash failed", apierror.Internal(err))
|
||||
return
|
||||
}
|
||||
if err := q.ResetUserPassword(r.Context(), dbq.ResetUserPasswordParams{
|
||||
ID: targetID,
|
||||
PasswordHash: string(hash),
|
||||
}); err != nil {
|
||||
h.logger.Error("admin reset password: update failed", "err", err)
|
||||
writeErr(w, http.StatusInternalServerError, "server_error", "")
|
||||
writeErrWithLog(w, h.logger, "admin reset password: update failed", apierror.Internal(err))
|
||||
return
|
||||
}
|
||||
|
||||
@@ -335,17 +323,17 @@ type adminAutoApproveReq struct {
|
||||
func (h *handlers) handleAdminAutoApproveToggle(w http.ResponseWriter, r *http.Request) {
|
||||
caller, ok := auth.UserFromContext(r.Context())
|
||||
if !ok {
|
||||
writeErr(w, http.StatusUnauthorized, "auth_required", "")
|
||||
writeErr(w, apierror.Unauthorized("auth_required", ""))
|
||||
return
|
||||
}
|
||||
targetID, ok := parseUUID(chi.URLParam(r, "id"))
|
||||
if !ok {
|
||||
writeErr(w, http.StatusBadRequest, "invalid_id", "")
|
||||
writeErr(w, apierror.BadRequest("invalid_id", ""))
|
||||
return
|
||||
}
|
||||
var req adminAutoApproveReq
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, "invalid_body", "")
|
||||
writeErr(w, apierror.BadRequest("invalid_body", ""))
|
||||
return
|
||||
}
|
||||
|
||||
@@ -356,11 +344,10 @@ func (h *handlers) handleAdminAutoApproveToggle(w http.ResponseWriter, r *http.R
|
||||
})
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
writeErr(w, http.StatusNotFound, "not_found", "")
|
||||
writeErr(w, &apierror.Error{Status: http.StatusNotFound, Code: "not_found", Message: ""})
|
||||
return
|
||||
}
|
||||
h.logger.Error("admin auto-approve: update failed", "err", err)
|
||||
writeErr(w, http.StatusInternalServerError, "server_error", "")
|
||||
writeErrWithLog(w, h.logger, "admin auto-approve: update failed", apierror.Internal(err))
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user