Files
book-comic-library/backend/cmd/webui/handlers/users.go
T

89 lines
2.2 KiB
Go

package handlers
import (
"errors"
"net/http"
"strconv"
"time"
"github.com/gin-gonic/gin"
"github.com/jackc/pgx/v5"
"booklib/internal/auth"
"booklib/internal/store"
)
// isUnique is a convenience alias for store.IsUniqueViolation.
func isUnique(e error) bool { return store.IsUniqueViolation(e) }
func (h *H) ListUsers(c *gin.Context) {
users, e := h.st.ListUsers(c)
if e != nil {
dbErr(c, e)
return
}
out := make([]gin.H, 0, len(users))
for _, u := range users {
out = append(out, gin.H{"id": u.ID, "username": u.Username, "role": u.Role,
"created_at": u.CreatedAt.Format(time.RFC3339)})
}
c.JSON(http.StatusOK, out)
}
func (h *H) CreateUser(c *gin.Context) {
var req struct{ Username, Password, Role string }
if c.ShouldBindJSON(&req) != nil {
err(c, http.StatusBadRequest, "bad_request", "json body required")
return
}
if req.Role != "admin" && req.Role != "member" {
err(c, http.StatusBadRequest, "bad_request", "role must be admin|member")
return
}
if len(req.Password) < 8 {
err(c, http.StatusBadRequest, "bad_request", "password too short (min 8)")
return
}
hp, e := auth.HashPassword(req.Password)
if e != nil {
err(c, http.StatusInternalServerError, "internal", "hash")
return
}
id, e := h.st.CreateUser(c, req.Username, hp, req.Role)
if e != nil {
if isUnique(e) {
err(c, http.StatusConflict, "exists", "username taken")
return
}
dbErr(c, e)
return
}
c.JSON(http.StatusCreated, gin.H{"id": id, "username": req.Username, "role": req.Role})
}
func (h *H) DeleteUser(c *gin.Context) {
id, e := strconv.ParseInt(c.Param("id"), 10, 64)
if e != nil {
err(c, http.StatusBadRequest, "bad_request", "bad id")
return
}
if id == uid(c) {
err(c, http.StatusBadRequest, "bad_request", "cannot delete yourself")
return
}
// B5: transactional last-admin check eliminates TOCTOU race.
if e := h.st.DeleteUser(c, id); e != nil {
if errors.Is(e, pgx.ErrNoRows) {
err(c, http.StatusNotFound, "not_found", "no such user")
return
}
if errors.Is(e, store.ErrLastAdmin) {
err(c, http.StatusBadRequest, "bad_request", "cannot delete the last admin")
return
}
dbErr(c, e)
return
}
c.Status(http.StatusNoContent)
}