Files
gochat/internal/handler/api/v1/custom_role_handler.go
T

246 lines
7.4 KiB
Go

package v1
import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/gochat/gochat/internal/model"
"github.com/gochat/gochat/internal/service"
applogger "github.com/gochat/gochat/pkg/logger"
"github.com/gochat/gochat/pkg/response"
)
// CustomRoleHandler handles CustomRole CRUD operations.
// Reference: Chatwoot enterprise/app/controllers/api/v1/custom_roles_controller.rb
type CustomRoleHandler struct {
svc *service.CustomRoleService
auditSvc *service.AuditService
}
// NewCustomRoleHandler creates a new CustomRole handler.
func NewCustomRoleHandler(svc *service.CustomRoleService) *CustomRoleHandler {
return &CustomRoleHandler{svc: svc}
}
func (h *CustomRoleHandler) WithAuditService(auditSvc *service.AuditService) *CustomRoleHandler {
h.auditSvc = auditSvc
return h
}
// List returns all custom roles for an account.
// GET /api/v1/accounts/:account_id/custom_roles
func (h *CustomRoleHandler) List(c *gin.Context) {
accountID := getAccountID(c)
if accountID == 0 {
response.AbortWithStatusError(c, http.StatusUnauthorized, response.ErrUnauthorized, "account not identified")
return
}
if !isCustomRoleAdmin(c) {
response.AbortWithStatusError(c, http.StatusUnauthorized, response.ErrUnauthorized, "administrator role required")
return
}
roles, _, err := h.svc.List(c.Request.Context(), accountID, 1, 10000)
if err != nil {
applogger.L().Errorf("List custom roles for account %d: %v", accountID, err)
handleServiceError(c, err)
return
}
c.JSON(http.StatusOK, serializeCustomRoles(roles))
}
// Create creates a new custom role for an account.
// POST /api/v1/accounts/:account_id/custom_roles
// Request body uses Chatwoot-style wrapper: { "custom_role": { "name": "...", "permissions": {...} } }
func (h *CustomRoleHandler) Create(c *gin.Context) {
accountID := getAccountID(c)
if accountID == 0 {
response.AbortWithStatusError(c, http.StatusUnauthorized, response.ErrUnauthorized, "account not identified")
return
}
if !isCustomRoleAdmin(c) {
response.AbortWithStatusError(c, http.StatusUnauthorized, response.ErrUnauthorized, "administrator role required")
return
}
var wrapper struct {
CustomRole service.CreateCustomRoleRequest `json:"custom_role"`
}
if err := c.ShouldBindJSON(&wrapper); err != nil {
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrValidation, err.Error())
return
}
role, err := h.svc.Create(c.Request.Context(), accountID, wrapper.CustomRole)
if err != nil {
applogger.L().Errorf("Create custom role for account %d: %v", accountID, err)
handleServiceError(c, err)
return
}
recordAuditMutation(c, h.auditSvc, auditMutation{
AccountID: accountID,
AuditableType: "CustomRole",
AuditableID: role.ID,
Action: "create",
AuditedChanges: role,
})
c.JSON(http.StatusOK, serializeCustomRole(role))
}
// Get returns a single custom role by ID.
// GET /api/v1/accounts/:account_id/custom_roles/:id
func (h *CustomRoleHandler) Get(c *gin.Context) {
accountID := getAccountID(c)
if accountID == 0 {
response.AbortWithStatusError(c, http.StatusUnauthorized, response.ErrUnauthorized, "account not identified")
return
}
if !isCustomRoleAdmin(c) {
response.AbortWithStatusError(c, http.StatusUnauthorized, response.ErrUnauthorized, "administrator role required")
return
}
id, err := parseUintParam(c, "id")
if err != nil {
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid id")
return
}
role, svcErr := h.svc.GetByID(c.Request.Context(), id, accountID)
if svcErr != nil {
applogger.L().Errorf("Get custom role %d for account %d: %v", id, accountID, svcErr)
handleServiceError(c, svcErr)
return
}
c.JSON(http.StatusOK, serializeCustomRole(role))
}
// Update updates an existing custom role.
// PUT /api/v1/accounts/:account_id/custom_roles/:id
// Request body uses Chatwoot-style wrapper: { "custom_role": { "name": "...", "permissions": {...} } }
func (h *CustomRoleHandler) Update(c *gin.Context) {
accountID := getAccountID(c)
if accountID == 0 {
response.AbortWithStatusError(c, http.StatusUnauthorized, response.ErrUnauthorized, "account not identified")
return
}
if !isCustomRoleAdmin(c) {
response.AbortWithStatusError(c, http.StatusUnauthorized, response.ErrUnauthorized, "administrator role required")
return
}
id, err := parseUintParam(c, "id")
if err != nil {
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid id")
return
}
var wrapper struct {
CustomRole service.UpdateCustomRoleRequest `json:"custom_role"`
}
if err := c.ShouldBindJSON(&wrapper); err != nil {
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrValidation, err.Error())
return
}
role, svcErr := h.svc.Update(c.Request.Context(), id, accountID, wrapper.CustomRole)
if svcErr != nil {
applogger.L().Errorf("Update custom role %d for account %d: %v", id, accountID, svcErr)
handleServiceError(c, svcErr)
return
}
recordAuditMutation(c, h.auditSvc, auditMutation{
AccountID: accountID,
AuditableType: "CustomRole",
AuditableID: role.ID,
Action: "update",
AuditedChanges: role,
})
c.JSON(http.StatusOK, serializeCustomRole(role))
}
// Delete soft-deletes a custom role.
// DELETE /api/v1/accounts/:account_id/custom_roles/:id
func (h *CustomRoleHandler) Delete(c *gin.Context) {
accountID := getAccountID(c)
if accountID == 0 {
response.AbortWithStatusError(c, http.StatusUnauthorized, response.ErrUnauthorized, "account not identified")
return
}
if !isCustomRoleAdmin(c) {
response.AbortWithStatusError(c, http.StatusUnauthorized, response.ErrUnauthorized, "administrator role required")
return
}
id, err := parseUintParam(c, "id")
if err != nil {
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid id")
return
}
if svcErr := h.svc.Delete(c.Request.Context(), id, accountID); svcErr != nil {
applogger.L().Errorf("Delete custom role %d for account %d: %v", id, accountID, svcErr)
handleServiceError(c, svcErr)
return
}
recordAuditMutation(c, h.auditSvc, auditMutation{
AccountID: accountID,
AuditableType: "CustomRole",
AuditableID: id,
Action: "destroy",
AuditedChanges: gin.H{"id": id},
})
c.Status(http.StatusOK)
}
// RegisterCustomRoleRoutes registers custom role routes on a gin.RouterGroup.
func RegisterCustomRoleRoutes(rg *gin.RouterGroup, h *CustomRoleHandler) {
customRoles := rg.Group("/custom_roles")
{
customRoles.GET("/", h.List)
customRoles.POST("/", h.Create)
customRoles.GET("/:id", h.Get)
customRoles.PATCH("/:id", h.Update)
customRoles.PUT("/:id", h.Update)
customRoles.DELETE("/:id", h.Delete)
}
}
func isCustomRoleAdmin(c *gin.Context) bool {
role := getRole(c)
return role == "administrator" || role == "super_admin"
}
func serializeCustomRoles(roles []model.CustomRole) []gin.H {
items := make([]gin.H, 0, len(roles))
for i := range roles {
items = append(items, serializeCustomRole(&roles[i]))
}
return items
}
func serializeCustomRole(role *model.CustomRole) gin.H {
permissions, err := role.GetPermissionKeys()
if err != nil {
permissions = []model.PermissionDimension{}
}
permissionStrings := make([]string, 0, len(permissions))
for _, key := range permissions {
permissionStrings = append(permissionStrings, string(key))
}
return gin.H{
"id": role.ID,
"name": role.Name,
"description": role.Description,
"permissions": permissionStrings,
"created_at": role.CreatedAt,
"updated_at": role.UpdatedAt,
}
}