f1909da1ad
Go CI / build (push) Failing after 2m42s
feat: create basic server to manage google oauth, account, sessions, places, attributes and ratings.
73 lines
2.0 KiB
Go
73 lines
2.0 KiB
Go
package api
|
|
|
|
import (
|
|
"net/http"
|
|
|
|
"git.pengzhan.dev/noteplace-server/internal/models"
|
|
"git.pengzhan.dev/noteplace-server/internal/store"
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/google/uuid"
|
|
)
|
|
|
|
// AttributesHandler handles HTTP requests for attributes.
|
|
type AttributesHandler struct {
|
|
Store *store.Store
|
|
}
|
|
|
|
// HandleCreateAttribute creates a new attribute.
|
|
func (h *AttributesHandler) HandleCreateAttribute(c *gin.Context) {
|
|
var newAttr models.Attribute
|
|
if err := c.ShouldBindJSON(&newAttr); err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})
|
|
return
|
|
}
|
|
|
|
// --- Validation ---
|
|
user, exists := c.Get("user")
|
|
if !exists {
|
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized: User not found in context"})
|
|
return
|
|
}
|
|
|
|
if user.(models.User).Role > models.TRUSTED {
|
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized: User not allowed to perform this action"})
|
|
return
|
|
}
|
|
|
|
if newAttr.Name == "" {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "Name is a required field"})
|
|
return
|
|
}
|
|
|
|
switch newAttr.Scope {
|
|
case models.CATEGORY:
|
|
if newAttr.OwnerID == "" {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "OwnerID (PlaceCategory) is required for CATEGORY attributes"})
|
|
return
|
|
}
|
|
case models.PLACE:
|
|
if newAttr.OwnerID == "" {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "OwnerID (PlaceID) is required for PLACE attributes"})
|
|
return
|
|
}
|
|
if _, found := h.Store.GetPlaceByID(newAttr.OwnerID); !found {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "OwnerID (PlaceID) does not refer to a valid place"})
|
|
return
|
|
}
|
|
default:
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "Scope must be either CATEGORY or PLACE"})
|
|
return
|
|
}
|
|
|
|
newAttr.ID = "attr-" + uuid.New().String()
|
|
|
|
// UserID for attribute creation is not specified in DESIGN.md, assuming it's not directly linked to the creator for now.
|
|
|
|
if err := h.Store.CreateAttribute(newAttr); err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to save attribute"})
|
|
return
|
|
}
|
|
|
|
c.JSON(http.StatusCreated, newAttr)
|
|
}
|