ch some
This commit is contained in:
1 parent
28509eb4ca
commit
d1a6fcaadc
102 files changed
+2089
-1957
No files matched your search
@@ -7,6 +7,7 @@ import (
|
||||
"strings"
|
||||
|
||||
"online-back/internal/identity/permission"
|
||||
"online-back/internal/shared"
|
||||
"online-back/pkg/client/postgresql"
|
||||
"online-back/pkg/logging"
|
||||
"online-back/pkg/repository/genericrepo"
|
||||
@@ -28,9 +29,9 @@ func NewRepository(client postgresql.Client, logger *logging.Logger) permission.
|
||||
}
|
||||
}
|
||||
|
||||
const permissionColumns = `p.id, p.code, p.name, p.guard_name, p.created_at, p.updated_at`
|
||||
const permissionColumns = `p.id, p.code, p.name, p.guard_name, p.module, p.created_at, p.updated_at`
|
||||
|
||||
const permissionReturningColumns = `id, code, name, guard_name, created_at, updated_at`
|
||||
const permissionReturningColumns = `id, code, name, guard_name, module, created_at, updated_at`
|
||||
|
||||
func (r *repository) List(ctx context.Context, filter permission.ListFilter) (permission.ListPermissionDTO, error) {
|
||||
whereClause, args := buildListQuery(filter)
|
||||
@@ -46,10 +47,18 @@ func (r *repository) List(ctx context.Context, filter permission.ListFilter) (pe
|
||||
func buildListQuery(filter permission.ListFilter) (whereClause string, args []interface{}) {
|
||||
var conditions []string
|
||||
if filter.PermissionName != "" {
|
||||
args = append(args, likePattern(filter.PermissionName))
|
||||
args = append(args, shared.LikePattern(filter.PermissionName))
|
||||
n := len(args)
|
||||
conditions = append(conditions, fmt.Sprintf(`p.name ILIKE $%d`, n))
|
||||
}
|
||||
if filter.GuardName != "" {
|
||||
args = append(args, filter.GuardName)
|
||||
conditions = append(conditions, fmt.Sprintf(`p.guard_name = $%d`, len(args)))
|
||||
}
|
||||
if filter.Module != "" {
|
||||
args = append(args, filter.Module)
|
||||
conditions = append(conditions, fmt.Sprintf(`p.module = $%d`, len(args)))
|
||||
}
|
||||
|
||||
if len(conditions) == 0 {
|
||||
return "", args
|
||||
@@ -58,35 +67,57 @@ func buildListQuery(filter permission.ListFilter) (whereClause string, args []in
|
||||
return " WHERE " + strings.Join(conditions, " AND "), args
|
||||
}
|
||||
|
||||
func likePattern(term string) string {
|
||||
term = strings.ReplaceAll(term, `\`, `\\`)
|
||||
term = strings.ReplaceAll(term, `%`, `\%`)
|
||||
term = strings.ReplaceAll(term, `_`, `\_`)
|
||||
return "%" + term + "%"
|
||||
}
|
||||
|
||||
func (r *repository) GetByID(ctx context.Context, id int64) (permission.PermissionDTO, error) {
|
||||
return r.generic.GetByID(ctx, id)
|
||||
}
|
||||
|
||||
func (r *repository) Tree(ctx context.Context, guardName string) (permission.PermissionTreeDTO, error) {
|
||||
query := `SELECT ` + permissionColumns + ` FROM permissions p`
|
||||
var args []interface{}
|
||||
if guardName != "" {
|
||||
query += ` WHERE p.guard_name = $1`
|
||||
args = append(args, guardName)
|
||||
}
|
||||
query += ` ORDER BY p.guard_name, p.module, p.id`
|
||||
|
||||
rows, err := r.client.Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return permission.PermissionTreeDTO{}, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var items []permission.PermissionDTO
|
||||
for rows.Next() {
|
||||
item, err := scanPermission(rows)
|
||||
if err != nil {
|
||||
return permission.PermissionTreeDTO{}, err
|
||||
}
|
||||
items = append(items, item)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return permission.PermissionTreeDTO{}, err
|
||||
}
|
||||
return permission.BuildTree(items), nil
|
||||
}
|
||||
|
||||
func (r *repository) Create(ctx context.Context, dto permission.CreatePermissionDTO) (permission.PermissionDTO, error) {
|
||||
query := fmt.Sprintf(`
|
||||
INSERT INTO permissions (code, name, guard_name)
|
||||
VALUES ($1, $2, $3)
|
||||
INSERT INTO permissions (code, name, guard_name, module)
|
||||
VALUES ($1, $2, $3, $4)
|
||||
RETURNING %s`, permissionReturningColumns)
|
||||
|
||||
return scanPermission(r.client.QueryRow(ctx, query, dto.Code, dto.Name, dto.GuardName))
|
||||
return scanPermission(r.client.QueryRow(ctx, query, dto.Code, dto.Name, dto.GuardName, dto.Module))
|
||||
}
|
||||
|
||||
func (r *repository) Update(ctx context.Context, id int64, dto permission.UpdatePermissionDTO) (permission.PermissionDTO, error) {
|
||||
query := fmt.Sprintf(`
|
||||
UPDATE permissions SET
|
||||
code = $1, name = $2, guard_name = $3,
|
||||
code = $1, name = $2, guard_name = $3, module = $4,
|
||||
updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
|
||||
WHERE id = $4
|
||||
WHERE id = $5
|
||||
RETURNING %s`, permissionReturningColumns)
|
||||
|
||||
item, err := scanPermission(r.client.QueryRow(ctx, query, dto.Code, dto.Name, dto.GuardName, id))
|
||||
item, err := scanPermission(r.client.QueryRow(ctx, query, dto.Code, dto.Name, dto.GuardName, dto.Module, id))
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return permission.PermissionDTO{}, err
|
||||
}
|
||||
@@ -100,7 +131,7 @@ func (r *repository) Delete(ctx context.Context, id int64) error {
|
||||
func scanPermission(row genericrepo.Scanner) (permission.PermissionDTO, error) {
|
||||
var item permission.PermissionDTO
|
||||
if err := row.Scan(
|
||||
&item.Id, &item.Code, &item.Name, &item.GuardName, &item.CreatedAt, &item.UpdatedAt,
|
||||
&item.Id, &item.Code, &item.Name, &item.GuardName, &item.Module, &item.CreatedAt, &item.UpdatedAt,
|
||||
); err != nil {
|
||||
return permission.PermissionDTO{}, err
|
||||
}
|
||||
|
||||
@@ -7,24 +7,29 @@ type PermissionDTO struct {
|
||||
Code string `json:"code"`
|
||||
Name string `json:"name"`
|
||||
GuardName string `json:"guardName"`
|
||||
Module string `json:"module"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
}
|
||||
|
||||
type CreatePermissionDTO struct {
|
||||
Code string `json:"code" binding:"required"`
|
||||
Name string `json:"name" binding:"required"`
|
||||
GuardName string `json:"guardName" binding:"required"`
|
||||
Code string `json:"code" binding:"required"`
|
||||
Name string `json:"name" binding:"required"`
|
||||
GuardName string `json:"guardName" binding:"required,oneof=web operator admin"`
|
||||
Module string `json:"module" binding:"required"`
|
||||
}
|
||||
|
||||
type UpdatePermissionDTO struct {
|
||||
Code string `json:"code" binding:"required"`
|
||||
Name string `json:"name" binding:"required"`
|
||||
GuardName string `json:"guardName" binding:"required"`
|
||||
Code string `json:"code" binding:"required"`
|
||||
Name string `json:"name" binding:"required"`
|
||||
GuardName string `json:"guardName" binding:"required,oneof=web operator admin"`
|
||||
Module string `json:"module" binding:"required"`
|
||||
}
|
||||
|
||||
type ListFilter struct {
|
||||
PermissionName string
|
||||
GuardName string
|
||||
Module string
|
||||
Page int
|
||||
Limit int
|
||||
}
|
||||
@@ -33,3 +38,17 @@ type ListPermissionDTO struct {
|
||||
Count int64 `json:"count"`
|
||||
Permissions []PermissionDTO `json:"permissions"`
|
||||
}
|
||||
|
||||
type PermissionTreeDTO struct {
|
||||
Guards []GuardModulesDTO `json:"guards"`
|
||||
}
|
||||
|
||||
type GuardModulesDTO struct {
|
||||
GuardName string `json:"guardName"`
|
||||
Modules []ModulePermissionsDTO `json:"modules"`
|
||||
}
|
||||
|
||||
type ModulePermissionsDTO struct {
|
||||
Module string `json:"module"`
|
||||
Permissions []PermissionDTO `json:"permissions"`
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
|
||||
"online-back/internal/appresult"
|
||||
"online-back/internal/handlers"
|
||||
"online-back/internal/shared"
|
||||
"online-back/pkg/logging"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
@@ -28,6 +29,7 @@ func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler
|
||||
func (h *handler) Register(router *gin.RouterGroup) {
|
||||
group := router.Group(baseURL, appresult.JwtTokenCheck())
|
||||
group.GET("", h.list)
|
||||
group.GET("/tree", h.tree)
|
||||
group.GET("/:id", h.getByID)
|
||||
group.POST("", h.create)
|
||||
group.PUT("/:id", h.update)
|
||||
@@ -41,6 +43,8 @@ func (h *handler) Register(router *gin.RouterGroup) {
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param permission_name query string false "Filter by name"
|
||||
// @Param guard_name query string false "Filter by guard (web, operator, admin)"
|
||||
// @Param module query string false "Filter by saha (cards, loans, …)"
|
||||
// @Param page query int false "Page number" default(1)
|
||||
// @Param limit query int false "Items per page" default(10)
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
@@ -64,6 +68,32 @@ func (h *handler) list(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
|
||||
}
|
||||
|
||||
// tree godoc
|
||||
// @Summary Permission tree
|
||||
// @Description Returns permissions grouped as guard → module (saha) → permissions
|
||||
// @Tags permission
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param guard_name query string false "Filter by guard (web, operator, admin)"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /permissions/tree [get]
|
||||
func (h *handler) tree(c *gin.Context) {
|
||||
guardName := strings.TrimSpace(c.Query("guard_name"))
|
||||
if guardName == "" {
|
||||
guardName = strings.TrimSpace(c.Query("guardName"))
|
||||
}
|
||||
|
||||
result, err := h.repository.Tree(c.Request.Context(), guardName)
|
||||
if err != nil {
|
||||
h.logger.Errorf("permission tree failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
|
||||
}
|
||||
|
||||
// getByID godoc
|
||||
// @Summary Get permission by ID
|
||||
// @Description Returns a single permission
|
||||
@@ -77,7 +107,7 @@ func (h *handler) list(c *gin.Context) {
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /permissions/{id} [get]
|
||||
func (h *handler) getByID(c *gin.Context) {
|
||||
id, ok := parseID(c.Param("id"))
|
||||
id, ok := shared.ParseID(c.Param("id"))
|
||||
if !ok {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
@@ -115,6 +145,10 @@ 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 {
|
||||
@@ -141,7 +175,7 @@ func (h *handler) create(c *gin.Context) {
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /permissions/{id} [put]
|
||||
func (h *handler) update(c *gin.Context) {
|
||||
id, ok := parseID(c.Param("id"))
|
||||
id, ok := shared.ParseID(c.Param("id"))
|
||||
if !ok {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
@@ -152,6 +186,10 @@ 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) {
|
||||
@@ -180,7 +218,7 @@ func (h *handler) update(c *gin.Context) {
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /permissions/{id} [delete]
|
||||
func (h *handler) delete(c *gin.Context) {
|
||||
id, ok := parseID(c.Param("id"))
|
||||
id, ok := shared.ParseID(c.Param("id"))
|
||||
if !ok {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
@@ -198,24 +236,10 @@ func (h *handler) delete(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData("permission removed"))
|
||||
}
|
||||
|
||||
func parseID(raw string) (int64, bool) {
|
||||
id, err := strconv.ParseInt(raw, 10, 64)
|
||||
if err != nil || id <= 0 {
|
||||
return 0, false
|
||||
}
|
||||
return id, true
|
||||
}
|
||||
|
||||
const (
|
||||
defaultPage = 1
|
||||
defaultLimit = 10
|
||||
maxLimit = 100
|
||||
)
|
||||
|
||||
func parseListFilter(c *gin.Context) (ListFilter, bool) {
|
||||
filter := ListFilter{
|
||||
Page: defaultPage,
|
||||
Limit: defaultLimit,
|
||||
Page: shared.DefaultPage,
|
||||
Limit: shared.DefaultLimit,
|
||||
}
|
||||
|
||||
if raw := c.Query("page"); raw != "" {
|
||||
@@ -228,7 +252,7 @@ func parseListFilter(c *gin.Context) (ListFilter, bool) {
|
||||
|
||||
if raw := c.Query("limit"); raw != "" {
|
||||
limit, err := strconv.Atoi(raw)
|
||||
if err != nil || limit < 1 || limit > maxLimit {
|
||||
if err != nil || limit < 1 || limit > shared.MaxLimit {
|
||||
return ListFilter{}, false
|
||||
}
|
||||
filter.Limit = limit
|
||||
@@ -237,6 +261,24 @@ func parseListFilter(c *gin.Context) (ListFilter, bool) {
|
||||
if raw := strings.TrimSpace(c.Query("permission_name")); raw != "" {
|
||||
filter.PermissionName = raw
|
||||
}
|
||||
if raw := firstQuery(c, "guard_name", "guardName"); raw != "" {
|
||||
filter.GuardName = raw
|
||||
}
|
||||
if raw := firstQuery(c, "module"); raw != "" {
|
||||
filter.Module = raw
|
||||
}
|
||||
|
||||
return filter, true
|
||||
}
|
||||
|
||||
func firstQuery(c *gin.Context, keys ...string) string {
|
||||
for _, key := range keys {
|
||||
if key == "" {
|
||||
continue
|
||||
}
|
||||
if raw := strings.TrimSpace(c.Query(key)); raw != "" {
|
||||
return raw
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package permission
|
||||
|
||||
const (
|
||||
ModuleDashboard = "dashboard"
|
||||
ModuleCards = "cards"
|
||||
ModuleLoans = "loans"
|
||||
ModuleUsers = "users"
|
||||
ModuleRoles = "roles"
|
||||
ModuleBranches = "branches"
|
||||
ModuleProvinces = "provinces"
|
||||
ModuleActivityLogs = "activity-logs"
|
||||
ModuleBackups = "backups"
|
||||
ModuleCurrencies = "currencies"
|
||||
)
|
||||
|
||||
var moduleOrder = []string{
|
||||
ModuleDashboard,
|
||||
ModuleCards,
|
||||
ModuleLoans,
|
||||
ModuleUsers,
|
||||
ModuleRoles,
|
||||
ModuleBranches,
|
||||
ModuleProvinces,
|
||||
ModuleActivityLogs,
|
||||
ModuleBackups,
|
||||
ModuleCurrencies,
|
||||
}
|
||||
|
||||
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))
|
||||
copy(out, moduleOrder)
|
||||
return out
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import "context"
|
||||
|
||||
type Repository interface {
|
||||
List(ctx context.Context, filter ListFilter) (ListPermissionDTO, error)
|
||||
Tree(ctx context.Context, guardName string) (PermissionTreeDTO, error)
|
||||
GetByID(ctx context.Context, id int64) (PermissionDTO, error)
|
||||
Create(ctx context.Context, dto CreatePermissionDTO) (PermissionDTO, error)
|
||||
Update(ctx context.Context, id int64, dto UpdatePermissionDTO) (PermissionDTO, error)
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
package permission
|
||||
|
||||
import "sort"
|
||||
|
||||
type treeKey struct {
|
||||
guard string
|
||||
module string
|
||||
}
|
||||
|
||||
// BuildTree groups a flat permission list into guard → module → permissions
|
||||
// so the admin UI can render sahalar (cards, loans, …) as a tree.
|
||||
func BuildTree(items []PermissionDTO) PermissionTreeDTO {
|
||||
buckets := make(map[treeKey][]PermissionDTO)
|
||||
guardsSeen := make(map[string]struct{})
|
||||
modulesByGuard := make(map[string]map[string]struct{})
|
||||
|
||||
for _, item := range items {
|
||||
key := treeKey{guard: item.GuardName, module: item.Module}
|
||||
buckets[key] = append(buckets[key], item)
|
||||
guardsSeen[item.GuardName] = struct{}{}
|
||||
if modulesByGuard[item.GuardName] == nil {
|
||||
modulesByGuard[item.GuardName] = make(map[string]struct{})
|
||||
}
|
||||
modulesByGuard[item.GuardName][item.Module] = struct{}{}
|
||||
}
|
||||
|
||||
guards := make([]GuardModulesDTO, 0, len(guardsSeen))
|
||||
for _, guard := range orderedKeys(guardOrder, guardsSeen) {
|
||||
modulesSeen := modulesByGuard[guard]
|
||||
modules := make([]ModulePermissionsDTO, 0, len(modulesSeen))
|
||||
for _, module := range orderedKeys(moduleOrder, modulesSeen) {
|
||||
perms := buckets[treeKey{guard: guard, module: module}]
|
||||
if perms == nil {
|
||||
perms = []PermissionDTO{}
|
||||
}
|
||||
modules = append(modules, ModulePermissionsDTO{
|
||||
Module: module,
|
||||
Permissions: perms,
|
||||
})
|
||||
}
|
||||
guards = append(guards, GuardModulesDTO{
|
||||
GuardName: guard,
|
||||
Modules: modules,
|
||||
})
|
||||
}
|
||||
|
||||
return PermissionTreeDTO{Guards: guards}
|
||||
}
|
||||
|
||||
func orderedKeys(order []string, seen map[string]struct{}) []string {
|
||||
keys := make([]string, 0, len(seen))
|
||||
used := make(map[string]struct{}, len(seen))
|
||||
for _, name := range order {
|
||||
if _, ok := seen[name]; ok {
|
||||
keys = append(keys, name)
|
||||
used[name] = struct{}{}
|
||||
}
|
||||
}
|
||||
var extra []string
|
||||
for name := range seen {
|
||||
if _, ok := used[name]; !ok {
|
||||
extra = append(extra, name)
|
||||
}
|
||||
}
|
||||
sort.Strings(extra)
|
||||
return append(keys, extra...)
|
||||
}
|
||||
Reference in new issue
Block a user