enhance bug report handling with pagination, filtering, and improved response structure
This commit is contained in:
@@ -165,8 +165,6 @@ func evaluate(db *sqlx.DB, dbName string, c condition) (bool, error) {
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- MySQL introspection helpers ----------
|
||||
|
||||
func columnExists(db *sqlx.DB, dbName, table, column string) (bool, error) {
|
||||
var count int
|
||||
err := db.Get(&count,
|
||||
|
||||
251
internal/handlers/admin_auth.route.go
Normal file
251
internal/handlers/admin_auth.route.go
Normal file
@@ -0,0 +1,251 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/subtle"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/jmoiron/sqlx"
|
||||
"golang.org/x/crypto/argon2"
|
||||
|
||||
"emly-api-go/internal/models"
|
||||
)
|
||||
|
||||
// argon2id params — mirror @node-rs/argon2 defaults used in the TypeScript service.
|
||||
const (
|
||||
argonMemory = 19456
|
||||
argonTime = 2
|
||||
argonKeyLen = 32
|
||||
argonParallelism = 1
|
||||
argonSaltLen = 16
|
||||
|
||||
sessionExpiryDays = 30
|
||||
)
|
||||
|
||||
// hashPassword produces a PHC-formatted argon2id string compatible with
|
||||
// the @node-rs/argon2 library used in the TypeScript service.
|
||||
func hashPassword(password string) (string, error) {
|
||||
salt := make([]byte, argonSaltLen)
|
||||
if _, err := rand.Read(salt); err != nil {
|
||||
return "", err
|
||||
}
|
||||
hash := argon2.IDKey([]byte(password), salt, argonTime, argonMemory, argonParallelism, argonKeyLen)
|
||||
b64Salt := base64.RawStdEncoding.EncodeToString(salt)
|
||||
b64Hash := base64.RawStdEncoding.EncodeToString(hash)
|
||||
return fmt.Sprintf("$argon2id$v=19$m=%d,t=%d,p=%d$%s$%s",
|
||||
argonMemory, argonTime, argonParallelism, b64Salt, b64Hash), nil
|
||||
}
|
||||
|
||||
// verifyPassword checks a password against a PHC-formatted argon2id hash.
|
||||
func verifyPassword(phc, password string) (bool, error) {
|
||||
parts := strings.Split(phc, "$")
|
||||
// Expected: ["", "argon2id", "v=19", "m=...,t=...,p=...", "<salt>", "<hash>"]
|
||||
if len(parts) != 6 || parts[1] != "argon2id" {
|
||||
return false, fmt.Errorf("invalid hash format")
|
||||
}
|
||||
var memory, timeCost uint32
|
||||
var parallelism uint8
|
||||
if _, err := fmt.Sscanf(parts[3], "m=%d,t=%d,p=%d", &memory, &timeCost, ¶llelism); err != nil {
|
||||
return false, fmt.Errorf("invalid params: %w", err)
|
||||
}
|
||||
salt, err := base64.RawStdEncoding.DecodeString(parts[4])
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("invalid salt: %w", err)
|
||||
}
|
||||
hashBytes, err := base64.RawStdEncoding.DecodeString(parts[5])
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("invalid hash: %w", err)
|
||||
}
|
||||
computed := argon2.IDKey([]byte(password), salt, timeCost, memory, parallelism, uint32(len(hashBytes)))
|
||||
return subtle.ConstantTimeCompare(computed, hashBytes) == 1, nil
|
||||
}
|
||||
|
||||
// generateUUID generates a random UUID v4.
|
||||
func generateUUID() (string, error) {
|
||||
b := make([]byte, 16)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
return "", err
|
||||
}
|
||||
b[6] = (b[6] & 0x0f) | 0x40
|
||||
b[8] = (b[8] & 0x3f) | 0x80
|
||||
return fmt.Sprintf("%08x-%04x-%04x-%04x-%012x",
|
||||
b[0:4], b[4:6], b[6:8], b[8:10], b[10:16]), nil
|
||||
}
|
||||
|
||||
// generateSessionID returns a 64-char hex string (32 random bytes),
|
||||
// matching the TypeScript generateSessionId() implementation.
|
||||
func generateSessionID() (string, error) {
|
||||
b := make([]byte, 32)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return hex.EncodeToString(b), nil
|
||||
}
|
||||
|
||||
// authUser is the public representation returned to callers after login/validate.
|
||||
type authUser struct {
|
||||
ID string `json:"id"`
|
||||
Username string `json:"username"`
|
||||
Displayname string `json:"displayname"`
|
||||
Role models.UserRole `json:"role"`
|
||||
Enabled bool `json:"enabled"`
|
||||
}
|
||||
|
||||
// sessionHeader is the header name used to pass the session ID.
|
||||
const sessionHeader = "X-Session-Token"
|
||||
|
||||
// LoginUser handles POST /v1/api/admin/auth/login
|
||||
func LoginUser(db *sqlx.DB) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
var body struct {
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||
jsonError(w, http.StatusBadRequest, "invalid JSON: "+err.Error())
|
||||
return
|
||||
}
|
||||
if body.Username == "" || body.Password == "" {
|
||||
jsonError(w, http.StatusBadRequest, "username and password are required")
|
||||
return
|
||||
}
|
||||
|
||||
var row struct {
|
||||
models.User
|
||||
PasswordHash string `db:"password_hash"`
|
||||
}
|
||||
err := db.GetContext(r.Context(), &row,
|
||||
"SELECT id, username, displayname, password_hash, role, enabled FROM `user` WHERE username = ? LIMIT 1",
|
||||
body.Username,
|
||||
)
|
||||
if err != nil {
|
||||
// Return 401 whether the user doesn't exist or query failed to avoid enumeration
|
||||
jsonError(w, http.StatusUnauthorized, "invalid credentials")
|
||||
return
|
||||
}
|
||||
|
||||
valid, err := verifyPassword(row.PasswordHash, body.Password)
|
||||
if err != nil || !valid {
|
||||
jsonError(w, http.StatusUnauthorized, "invalid credentials")
|
||||
return
|
||||
}
|
||||
|
||||
if !row.Enabled {
|
||||
jsonError(w, http.StatusForbidden, "account disabled")
|
||||
return
|
||||
}
|
||||
|
||||
sessionID, err := generateSessionID()
|
||||
if err != nil {
|
||||
jsonError(w, http.StatusInternalServerError, "failed to generate session: "+err.Error())
|
||||
return
|
||||
}
|
||||
expiresAt := time.Now().UTC().Add(sessionExpiryDays * 24 * time.Hour)
|
||||
|
||||
if _, err := db.ExecContext(r.Context(),
|
||||
"INSERT INTO session (id, user_id, expires_at) VALUES (?, ?, ?)",
|
||||
sessionID, row.ID, expiresAt,
|
||||
); err != nil {
|
||||
jsonError(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
log.Printf("[AUTH] User logged in: username=%s session=%s...", body.Username, sessionID[:8])
|
||||
|
||||
jsonOK(w, map[string]any{
|
||||
"session_id": sessionID,
|
||||
"user": authUser{
|
||||
ID: row.ID,
|
||||
Username: row.Username,
|
||||
Displayname: row.Displayname,
|
||||
Role: row.Role,
|
||||
Enabled: row.Enabled,
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// ValidateSession handles GET /v1/api/admin/auth/validate
|
||||
// Reads the session ID from the X-Session-ID header.
|
||||
func ValidateSession(db *sqlx.DB) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
sessionID := r.Header.Get(sessionHeader)
|
||||
if sessionID == "" {
|
||||
jsonError(w, http.StatusUnauthorized, "missing "+sessionHeader+" header")
|
||||
return
|
||||
}
|
||||
|
||||
var row struct {
|
||||
ID string `db:"id"`
|
||||
Username string `db:"username"`
|
||||
Displayname string `db:"displayname"`
|
||||
Role models.UserRole `db:"role"`
|
||||
Enabled bool `db:"enabled"`
|
||||
ExpiresAt time.Time `db:"expires_at"`
|
||||
}
|
||||
err := db.GetContext(r.Context(), &row,
|
||||
`SELECT u.id, u.username, u.displayname, u.role, u.enabled, s.expires_at
|
||||
FROM session s
|
||||
JOIN user u ON u.id = s.user_id
|
||||
WHERE s.id = ? LIMIT 1`,
|
||||
sessionID,
|
||||
)
|
||||
if err != nil {
|
||||
jsonError(w, http.StatusUnauthorized, "invalid session")
|
||||
log.Fatalf("Database error during session validation: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
if time.Now().UTC().After(row.ExpiresAt) {
|
||||
_, _ = db.ExecContext(r.Context(), "DELETE FROM session WHERE id = ?", sessionID)
|
||||
jsonError(w, http.StatusUnauthorized, "session expired")
|
||||
return
|
||||
}
|
||||
|
||||
if !row.Enabled {
|
||||
jsonError(w, http.StatusForbidden, "account disabled")
|
||||
return
|
||||
}
|
||||
|
||||
jsonOK(w, map[string]any{
|
||||
"success": true,
|
||||
"user": authUser{
|
||||
ID: row.ID,
|
||||
Username: row.Username,
|
||||
Displayname: row.Displayname,
|
||||
Role: row.Role,
|
||||
Enabled: row.Enabled,
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// LogoutSession handles POST /v1/api/admin/auth/logout
|
||||
// Reads the session ID from the X-Session-ID header.
|
||||
func LogoutSession(db *sqlx.DB) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
sessionID := r.Header.Get(sessionHeader)
|
||||
if sessionID == "" {
|
||||
jsonError(w, http.StatusBadRequest, "missing "+sessionHeader+" header")
|
||||
return
|
||||
}
|
||||
|
||||
if _, err := db.ExecContext(r.Context(),
|
||||
"DELETE FROM session WHERE id = ?", sessionID,
|
||||
); err != nil {
|
||||
jsonError(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
log.Printf("[AUTH] Session logged out: %s...", sessionID[:8])
|
||||
|
||||
jsonOK(w, map[string]bool{"logged_out": true})
|
||||
}
|
||||
}
|
||||
263
internal/handlers/admin_users.route.go
Normal file
263
internal/handlers/admin_users.route.go
Normal file
@@ -0,0 +1,263 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/jmoiron/sqlx"
|
||||
|
||||
"emly-api-go/internal/models"
|
||||
)
|
||||
|
||||
// ListUsers handles GET /v1/api/admin/users
|
||||
func ListUsers(db *sqlx.DB) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
var users []models.User
|
||||
if err := db.SelectContext(r.Context(), &users,
|
||||
"SELECT id, username, displayname, role, enabled, created_at FROM `user` ORDER BY created_at ASC",
|
||||
); err != nil {
|
||||
jsonError(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
jsonOK(w, users)
|
||||
}
|
||||
}
|
||||
|
||||
// CreateUser handles POST /v1/api/admin/users
|
||||
func CreateUser(db *sqlx.DB) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
var body struct {
|
||||
Username string `json:"username"`
|
||||
Displayname string `json:"displayname"`
|
||||
Password string `json:"password"`
|
||||
Role models.UserRole `json:"role"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||
jsonError(w, http.StatusBadRequest, "invalid JSON: "+err.Error())
|
||||
return
|
||||
}
|
||||
if body.Username == "" || body.Password == "" {
|
||||
jsonError(w, http.StatusBadRequest, "username and password are required")
|
||||
return
|
||||
}
|
||||
if body.Role != models.UserRoleAdmin && body.Role != models.UserRoleUser {
|
||||
jsonError(w, http.StatusBadRequest, "role must be 'admin' or 'user'")
|
||||
return
|
||||
}
|
||||
|
||||
var count int
|
||||
if err := db.GetContext(r.Context(), &count,
|
||||
"SELECT COUNT(*) FROM `user` WHERE username = ?", body.Username,
|
||||
); err != nil {
|
||||
jsonError(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
if count > 0 {
|
||||
jsonError(w, http.StatusConflict, "username already exists")
|
||||
return
|
||||
}
|
||||
|
||||
passwordHash, err := hashPassword(body.Password)
|
||||
if err != nil {
|
||||
jsonError(w, http.StatusInternalServerError, "failed to hash password: "+err.Error())
|
||||
return
|
||||
}
|
||||
id, err := generateUUID()
|
||||
if err != nil {
|
||||
jsonError(w, http.StatusInternalServerError, "failed to generate id: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
if _, err := db.ExecContext(r.Context(),
|
||||
"INSERT INTO `user` (id, username, displayname, password_hash, role) VALUES (?, ?, ?, ?, ?)",
|
||||
id, body.Username, body.Displayname, passwordHash, body.Role,
|
||||
); err != nil {
|
||||
jsonError(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
var user models.User
|
||||
if err := db.GetContext(r.Context(), &user,
|
||||
"SELECT id, username, displayname, role, enabled, created_at FROM `user` WHERE id = ?", id,
|
||||
); err != nil {
|
||||
jsonError(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
jsonCreated(w, user)
|
||||
}
|
||||
}
|
||||
|
||||
// GetUserByID handles GET /v1/api/admin/users/{id}
|
||||
func GetUserByID(db *sqlx.DB) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
id := chi.URLParam(r, "id")
|
||||
if id == "" {
|
||||
jsonError(w, http.StatusBadRequest, "missing id parameter")
|
||||
return
|
||||
}
|
||||
|
||||
var user models.User
|
||||
err := db.GetContext(r.Context(), &user,
|
||||
"SELECT id, username, displayname, role, enabled, created_at FROM `user` WHERE id = ? LIMIT 1", id,
|
||||
)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
jsonError(w, http.StatusNotFound, "user not found")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
jsonError(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
jsonOK(w, user)
|
||||
}
|
||||
}
|
||||
|
||||
// UpdateUser handles PATCH /v1/api/admin/users/{id}
|
||||
// Accepted fields: displayname, enabled
|
||||
func UpdateUser(db *sqlx.DB) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
id := chi.URLParam(r, "id")
|
||||
if id == "" {
|
||||
jsonError(w, http.StatusBadRequest, "missing id parameter")
|
||||
return
|
||||
}
|
||||
|
||||
var body map[string]json.RawMessage
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||
jsonError(w, http.StatusBadRequest, "invalid JSON: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
fields := []string{}
|
||||
params := []any{}
|
||||
|
||||
if raw, ok := body["displayname"]; ok {
|
||||
var v string
|
||||
if err := json.Unmarshal(raw, &v); err != nil {
|
||||
jsonError(w, http.StatusBadRequest, "invalid displayname value")
|
||||
return
|
||||
}
|
||||
fields = append(fields, "displayname = ?")
|
||||
params = append(params, v)
|
||||
}
|
||||
if raw, ok := body["enabled"]; ok {
|
||||
var v bool
|
||||
if err := json.Unmarshal(raw, &v); err != nil {
|
||||
jsonError(w, http.StatusBadRequest, "invalid enabled value")
|
||||
return
|
||||
}
|
||||
fields = append(fields, "enabled = ?")
|
||||
params = append(params, v)
|
||||
}
|
||||
|
||||
if len(fields) == 0 {
|
||||
jsonError(w, http.StatusBadRequest, "no updatable fields provided")
|
||||
return
|
||||
}
|
||||
|
||||
query := "UPDATE `user` SET "
|
||||
for i, f := range fields {
|
||||
if i > 0 {
|
||||
query += ", "
|
||||
}
|
||||
query += f
|
||||
}
|
||||
query += " WHERE id = ?"
|
||||
params = append(params, id)
|
||||
|
||||
result, err := db.ExecContext(r.Context(), query, params...)
|
||||
if err != nil {
|
||||
jsonError(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
rows, err := result.RowsAffected()
|
||||
if err != nil {
|
||||
jsonError(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
if rows == 0 {
|
||||
jsonError(w, http.StatusNotFound, "user not found")
|
||||
return
|
||||
}
|
||||
jsonOK(w, map[string]bool{"updated": true})
|
||||
}
|
||||
}
|
||||
|
||||
// ResetPassword handles POST /v1/api/admin/users/{id}/reset-password
|
||||
func ResetPassword(db *sqlx.DB) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
id := chi.URLParam(r, "id")
|
||||
if id == "" {
|
||||
jsonError(w, http.StatusBadRequest, "missing id parameter")
|
||||
return
|
||||
}
|
||||
|
||||
var body struct {
|
||||
Password string `json:"password"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||
jsonError(w, http.StatusBadRequest, "invalid JSON: "+err.Error())
|
||||
return
|
||||
}
|
||||
if body.Password == "" {
|
||||
jsonError(w, http.StatusBadRequest, "password is required")
|
||||
return
|
||||
}
|
||||
|
||||
passwordHash, err := hashPassword(body.Password)
|
||||
if err != nil {
|
||||
jsonError(w, http.StatusInternalServerError, "failed to hash password: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
result, err := db.ExecContext(r.Context(),
|
||||
"UPDATE `user` SET password_hash = ? WHERE id = ?", passwordHash, id,
|
||||
)
|
||||
if err != nil {
|
||||
jsonError(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
rows, err := result.RowsAffected()
|
||||
if err != nil {
|
||||
jsonError(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
if rows == 0 {
|
||||
jsonError(w, http.StatusNotFound, "user not found")
|
||||
return
|
||||
}
|
||||
jsonOK(w, map[string]bool{"updated": true})
|
||||
}
|
||||
}
|
||||
|
||||
// DeleteUser handles DELETE /v1/api/admin/users/{id}
|
||||
func DeleteUser(db *sqlx.DB) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
id := chi.URLParam(r, "id")
|
||||
if id == "" {
|
||||
jsonError(w, http.StatusBadRequest, "missing id parameter")
|
||||
return
|
||||
}
|
||||
|
||||
result, err := db.ExecContext(r.Context(),
|
||||
"DELETE FROM `user` WHERE id = ?", id,
|
||||
)
|
||||
if err != nil {
|
||||
jsonError(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
rows, err := result.RowsAffected()
|
||||
if err != nil {
|
||||
jsonError(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
if rows == 0 {
|
||||
jsonError(w, http.StatusNotFound, "user not found")
|
||||
return
|
||||
}
|
||||
jsonOK(w, map[string]bool{"deleted": true})
|
||||
}
|
||||
}
|
||||
@@ -10,8 +10,10 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"math"
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"text/template"
|
||||
|
||||
@@ -139,13 +141,70 @@ func CreateBugReport(db *sqlx.DB) http.HandlerFunc {
|
||||
|
||||
func GetAllBugReports(db *sqlx.DB) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
var reports []models.BugReport
|
||||
if err := db.SelectContext(r.Context(), &reports, "SELECT * FROM emly_bugreports_dev.bug_reports"); err != nil {
|
||||
page, pageSize := 1, 20
|
||||
if p := r.URL.Query().Get("page"); p != "" {
|
||||
if v, err := strconv.Atoi(p); err == nil && v > 0 {
|
||||
page = v
|
||||
}
|
||||
}
|
||||
if ps := r.URL.Query().Get("page_size"); ps != "" {
|
||||
if v, err := strconv.Atoi(ps); err == nil && v > 0 && v <= 100 {
|
||||
pageSize = v
|
||||
}
|
||||
}
|
||||
|
||||
status := r.URL.Query().Get("status")
|
||||
search := r.URL.Query().Get("search")
|
||||
offset := (page - 1) * pageSize
|
||||
|
||||
var conditions []string
|
||||
var params []interface{}
|
||||
|
||||
if status != "" {
|
||||
conditions = append(conditions, "br.status = ?")
|
||||
params = append(params, status)
|
||||
}
|
||||
if search != "" {
|
||||
like := "%" + search + "%"
|
||||
conditions = append(conditions, "(br.hostname LIKE ? OR br.os_user LIKE ? OR br.name LIKE ? OR br.email LIKE ?)")
|
||||
params = append(params, like, like, like, like)
|
||||
}
|
||||
|
||||
whereClause := ""
|
||||
if len(conditions) > 0 {
|
||||
whereClause = "WHERE " + strings.Join(conditions, " AND ")
|
||||
}
|
||||
|
||||
var total int
|
||||
countQuery := fmt.Sprintf("SELECT COUNT(*) FROM emly_bugreports_dev.bug_reports br " + whereClause)
|
||||
if err := db.GetContext(r.Context(), &total, countQuery, params...); err != nil {
|
||||
jsonError(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
jsonOK(w, reports)
|
||||
mainQuery := fmt.Sprintf(`
|
||||
SELECT br.*, COUNT(bf.id) as file_count
|
||||
FROM emly_bugreports_dev.bug_reports br
|
||||
LEFT JOIN emly_bugreports_dev.bug_report_files bf ON bf.report_id = br.id
|
||||
` + whereClause + `
|
||||
GROUP BY br.id
|
||||
ORDER BY br.created_at DESC
|
||||
LIMIT ? OFFSET ?`)
|
||||
|
||||
listParams := append(params, pageSize, offset)
|
||||
var reports []models.BugReportListItem
|
||||
if err := db.SelectContext(r.Context(), &reports, mainQuery, listParams...); err != nil {
|
||||
jsonError(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
jsonOK(w, map[string]interface{}{
|
||||
"data": reports,
|
||||
"total": total,
|
||||
"page": page,
|
||||
"page_size": pageSize,
|
||||
"total_pages": int(math.Ceil(float64(total) / float64(pageSize))),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -158,17 +217,25 @@ func GetBugReportByID(db *sqlx.DB) http.HandlerFunc {
|
||||
}
|
||||
|
||||
var report models.BugReport
|
||||
err := db.GetContext(r.Context(), &report, "SELECT * FROM emly_bugreports_dev.bug_reports WHERE id = ?", id)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
reportErr := db.GetContext(r.Context(), &report, "SELECT * FROM emly_bugreports_dev.bug_reports WHERE id = ?", id)
|
||||
if errors.Is(reportErr, sql.ErrNoRows) {
|
||||
jsonError(w, http.StatusNotFound, "bug report not found")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
jsonError(w, http.StatusInternalServerError, err.Error())
|
||||
if reportErr != nil {
|
||||
jsonError(w, http.StatusInternalServerError, reportErr.Error())
|
||||
return
|
||||
}
|
||||
|
||||
jsonOK(w, report)
|
||||
type response struct {
|
||||
Report models.BugReport `json:"report"`
|
||||
}
|
||||
|
||||
responseData := response{
|
||||
Report: report,
|
||||
}
|
||||
|
||||
jsonOK(w, responseData)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -28,6 +28,7 @@ func AdminKeyAuth(_ *sqlx.DB) func(http.Handler) http.Handler {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
json.NewEncoder(w).Encode(map[string]string{"error": "unauthorized admin key"})
|
||||
log.Println("[ADMIN-KEY] Failed to authorize admin key for URL: " + r.URL.String())
|
||||
return
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
|
||||
@@ -28,6 +28,7 @@ func APIKeyAuth(_ *sqlx.DB) func(http.Handler) http.Handler {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
json.NewEncoder(w).Encode(map[string]string{"error": "unauthorized"})
|
||||
log.Println("[API-KEY] Failed to authorize admin key for URL: " + r.URL.String())
|
||||
return
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
|
||||
@@ -14,6 +14,11 @@ const (
|
||||
BugReportStatusClosed BugReportStatus = "closed"
|
||||
)
|
||||
|
||||
type BugReportListItem struct {
|
||||
BugReport
|
||||
FileCount int `db:"file_count" json:"file_count"`
|
||||
}
|
||||
|
||||
type BugReport struct {
|
||||
ID uint64 `db:"id" json:"id"`
|
||||
Name string `db:"name" json:"name"`
|
||||
|
||||
@@ -4,8 +4,6 @@ import "time"
|
||||
|
||||
type Session struct {
|
||||
ID string `db:"id" json:"id"`
|
||||
UserID int64 `db:"user_id" json:"user_id"`
|
||||
Token string `db:"token" json:"token"`
|
||||
UserID string `db:"user_id" json:"user_id"`
|
||||
ExpiresAt time.Time `db:"expires_at" json:"expires_at"`
|
||||
CreatedAt time.Time `db:"created_at" json:"created_at"`
|
||||
}
|
||||
|
||||
@@ -10,12 +10,11 @@ const (
|
||||
)
|
||||
|
||||
type User struct {
|
||||
ID int64 `db:"id" json:"id"`
|
||||
ID string `db:"id" json:"id"`
|
||||
Username string `db:"username" json:"username"`
|
||||
Email string `db:"email" json:"email"`
|
||||
Displayname string `db:"displayname" json:"displayname"`
|
||||
PasswordHash string `db:"password_hash" json:"-"`
|
||||
Role UserRole `db:"role" json:"role"`
|
||||
Enabled bool `db:"enabled" json:"enabled"`
|
||||
CreatedAt time.Time `db:"created_at" json:"created_at"`
|
||||
UpdatedAt time.Time `db:"updated_at" json:"updated_at"`
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user