From 848a07324f8fc9725d9707774faf1cce30f9b38c Mon Sep 17 00:00:00 2001 From: GuwandykA Date: Sat, 19 Sep 2026 02:40:38 +0500 Subject: [PATCH] rm -rf permission module --- db/seed.sql | 2 + docs/docs.go | 21 ++--- docs/swagger.json | 21 ++--- docs/swagger.yaml | 77 ++++++++++--------- internal/identity/permission/handler.go | 8 -- internal/identity/permission/module.go | 45 ++++------- .../identity/permissionrole/db/postgresql.go | 72 +++++++++++++---- internal/identity/permissionrole/dto.go | 12 ++- internal/identity/permissionrole/handler.go | 50 +++++++++--- internal/identity/permissionrole/storage.go | 4 +- 10 files changed, 193 insertions(+), 119 deletions(-) diff --git a/db/seed.sql b/db/seed.sql index 871a408..ff58148 100644 --- a/db/seed.sql +++ b/db/seed.sql @@ -155,6 +155,8 @@ INSERT INTO permissions (code, name, guard_name, module) VALUES ('backups.manage', 'Manage backups', 'admin', 'backups'), ('currencies.view', 'View currencies', 'admin', 'currencies'), ('currencies.manage', 'Manage currencies', 'admin', 'currencies'), + ('payment-settings.view', 'View payment settings', 'admin', 'payment-settings'), + ('payment-settings.manage', 'Manage payment settings', 'admin', 'payment-settings'), -- operator: two sahalar only ('cards', 'Cards', 'operator', 'cards'), ('loans', 'Loans', 'operator', 'loans'); diff --git a/docs/docs.go b/docs/docs.go index 4f87b9a..8156567 100644 --- a/docs/docs.go +++ b/docs/docs.go @@ -4977,14 +4977,14 @@ const docTemplate = `{ } } }, - "/permission-roles": { + "/permission-roles/bulk": { "post": { "security": [ { "BearerAuth": [] } ], - "description": "Creates a permission-role assignment, or updates the existing pair if already assigned", + "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", "consumes": [ "application/json" ], @@ -4994,15 +4994,15 @@ const docTemplate = `{ "tags": [ "permission-roles" ], - "summary": "Assign permission to role", + "summary": "Set a role's permissions", "parameters": [ { - "description": "Permission-role payload", + "description": "Role + the permission IDs it should have", "name": "body", "in": "body", "required": true, "schema": { - "$ref": "#/definitions/permissionrole.CreatePermissionRoleDTO" + "$ref": "#/definitions/permissionrole.SetRolePermissionsDTO" } } ], @@ -9359,15 +9359,18 @@ const docTemplate = `{ } } }, - "permissionrole.CreatePermissionRoleDTO": { + "permissionrole.SetRolePermissionsDTO": { "type": "object", "required": [ - "permissionId", + "permissionIds", "roleId" ], "properties": { - "permissionId": { - "type": "integer" + "permissionIds": { + "type": "array", + "items": { + "type": "integer" + } }, "roleId": { "type": "integer" diff --git a/docs/swagger.json b/docs/swagger.json index f6aa833..a7676ce 100644 --- a/docs/swagger.json +++ b/docs/swagger.json @@ -4971,14 +4971,14 @@ } } }, - "/permission-roles": { + "/permission-roles/bulk": { "post": { "security": [ { "BearerAuth": [] } ], - "description": "Creates a permission-role assignment, or updates the existing pair if already assigned", + "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", "consumes": [ "application/json" ], @@ -4988,15 +4988,15 @@ "tags": [ "permission-roles" ], - "summary": "Assign permission to role", + "summary": "Set a role's permissions", "parameters": [ { - "description": "Permission-role payload", + "description": "Role + the permission IDs it should have", "name": "body", "in": "body", "required": true, "schema": { - "$ref": "#/definitions/permissionrole.CreatePermissionRoleDTO" + "$ref": "#/definitions/permissionrole.SetRolePermissionsDTO" } } ], @@ -9353,15 +9353,18 @@ } } }, - "permissionrole.CreatePermissionRoleDTO": { + "permissionrole.SetRolePermissionsDTO": { "type": "object", "required": [ - "permissionId", + "permissionIds", "roleId" ], "properties": { - "permissionId": { - "type": "integer" + "permissionIds": { + "type": "array", + "items": { + "type": "integer" + } }, "roleId": { "type": "integer" diff --git a/docs/swagger.yaml b/docs/swagger.yaml index f726602..356d5d6 100644 --- a/docs/swagger.yaml +++ b/docs/swagger.yaml @@ -1364,14 +1364,16 @@ definitions: - module - name type: object - permissionrole.CreatePermissionRoleDTO: + permissionrole.SetRolePermissionsDTO: properties: - permissionId: - type: integer + permissionIds: + items: + type: integer + type: array roleId: type: integer required: - - permissionId + - permissionIds - roleId type: object province.CreateProvinceDTO: @@ -4941,39 +4943,6 @@ paths: summary: Update payment settings tags: - payment-settings - /permission-roles: - post: - consumes: - - application/json - description: Creates a permission-role assignment, or updates the existing pair - if already assigned - parameters: - - description: Permission-role payload - in: body - name: body - required: true - schema: - $ref: '#/definitions/permissionrole.CreatePermissionRoleDTO' - produces: - - application/json - responses: - "201": - description: Created - schema: - $ref: '#/definitions/appresult.AppSuccess' - "400": - description: Bad Request - schema: - $ref: '#/definitions/appresult.AppError' - "500": - description: Internal Server Error - schema: - $ref: '#/definitions/appresult.AppError' - security: - - BearerAuth: [] - summary: Assign permission to role - tags: - - permission-roles /permission-roles/{id}: delete: description: Deletes a permission-role assignment @@ -5007,6 +4976,40 @@ paths: summary: Remove permission from role tags: - permission-roles + /permission-roles/bulk: + post: + consumes: + - application/json + 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 + parameters: + - description: Role + the permission IDs it should have + in: body + name: body + required: true + schema: + $ref: '#/definitions/permissionrole.SetRolePermissionsDTO' + produces: + - application/json + responses: + "201": + description: Created + schema: + $ref: '#/definitions/appresult.AppSuccess' + "400": + description: Bad Request + schema: + $ref: '#/definitions/appresult.AppError' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/appresult.AppError' + security: + - BearerAuth: [] + summary: Set a role's permissions + tags: + - permission-roles /permissions: get: description: Returns paginated permissions with optional filters diff --git a/internal/identity/permission/handler.go b/internal/identity/permission/handler.go index ea6ff74..2628136 100644 --- a/internal/identity/permission/handler.go +++ b/internal/identity/permission/handler.go @@ -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) { diff --git a/internal/identity/permission/module.go b/internal/identity/permission/module.go index d196f59..a4562d2 100644 --- a/internal/identity/permission/module.go +++ b/internal/identity/permission/module.go @@ -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)) diff --git a/internal/identity/permissionrole/db/postgresql.go b/internal/identity/permissionrole/db/postgresql.go index 707fd77..8e114b0 100644 --- a/internal/identity/permissionrole/db/postgresql.go +++ b/internal/identity/permissionrole/db/postgresql.go @@ -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 { diff --git a/internal/identity/permissionrole/dto.go b/internal/identity/permissionrole/dto.go index 0321972..e8a7e3c 100644 --- a/internal/identity/permissionrole/dto.go +++ b/internal/identity/permissionrole/dto.go @@ -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"` } diff --git a/internal/identity/permissionrole/handler.go b/internal/identity/permissionrole/handler.go index 453358b..e02225d 100644 --- a/internal/identity/permissionrole/handler.go +++ b/internal/identity/permissionrole/handler.go @@ -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")) } diff --git a/internal/identity/permissionrole/storage.go b/internal/identity/permissionrole/storage.go index d8d6363..6a001ca 100644 --- a/internal/identity/permissionrole/storage.go +++ b/internal/identity/permissionrole/storage.go @@ -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 }