You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
OneAuth/api/role/patch.go

55 lines
1.4 KiB
Go

1 week ago
// Copyright (C) 2024 veypi <i@veypi.com>
// 2025-03-04 16:08:06
// Distributed under terms of the MIT license.
package role
import (
"github.com/veypi/vbase/cfg"
"github.com/veypi/vbase/models"
"github.com/veypi/vigo"
)
type PatchRequest struct {
RoleID string `src:"path@role_id" desc:"角色ID"`
Name *string `json:"name,omitempty" src:"json" desc:"角色名称"`
Description *string `json:"description,omitempty" src:"json" desc:"描述"`
PolicyIDs []string `json:"policy_ids,omitempty" src:"json" desc:"策略ID列表"`
}
func patch(x *vigo.X, req *PatchRequest) (*models.Role, error) {
var role models.Role
if err := cfg.DB().First(&role, "id = ?", req.RoleID).Error; err != nil {
return nil, vigo.ErrNotFound
}
// 系统角色不允许修改
if role.IsSystem {
return nil, vigo.ErrForbidden.WithString("system roles cannot be modified")
}
updates := make(map[string]any)
if req.Name != nil {
updates["name"] = *req.Name
}
if req.Description != nil {
updates["description"] = *req.Description
}
if req.PolicyIDs != nil {
policyIDsStr := ""
for i, id := range req.PolicyIDs {
if i > 0 {
policyIDsStr += ","
}
policyIDsStr += id
}
updates["policy_ids"] = policyIDsStr
}
if err := cfg.DB().Model(&role).Updates(updates).Error; err != nil {
return nil, vigo.ErrInternalServer.WithError(err)
}
return &role, nil
}