feat(custom-roles): align chatwoot permissions

This commit is contained in:
2026-06-05 11:14:38 +08:00
parent b5f2a47ef8
commit 8b3b532c65
20 changed files with 681 additions and 226 deletions
+59 -8
View File
@@ -5,9 +5,9 @@ import (
"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/pagination"
"github.com/gochat/gochat/pkg/response"
)
@@ -36,16 +36,19 @@ func (h *CustomRoleHandler) List(c *gin.Context) {
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
}
pg := pagination.Parse(c)
roles, total, err := h.svc.List(c.Request.Context(), accountID, pg.Page, pg.PerPage)
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
}
response.OKWithMeta(c, roles, pg.Page, pg.PerPage, total)
c.JSON(http.StatusOK, serializeCustomRoles(roles))
}
// Create creates a new custom role for an account.
@@ -57,6 +60,10 @@ func (h *CustomRoleHandler) Create(c *gin.Context) {
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"`
@@ -80,7 +87,7 @@ func (h *CustomRoleHandler) Create(c *gin.Context) {
AuditedChanges: role,
})
response.Created(c, role)
c.JSON(http.StatusOK, serializeCustomRole(role))
}
// Get returns a single custom role by ID.
@@ -91,6 +98,10 @@ func (h *CustomRoleHandler) Get(c *gin.Context) {
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 {
@@ -105,7 +116,7 @@ func (h *CustomRoleHandler) Get(c *gin.Context) {
return
}
response.OK(c, role)
c.JSON(http.StatusOK, serializeCustomRole(role))
}
// Update updates an existing custom role.
@@ -117,6 +128,10 @@ func (h *CustomRoleHandler) Update(c *gin.Context) {
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 {
@@ -146,7 +161,7 @@ func (h *CustomRoleHandler) Update(c *gin.Context) {
AuditedChanges: role,
})
response.OK(c, role)
c.JSON(http.StatusOK, serializeCustomRole(role))
}
// Delete soft-deletes a custom role.
@@ -157,6 +172,10 @@ func (h *CustomRoleHandler) Delete(c *gin.Context) {
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 {
@@ -177,7 +196,7 @@ func (h *CustomRoleHandler) Delete(c *gin.Context) {
AuditedChanges: gin.H{"id": id},
})
response.NoContent(c)
c.Status(http.StatusOK)
}
// RegisterCustomRoleRoutes registers custom role routes on a gin.RouterGroup.
@@ -191,3 +210,35 @@ func RegisterCustomRoleRoutes(rg *gin.RouterGroup, h *CustomRoleHandler) {
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,
}
}
@@ -32,7 +32,7 @@ func (s *CustomRoleHandlerTestSuite) SetupSuite() {
Logger: logger.Default.LogMode(logger.Silent),
})
s.Require().NoError(err)
s.Require().NoError(db.AutoMigrate(&model.Account{}, &model.CustomRole{}, &model.Audit{}))
s.Require().NoError(db.AutoMigrate(&model.Account{}, &model.User{}, &model.AccountUser{}, &model.CustomRole{}, &model.Audit{}))
s.db = db
repo := repository.NewCustomRoleRepo(db)
@@ -57,23 +57,32 @@ func TestCustomRoleHandlerSuite(t *testing.T) {
func (s *CustomRoleHandlerTestSuite) SetupTest() {
s.Require().NoError(s.db.Exec("DELETE FROM audits").Error)
s.Require().NoError(s.db.Exec("DELETE FROM account_users").Error)
s.Require().NoError(s.db.Exec("DELETE FROM users").Error)
s.Require().NoError(s.db.Exec("DELETE FROM custom_roles").Error)
}
func (s *CustomRoleHandlerTestSuite) TestList_Success() {
r := gin.New()
r.GET("/api/v1/accounts/:account_id/custom_roles", s.handler.List)
r.GET("/api/v1/accounts/:account_id/custom_roles", withCustomRoleAdminContext(s.account.ID, s.handler.List))
s.Require().NoError(s.db.Create(&model.CustomRole{AccountID: s.account.ID, Name: "Supervisor", Permissions: `["conversation_manage"]`}).Error)
w := httptest.NewRecorder()
req, _ := http.NewRequest("GET", fmt.Sprintf("/api/v1/accounts/%d/custom_roles", s.account.ID), nil)
r.ServeHTTP(w, req)
assert.Equal(s.T(), http.StatusOK, w.Code)
var payload []map[string]interface{}
s.Require().NoError(json.Unmarshal(w.Body.Bytes(), &payload))
s.Require().Len(payload, 1)
s.Equal("Supervisor", payload[0]["name"])
s.NotContains(payload[0], "data")
s.NotContains(payload[0], "success")
}
func (s *CustomRoleHandlerTestSuite) TestCreate_BadRequest_EmptyBody() {
r := gin.New()
r.POST("/api/v1/accounts/:account_id/custom_roles", s.handler.Create)
r.POST("/api/v1/accounts/:account_id/custom_roles", withCustomRoleAdminContext(s.account.ID, s.handler.Create))
w := httptest.NewRecorder()
req, _ := http.NewRequest("POST", fmt.Sprintf("/api/v1/accounts/%d/custom_roles", s.account.ID), nil)
@@ -85,7 +94,7 @@ func (s *CustomRoleHandlerTestSuite) TestCreate_BadRequest_EmptyBody() {
func (s *CustomRoleHandlerTestSuite) TestGet_BadRequest_InvalidID() {
r := gin.New()
r.GET("/api/v1/accounts/:account_id/custom_roles/:id", s.handler.Get)
r.GET("/api/v1/accounts/:account_id/custom_roles/:id", withCustomRoleAdminContext(s.account.ID, s.handler.Get))
w := httptest.NewRecorder()
req, _ := http.NewRequest("GET", fmt.Sprintf("/api/v1/accounts/%d/custom_roles/abc", s.account.ID), nil)
@@ -96,7 +105,7 @@ func (s *CustomRoleHandlerTestSuite) TestGet_BadRequest_InvalidID() {
func (s *CustomRoleHandlerTestSuite) TestUpdate_BadRequest_InvalidID() {
r := gin.New()
r.PUT("/api/v1/accounts/:account_id/custom_roles/:id", s.handler.Update)
r.PUT("/api/v1/accounts/:account_id/custom_roles/:id", withCustomRoleAdminContext(s.account.ID, s.handler.Update))
w := httptest.NewRecorder()
req, _ := http.NewRequest("PUT", fmt.Sprintf("/api/v1/accounts/%d/custom_roles/abc", s.account.ID), nil)
@@ -108,7 +117,7 @@ func (s *CustomRoleHandlerTestSuite) TestUpdate_BadRequest_InvalidID() {
func (s *CustomRoleHandlerTestSuite) TestDelete_BadRequest_InvalidID() {
r := gin.New()
r.DELETE("/api/v1/accounts/:account_id/custom_roles/:id", s.handler.Delete)
r.DELETE("/api/v1/accounts/:account_id/custom_roles/:id", withCustomRoleAdminContext(s.account.ID, s.handler.Delete))
w := httptest.NewRecorder()
req, _ := http.NewRequest("DELETE", fmt.Sprintf("/api/v1/accounts/%d/custom_roles/abc", s.account.ID), nil)
@@ -121,59 +130,77 @@ func (s *CustomRoleHandlerTestSuite) TestCreate_Success() {
r := gin.New()
r.POST("/api/v1/accounts/:account_id/custom_roles", func(c *gin.Context) {
c.Set("account_id", uint(s.account.ID))
c.Set("role", "administrator")
s.handler.Create(c)
})
w := httptest.NewRecorder()
body := fmt.Sprintf(`{"custom_role":{"name":"test-role","permissions":{"conversation_manage":"full"}}}`)
body := `{"custom_role":{"name":"test-role","permissions":["conversation_manage","contact_manage"]}}`
req, _ := http.NewRequest("POST", fmt.Sprintf("/api/v1/accounts/%d/custom_roles", s.account.ID), bytes.NewBufferString(body))
req.Header.Set("Content-Type", "application/json")
r.ServeHTTP(w, req)
assert.Equal(s.T(), http.StatusCreated, w.Code)
assert.Equal(s.T(), http.StatusOK, w.Code)
var payload map[string]interface{}
s.Require().NoError(json.Unmarshal(w.Body.Bytes(), &payload))
s.Equal("test-role", payload["name"])
s.Equal([]interface{}{"conversation_manage", "contact_manage"}, payload["permissions"])
s.NotContains(payload, "data")
}
func (s *CustomRoleHandlerTestSuite) TestGet_Success() {
// Create a custom role first
role := &model.CustomRole{AccountID: s.account.ID, Name: "get-test-role", Permissions: "inbox_read"}
role := &model.CustomRole{AccountID: s.account.ID, Name: "get-test-role", Permissions: `["report_manage"]`}
s.Require().NoError(s.db.Create(role).Error)
r := gin.New()
r.GET("/api/v1/accounts/:account_id/custom_roles/:id", s.handler.Get)
r.GET("/api/v1/accounts/:account_id/custom_roles/:id", withCustomRoleAdminContext(s.account.ID, s.handler.Get))
w := httptest.NewRecorder()
req, _ := http.NewRequest("GET", fmt.Sprintf("/api/v1/accounts/%d/custom_roles/%d", s.account.ID, role.ID), nil)
r.ServeHTTP(w, req)
assert.Equal(s.T(), http.StatusOK, w.Code)
var payload map[string]interface{}
s.Require().NoError(json.Unmarshal(w.Body.Bytes(), &payload))
s.Equal([]interface{}{"report_manage"}, payload["permissions"])
}
func (s *CustomRoleHandlerTestSuite) TestUpdate_Success() {
role := &model.CustomRole{AccountID: s.account.ID, Name: "update-test-role", Permissions: "inbox_read"}
role := &model.CustomRole{AccountID: s.account.ID, Name: "update-test-role", Permissions: `["report_manage"]`}
s.Require().NoError(s.db.Create(role).Error)
r := gin.New()
r.PUT("/api/v1/accounts/:account_id/custom_roles/:id", func(c *gin.Context) {
c.Set("account_id", uint(s.account.ID))
c.Set("role", "administrator")
s.handler.Update(c)
})
w := httptest.NewRecorder()
body := fmt.Sprintf(`{"custom_role":{"name":"updated-role","permissions":{"conversation_manage":"full"}}}`)
body := `{"custom_role":{"name":"updated-role","permissions":["knowledge_base_manage"]}}`
req, _ := http.NewRequest("PUT", fmt.Sprintf("/api/v1/accounts/%d/custom_roles/%d", s.account.ID, role.ID), bytes.NewBufferString(body))
req.Header.Set("Content-Type", "application/json")
r.ServeHTTP(w, req)
assert.Equal(s.T(), http.StatusOK, w.Code)
var payload map[string]interface{}
s.Require().NoError(json.Unmarshal(w.Body.Bytes(), &payload))
s.Equal("updated-role", payload["name"])
s.Equal([]interface{}{"knowledge_base_manage"}, payload["permissions"])
}
func (s *CustomRoleHandlerTestSuite) TestDelete_Success() {
role := &model.CustomRole{AccountID: s.account.ID, Name: "delete-test-role", Permissions: "inbox_read"}
role := &model.CustomRole{AccountID: s.account.ID, Name: "delete-test-role", Permissions: `["conversation_manage"]`}
s.Require().NoError(s.db.Create(role).Error)
user := &model.User{AccountID: s.account.ID, Name: "Role User", Email: "role-user@example.com", Password: "pw", Active: true}
s.Require().NoError(s.db.Create(user).Error)
s.Require().NoError(s.db.Create(&model.AccountUser{AccountID: s.account.ID, UserID: user.ID, Role: "agent", CustomRoleID: role.ID}).Error)
r := gin.New()
r.DELETE("/api/v1/accounts/:account_id/custom_roles/:id", func(c *gin.Context) {
c.Set("account_id", uint(s.account.ID))
c.Set("role", "administrator")
s.handler.Delete(c)
})
@@ -181,7 +208,41 @@ func (s *CustomRoleHandlerTestSuite) TestDelete_Success() {
req, _ := http.NewRequest("DELETE", fmt.Sprintf("/api/v1/accounts/%d/custom_roles/%d", s.account.ID, role.ID), nil)
r.ServeHTTP(w, req)
assert.Equal(s.T(), http.StatusNoContent, w.Code)
assert.Equal(s.T(), http.StatusOK, w.Code)
s.Empty(w.Body.String())
var au model.AccountUser
s.Require().NoError(s.db.Where("account_id = ? AND user_id = ?", s.account.ID, user.ID).First(&au).Error)
s.Equal(uint(0), au.CustomRoleID)
s.Equal("agent", au.Role)
}
func (s *CustomRoleHandlerTestSuite) TestCreate_InvalidPermission() {
r := gin.New()
r.POST("/api/v1/accounts/:account_id/custom_roles", withCustomRoleAdminContext(s.account.ID, s.handler.Create))
w := httptest.NewRecorder()
body := `{"custom_role":{"name":"bad-role","permissions":["conversation_delete"]}}`
req, _ := http.NewRequest("POST", fmt.Sprintf("/api/v1/accounts/%d/custom_roles", s.account.ID), bytes.NewBufferString(body))
req.Header.Set("Content-Type", "application/json")
r.ServeHTTP(w, req)
assert.Equal(s.T(), http.StatusBadRequest, w.Code)
}
func (s *CustomRoleHandlerTestSuite) TestList_NonAdminDenied() {
r := gin.New()
r.GET("/api/v1/accounts/:account_id/custom_roles", func(c *gin.Context) {
c.Set("account_id", s.account.ID)
c.Set("role", "agent")
s.handler.List(c)
})
w := httptest.NewRecorder()
req, _ := http.NewRequest("GET", fmt.Sprintf("/api/v1/accounts/%d/custom_roles", s.account.ID), nil)
r.ServeHTTP(w, req)
assert.Equal(s.T(), http.StatusUnauthorized, w.Code)
}
func (s *CustomRoleHandlerTestSuite) TestMutations_WriteAuditEntries() {
@@ -190,22 +251,22 @@ func (s *CustomRoleHandlerTestSuite) TestMutations_WriteAuditEntries() {
r.PUT("/api/v1/accounts/:account_id/custom_roles/:id", withCustomRoleAuditContext(s.account.ID, 77, s.handler.Update))
r.DELETE("/api/v1/accounts/:account_id/custom_roles/:id", withCustomRoleAuditContext(s.account.ID, 77, s.handler.Delete))
createBody := `{"custom_role":{"name":"audit-role","permissions":{"conversation_manage":"full"}}}`
createBody := `{"custom_role":{"name":"audit-role","permissions":["conversation_manage"]}}`
createReq, _ := http.NewRequest("POST", fmt.Sprintf("/api/v1/accounts/%d/custom_roles", s.account.ID), bytes.NewBufferString(createBody))
createReq.Header.Set("Content-Type", "application/json")
createReq.Header.Set("X-Request-ID", "audit-create-req")
createReq.RemoteAddr = "203.0.113.20:1234"
createW := httptest.NewRecorder()
r.ServeHTTP(createW, createReq)
s.Require().Equal(http.StatusCreated, createW.Code)
s.Require().Equal(http.StatusOK, createW.Code)
var createResp struct {
Data model.CustomRole `json:"data"`
ID uint `json:"id"`
}
s.Require().NoError(json.Unmarshal(createW.Body.Bytes(), &createResp))
roleID := createResp.Data.ID
roleID := createResp.ID
updateBody := `{"custom_role":{"name":"audit-role-updated","permissions":{"contact_manage":"full"}}}`
updateBody := `{"custom_role":{"name":"audit-role-updated","permissions":["contact_manage"]}}`
updateReq, _ := http.NewRequest("PUT", fmt.Sprintf("/api/v1/accounts/%d/custom_roles/%d", s.account.ID, roleID), bytes.NewBufferString(updateBody))
updateReq.Header.Set("Content-Type", "application/json")
updateW := httptest.NewRecorder()
@@ -215,7 +276,7 @@ func (s *CustomRoleHandlerTestSuite) TestMutations_WriteAuditEntries() {
deleteReq, _ := http.NewRequest("DELETE", fmt.Sprintf("/api/v1/accounts/%d/custom_roles/%d", s.account.ID, roleID), nil)
deleteW := httptest.NewRecorder()
r.ServeHTTP(deleteW, deleteReq)
s.Require().Equal(http.StatusNoContent, deleteW.Code)
s.Require().Equal(http.StatusOK, deleteW.Code)
var audits []model.Audit
s.Require().NoError(s.db.Order("id ASC").Find(&audits).Error)
@@ -240,6 +301,15 @@ func withCustomRoleAuditContext(accountID uint, userID uint, h gin.HandlerFunc)
return func(c *gin.Context) {
c.Set("account_id", accountID)
c.Set("user_id", userID)
c.Set("role", "administrator")
h(c)
}
}
func withCustomRoleAdminContext(accountID uint, h gin.HandlerFunc) gin.HandlerFunc {
return func(c *gin.Context) {
c.Set("account_id", accountID)
c.Set("role", "administrator")
h(c)
}
}