rm -rf permission module
This commit is contained in:
@@ -145,10 +145,6 @@ func (h *handler) create(c *gin.Context) {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
if !IsKnownModule(dto.Module) {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
item, err := h.repository.Create(c.Request.Context(), dto)
|
||||
if err != nil {
|
||||
@@ -186,10 +182,6 @@ func (h *handler) update(c *gin.Context) {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
if !IsKnownModule(dto.Module) {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
item, err := h.repository.Update(c.Request.Context(), id, dto)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
|
||||
@@ -1,18 +1,24 @@
|
||||
package permission
|
||||
|
||||
const (
|
||||
ModuleDashboard = "dashboard"
|
||||
ModuleCards = "cards"
|
||||
ModuleLoans = "loans"
|
||||
ModuleUsers = "users"
|
||||
ModuleRoles = "roles"
|
||||
ModuleBranches = "branches"
|
||||
ModuleProvinces = "provinces"
|
||||
ModuleActivityLogs = "activity-logs"
|
||||
ModuleBackups = "backups"
|
||||
ModuleCurrencies = "currencies"
|
||||
ModuleDashboard = "dashboard"
|
||||
ModuleCards = "cards"
|
||||
ModuleLoans = "loans"
|
||||
ModuleUsers = "users"
|
||||
ModuleRoles = "roles"
|
||||
ModuleBranches = "branches"
|
||||
ModuleProvinces = "provinces"
|
||||
ModuleActivityLogs = "activity-logs"
|
||||
ModuleBackups = "backups"
|
||||
ModuleCurrencies = "currencies"
|
||||
ModulePaymentSettings = "payment-settings"
|
||||
)
|
||||
|
||||
// moduleOrder is a display-order hint only, not a whitelist: the
|
||||
// permissions.module field accepts any value (see permission.Repository.
|
||||
// Modules, which lists what's actually in use). BuildTree/GroupProfileModules
|
||||
// sort these first, then append any other module alphabetically, so a
|
||||
// newly invented module still renders correctly without editing this file.
|
||||
var moduleOrder = []string{
|
||||
ModuleDashboard,
|
||||
ModuleCards,
|
||||
@@ -24,28 +30,11 @@ var moduleOrder = []string{
|
||||
ModuleActivityLogs,
|
||||
ModuleBackups,
|
||||
ModuleCurrencies,
|
||||
ModulePaymentSettings,
|
||||
}
|
||||
|
||||
var guardOrder = []string{"operator", "admin", "web"}
|
||||
|
||||
var knownModules = map[string]struct{}{
|
||||
ModuleDashboard: {},
|
||||
ModuleCards: {},
|
||||
ModuleLoans: {},
|
||||
ModuleUsers: {},
|
||||
ModuleRoles: {},
|
||||
ModuleBranches: {},
|
||||
ModuleProvinces: {},
|
||||
ModuleActivityLogs: {},
|
||||
ModuleBackups: {},
|
||||
ModuleCurrencies: {},
|
||||
}
|
||||
|
||||
func IsKnownModule(module string) bool {
|
||||
_, ok := knownModules[module]
|
||||
return ok
|
||||
}
|
||||
|
||||
// ModuleOrder is the display order of sahalar in trees and profile.
|
||||
func ModuleOrder() []string {
|
||||
out := make([]string, len(moduleOrder))
|
||||
|
||||
@@ -21,22 +21,64 @@ func NewRepository(client postgresql.Client, logger *logging.Logger) permissionr
|
||||
return &repository{client: client, logger: logger}
|
||||
}
|
||||
|
||||
func (r *repository) Create(ctx context.Context, dto permissionrole.CreatePermissionRoleDTO) (permissionrole.PermissionRoleDTO, error) {
|
||||
query := `
|
||||
WITH upserted AS (
|
||||
INSERT INTO permission_role (permission_id, role_id)
|
||||
VALUES ($1, $2)
|
||||
ON CONFLICT (permission_id, role_id) WHERE deleted_at IS NULL DO UPDATE SET
|
||||
updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
|
||||
RETURNING id, permission_id, role_id, created_at, updated_at
|
||||
)
|
||||
SELECT upserted.id, upserted.permission_id, p.name, upserted.role_id, r.name, upserted.created_at, upserted.updated_at
|
||||
FROM upserted
|
||||
JOIN permissions p ON p.id = upserted.permission_id
|
||||
JOIN roles r ON r.id = upserted.role_id`
|
||||
// SetPermissions replaces dto.RoleId's whole permission set with
|
||||
// dto.PermissionIds inside one transaction: pairs not in the list are
|
||||
// soft-deleted, pairs in the list are upserted. Both statements run on the
|
||||
// same tx so a role never ends up with permissions only half-updated.
|
||||
func (r *repository) SetPermissions(ctx context.Context, dto permissionrole.SetRolePermissionsDTO) ([]permissionrole.PermissionRoleDTO, error) {
|
||||
tx, err := r.client.Begin(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
|
||||
row := r.client.QueryRow(ctx, query, dto.PermissionId, dto.RoleId)
|
||||
return scanPermissionRole(row)
|
||||
_, err = tx.Exec(ctx,
|
||||
`UPDATE permission_role SET deleted_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
|
||||
WHERE role_id = $1 AND deleted_at IS NULL AND NOT (permission_id = ANY($2::bigint[]))`,
|
||||
dto.RoleId, dto.PermissionIds,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var items []permissionrole.PermissionRoleDTO
|
||||
if len(dto.PermissionIds) > 0 {
|
||||
query := `
|
||||
WITH upserted AS (
|
||||
INSERT INTO permission_role (permission_id, role_id)
|
||||
SELECT unnest($1::bigint[]), $2
|
||||
ON CONFLICT (permission_id, role_id) WHERE deleted_at IS NULL DO UPDATE SET
|
||||
updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
|
||||
RETURNING id, permission_id, role_id, created_at, updated_at
|
||||
)
|
||||
SELECT upserted.id, upserted.permission_id, p.name, upserted.role_id, r.name, upserted.created_at, upserted.updated_at
|
||||
FROM upserted
|
||||
JOIN permissions p ON p.id = upserted.permission_id
|
||||
JOIN roles r ON r.id = upserted.role_id`
|
||||
|
||||
rows, err := tx.Query(ctx, query, dto.PermissionIds, dto.RoleId)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for rows.Next() {
|
||||
item, err := scanPermissionRole(rows)
|
||||
if err != nil {
|
||||
rows.Close()
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, item)
|
||||
}
|
||||
rowsErr := rows.Err()
|
||||
rows.Close()
|
||||
if rowsErr != nil {
|
||||
return nil, rowsErr
|
||||
}
|
||||
}
|
||||
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
func (r *repository) Delete(ctx context.Context, id int64) error {
|
||||
|
||||
@@ -12,7 +12,13 @@ type PermissionRoleDTO struct {
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
}
|
||||
|
||||
type CreatePermissionRoleDTO struct {
|
||||
PermissionId int64 `json:"permissionId" binding:"required"`
|
||||
RoleId int64 `json:"roleId" binding:"required"`
|
||||
// SetRolePermissionsDTO replaces a role's whole permission set: after the
|
||||
// call, the role is assigned exactly PermissionIds - pairs not listed are
|
||||
// removed, pairs listed but missing are added, and pairs already present
|
||||
// are left as-is. An empty PermissionIds clears all permissions from the
|
||||
// role. This is the only way to attach/update a role's permissions - there
|
||||
// is no single-pair create endpoint.
|
||||
type SetRolePermissionsDTO struct {
|
||||
RoleId int64 `json:"roleId" binding:"required"`
|
||||
PermissionIds []int64 `json:"permissionIds" binding:"required"`
|
||||
}
|
||||
|
||||
@@ -1,12 +1,16 @@
|
||||
package permissionrole
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"online-back/internal/appresult"
|
||||
"online-back/internal/handlers"
|
||||
"online-back/internal/shared"
|
||||
"online-back/pkg/logging"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/jackc/pgx/v4"
|
||||
)
|
||||
|
||||
const baseURL = "/permission-roles"
|
||||
@@ -22,24 +26,37 @@ func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler
|
||||
|
||||
func (h *handler) Register(router *gin.RouterGroup) {
|
||||
group := router.Group(baseURL, appresult.JwtTokenCheck())
|
||||
group.POST("", h.create)
|
||||
group.POST("/bulk", h.setPermissions)
|
||||
group.DELETE("/:id", h.delete)
|
||||
}
|
||||
|
||||
// create godoc
|
||||
// @Summary Assign permission to role
|
||||
// @Description Creates a permission-role assignment, or updates the existing pair if already assigned
|
||||
// setPermissions godoc
|
||||
// @Summary Set a role's permissions
|
||||
// @Description Replaces roleId's whole permission set with permissionIds - pairs not listed are removed, missing ones are added, an empty list clears all permissions from the role
|
||||
// @Tags permission-roles
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param body body CreatePermissionRoleDTO true "Permission-role payload"
|
||||
// @Param body body SetRolePermissionsDTO true "Role + the permission IDs it should have"
|
||||
// @Success 201 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /permission-roles [post]
|
||||
func (h *handler) create(c *gin.Context) {
|
||||
shared.CreateAssoc[CreatePermissionRoleDTO, PermissionRoleDTO](c, h.logger, h.repository, "permission role")
|
||||
// @Router /permission-roles/bulk [post]
|
||||
func (h *handler) setPermissions(c *gin.Context) {
|
||||
var dto SetRolePermissionsDTO
|
||||
if err := c.ShouldBindJSON(&dto); err != nil {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
items, err := h.repository.SetPermissions(c.Request.Context(), dto)
|
||||
if err != nil {
|
||||
h.logger.Errorf("set role permissions failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusCreated, appresult.SuccessWithData(items))
|
||||
}
|
||||
|
||||
// delete godoc
|
||||
@@ -55,5 +72,20 @@ func (h *handler) create(c *gin.Context) {
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /permission-roles/{id} [delete]
|
||||
func (h *handler) delete(c *gin.Context) {
|
||||
shared.DeleteAssoc[CreatePermissionRoleDTO, PermissionRoleDTO](c, h.logger, h.repository, "permission role")
|
||||
id, ok := shared.ParseID(c.Param("id"))
|
||||
if !ok {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.repository.Delete(c.Request.Context(), id); errors.Is(err, pgx.ErrNoRows) {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
|
||||
return
|
||||
} else if err != nil {
|
||||
h.logger.Errorf("delete permission role failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData("permission role removed"))
|
||||
}
|
||||
|
||||
@@ -3,6 +3,8 @@ package permissionrole
|
||||
import "context"
|
||||
|
||||
type Repository interface {
|
||||
Create(ctx context.Context, dto CreatePermissionRoleDTO) (PermissionRoleDTO, error)
|
||||
// SetPermissions replaces the role's permission set. See
|
||||
// SetRolePermissionsDTO for the exact (add/remove/clear) semantics.
|
||||
SetPermissions(ctx context.Context, dto SetRolePermissionsDTO) ([]PermissionRoleDTO, error)
|
||||
Delete(ctx context.Context, id int64) error
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user