changed role permission
This commit is contained in:
1 parent
f0ecf23879
commit
323e131216
74 files changed
+2915
-4713
No files matched your search
@@ -4,99 +4,184 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"online-back/internal/identity/rbac"
|
||||
"online-back/internal/identity/rbac/perm"
|
||||
"online-back/internal/identity/role"
|
||||
"online-back/internal/shared"
|
||||
"online-back/pkg/client/postgresql"
|
||||
"online-back/pkg/logging"
|
||||
"online-back/pkg/repository/genericrepo"
|
||||
|
||||
"github.com/jackc/pgconn"
|
||||
"github.com/jackc/pgx/v4"
|
||||
)
|
||||
|
||||
type repository struct {
|
||||
client postgresql.Client
|
||||
generic *genericrepo.Repository[role.RoleDTO]
|
||||
logger *logging.Logger
|
||||
client postgresql.Client
|
||||
logger *logging.Logger
|
||||
}
|
||||
|
||||
func NewRepository(client postgresql.Client, logger *logging.Logger) role.Repository {
|
||||
return &repository{
|
||||
client: client,
|
||||
generic: genericrepo.New(client, "roles r", roleColumns, scanRole),
|
||||
logger: logger,
|
||||
}
|
||||
return &repository{client: client, logger: logger}
|
||||
}
|
||||
|
||||
const roleColumns = `r.id, r.code, r.name, r.guard_name, r.created_at, r.updated_at`
|
||||
|
||||
const roleReturningColumns = `id, code, name, guard_name, created_at, updated_at`
|
||||
const roleColumns = `r.id, r.code, r.name, r.scope, r.is_super, r.is_system,
|
||||
ARRAY(SELECT rp.permission_code::text FROM role_permissions rp WHERE rp.role_id = r.id ORDER BY 1),
|
||||
(SELECT COUNT(*) FROM users u WHERE u.role_id = r.id AND u.deleted_at IS NULL),
|
||||
r.created_at, r.updated_at`
|
||||
|
||||
func (r *repository) List(ctx context.Context, filter role.ListFilter) (role.ListRoleDTO, error) {
|
||||
whereClause, args := buildListQuery(filter)
|
||||
where := ` WHERE r.deleted_at IS NULL`
|
||||
var args []interface{}
|
||||
if filter.RoleName != "" {
|
||||
args = append(args, shared.LikePattern(filter.RoleName))
|
||||
where += fmt.Sprintf(` AND (r.name ILIKE $%d OR r.code ILIKE $%d)`, len(args), len(args))
|
||||
}
|
||||
|
||||
items, count, err := r.generic.List(ctx, whereClause, args, filter.Page, filter.Limit, "id")
|
||||
if err != nil {
|
||||
var count int64
|
||||
if err := r.client.QueryRow(ctx, `SELECT COUNT(*) FROM roles r`+where, args...).Scan(&count); err != nil {
|
||||
return role.ListRoleDTO{}, err
|
||||
}
|
||||
|
||||
args = append(args, filter.Limit, (filter.Page-1)*filter.Limit)
|
||||
query := fmt.Sprintf(`SELECT %s FROM roles r%s ORDER BY r.id LIMIT $%d OFFSET $%d`,
|
||||
roleColumns, where, len(args)-1, len(args))
|
||||
rows, err := r.client.Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return role.ListRoleDTO{}, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
items := []role.RoleDTO{}
|
||||
for rows.Next() {
|
||||
item, err := scanRole(rows)
|
||||
if err != nil {
|
||||
return role.ListRoleDTO{}, err
|
||||
}
|
||||
items = append(items, item)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return role.ListRoleDTO{}, err
|
||||
}
|
||||
return role.ListRoleDTO{Count: count, Roles: items}, nil
|
||||
}
|
||||
|
||||
func buildListQuery(filter role.ListFilter) (whereClause string, args []interface{}) {
|
||||
var conditions []string
|
||||
if filter.RoleName != "" {
|
||||
args = append(args, shared.LikePattern(filter.RoleName))
|
||||
n := len(args)
|
||||
conditions = append(conditions, fmt.Sprintf(`r.name ILIKE $%d`, n))
|
||||
}
|
||||
|
||||
if len(conditions) == 0 {
|
||||
return "", args
|
||||
}
|
||||
|
||||
return " WHERE " + strings.Join(conditions, " AND "), args
|
||||
func (r *repository) GetByID(ctx context.Context, id int64) (role.RoleDTO, error) {
|
||||
return getByID(ctx, r.client, id)
|
||||
}
|
||||
|
||||
func (r *repository) GetByID(ctx context.Context, id int64) (role.RoleDTO, error) {
|
||||
return r.generic.GetByID(ctx, id)
|
||||
type querier interface {
|
||||
QueryRow(ctx context.Context, sql string, args ...interface{}) pgx.Row
|
||||
}
|
||||
|
||||
func getByID(ctx context.Context, q querier, id int64) (role.RoleDTO, error) {
|
||||
return scanRole(q.QueryRow(ctx, `SELECT `+roleColumns+` FROM roles r WHERE r.id = $1 AND r.deleted_at IS NULL`, id))
|
||||
}
|
||||
|
||||
func (r *repository) Create(ctx context.Context, dto role.CreateRoleDTO) (role.RoleDTO, error) {
|
||||
query := fmt.Sprintf(`
|
||||
INSERT INTO roles (code, name, guard_name)
|
||||
VALUES ($1, $2, $3)
|
||||
RETURNING %s`, roleReturningColumns)
|
||||
tx, err := r.client.Begin(ctx)
|
||||
if err != nil {
|
||||
return role.RoleDTO{}, err
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
|
||||
return scanRole(r.client.QueryRow(ctx, query, dto.Code, dto.Name, dto.GuardName))
|
||||
var id int64
|
||||
err = tx.QueryRow(ctx, `INSERT INTO roles (code, name, scope) VALUES ($1, $2, $3) RETURNING id`,
|
||||
dto.Code, dto.Name, string(dto.Scope)).Scan(&id)
|
||||
if isUniqueViolation(err) {
|
||||
return role.RoleDTO{}, role.ErrDuplicateCode
|
||||
}
|
||||
if err != nil {
|
||||
return role.RoleDTO{}, err
|
||||
}
|
||||
if err := setPermissions(ctx, tx, id, dto.Permissions); err != nil {
|
||||
return role.RoleDTO{}, err
|
||||
}
|
||||
|
||||
item, err := getByID(ctx, tx, id)
|
||||
if err != nil {
|
||||
return role.RoleDTO{}, err
|
||||
}
|
||||
return item, tx.Commit(ctx)
|
||||
}
|
||||
|
||||
func (r *repository) Update(ctx context.Context, id int64, dto role.UpdateRoleDTO) (role.RoleDTO, error) {
|
||||
query := fmt.Sprintf(`
|
||||
UPDATE roles SET
|
||||
code = $1, name = $2, guard_name = $3,
|
||||
updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
|
||||
WHERE id = $4 AND deleted_at IS NULL
|
||||
RETURNING %s`, roleReturningColumns)
|
||||
|
||||
item, err := scanRole(r.client.QueryRow(ctx, query, dto.Code, dto.Name, dto.GuardName, id))
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
tx, err := r.client.Begin(ctx)
|
||||
if err != nil {
|
||||
return role.RoleDTO{}, err
|
||||
}
|
||||
return item, err
|
||||
defer tx.Rollback(ctx)
|
||||
|
||||
tag, err := tx.Exec(ctx, `
|
||||
UPDATE roles SET name = $1, scope = $2, updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
|
||||
WHERE id = $3 AND deleted_at IS NULL`, dto.Name, string(dto.Scope), id)
|
||||
if err != nil {
|
||||
return role.RoleDTO{}, err
|
||||
}
|
||||
if tag.RowsAffected() == 0 {
|
||||
return role.RoleDTO{}, pgx.ErrNoRows
|
||||
}
|
||||
if err := setPermissions(ctx, tx, id, dto.Permissions); err != nil {
|
||||
return role.RoleDTO{}, err
|
||||
}
|
||||
|
||||
item, err := getByID(ctx, tx, id)
|
||||
if err != nil {
|
||||
return role.RoleDTO{}, err
|
||||
}
|
||||
return item, tx.Commit(ctx)
|
||||
}
|
||||
|
||||
// setPermissions makes the role hold exactly codes.
|
||||
func setPermissions(ctx context.Context, tx pgx.Tx, roleID int64, codes []perm.Code) error {
|
||||
values := make([]string, len(codes))
|
||||
for i, code := range codes {
|
||||
values[i] = string(code)
|
||||
}
|
||||
if _, err := tx.Exec(ctx,
|
||||
`DELETE FROM role_permissions WHERE role_id = $1 AND NOT (permission_code = ANY($2::varchar[]))`,
|
||||
roleID, values); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err := tx.Exec(ctx, `
|
||||
INSERT INTO role_permissions (role_id, permission_code)
|
||||
SELECT $1, unnest($2::varchar[])
|
||||
ON CONFLICT DO NOTHING`, roleID, values)
|
||||
return err
|
||||
}
|
||||
|
||||
func (r *repository) Delete(ctx context.Context, id int64) error {
|
||||
return r.generic.Delete(ctx, id)
|
||||
var inUse bool
|
||||
if err := r.client.QueryRow(ctx,
|
||||
`SELECT EXISTS (SELECT 1 FROM users WHERE role_id = $1 AND deleted_at IS NULL)`, id).Scan(&inUse); err != nil {
|
||||
return err
|
||||
}
|
||||
if inUse {
|
||||
return role.ErrInUse
|
||||
}
|
||||
return genericrepo.Delete(ctx, r.client, "roles", id)
|
||||
}
|
||||
|
||||
func scanRole(row genericrepo.Scanner) (role.RoleDTO, error) {
|
||||
var item role.RoleDTO
|
||||
var scope string
|
||||
var codes []string
|
||||
if err := row.Scan(
|
||||
&item.Id, &item.Code, &item.Name, &item.GuardName, &item.CreatedAt, &item.UpdatedAt,
|
||||
&item.Id, &item.Code, &item.Name, &scope, &item.IsSuper, &item.IsSystem, &codes, &item.UsersCount,
|
||||
&item.CreatedAt, &item.UpdatedAt,
|
||||
); err != nil {
|
||||
return role.RoleDTO{}, err
|
||||
}
|
||||
item.Scope = rbac.Scope(scope)
|
||||
item.Permissions = make([]perm.Code, len(codes))
|
||||
for i, code := range codes {
|
||||
item.Permissions[i] = perm.Code(code)
|
||||
}
|
||||
return item, nil
|
||||
}
|
||||
|
||||
func isUniqueViolation(err error) bool {
|
||||
var pgErr *pgconn.PgError
|
||||
return errors.As(err, &pgErr) && pgErr.Code == "23505"
|
||||
}
|
||||
Reference in new issue
Block a user