rbac/controllers/rbac.go
zhangkun9038@dingtalk.com 375b305ab4 aliyun-deepseek-r1
2025-02-20 11:29:57 +08:00

54 lines
1.2 KiB
Go

package controllers
import (
"net/http"
"gitea.zjmud.com/phyer/rbac/models"
"github.com/gin-gonic/gin"
"gorm.io/gorm"
)
type RBACController struct {
DB *gorm.DB
Redis *redis.Client
}
func NewRBACController(db *gorm.DB, redis *redis.Client) *RBACController {
return &RBACController{DB: db, Redis: redis}
}
func (rc *RBACController) CreateRole(c *gin.Context) {
type CreateRoleRequest struct {
Name string `json:"name" binding:"required"`
Description string `json:"description"`
}
var req CreateRoleRequest
if err := c.ShouldBindJSON(&req); err != nil {
utils.Error(c, http.StatusBadRequest, "Invalid request format")
return
}
// 检查角色是否已存在
roleRepo := repositories.NewRoleRepository(rc.DB)
exists, err := roleRepo.ExistsByNameExcludeID(req.Name, 0)
if err != nil || exists {
utils.Error(c, http.StatusConflict, "Role already exists")
return
}
newRole := &models.Role{
Name: req.Name,
Description: req.Description,
}
if err := roleRepo.Create(newRole); err != nil {
utils.Error(c, http.StatusInternalServerError, "Failed to create role")
return
}
utils.Success(c, newRole)
}
// 其他RBAC相关方法...