194 lines
5.6 KiB
Go
194 lines
5.6 KiB
Go
package db
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
|
|
"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
|
|
logger *logging.Logger
|
|
}
|
|
|
|
func NewRepository(client postgresql.Client, logger *logging.Logger) role.Repository {
|
|
return &repository{client: client, logger: logger}
|
|
}
|
|
|
|
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) {
|
|
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))
|
|
}
|
|
|
|
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 r.id, r.code, r.name, r.scope,
|
|
(SELECT COUNT(*) FROM users u WHERE u.role_id = r.id AND u.deleted_at IS NULL)
|
|
FROM roles r%s ORDER BY r.id LIMIT $%d OFFSET $%d`,
|
|
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.RoleListItemDTO{}
|
|
for rows.Next() {
|
|
var item role.RoleListItemDTO
|
|
var scope string
|
|
if err := rows.Scan(&item.Id, &item.Code, &item.Name, &scope, &item.UsersCount); err != nil {
|
|
return role.ListRoleDTO{}, err
|
|
}
|
|
item.Scope = rbac.Scope(scope)
|
|
item.ScopeName = item.Scope.Name()
|
|
items = append(items, item)
|
|
}
|
|
if err := rows.Err(); err != nil {
|
|
return role.ListRoleDTO{}, err
|
|
}
|
|
return role.ListRoleDTO{Count: count, Roles: items}, nil
|
|
}
|
|
|
|
func (r *repository) GetByID(ctx context.Context, id int64) (role.RoleDTO, error) {
|
|
return getByID(ctx, r.client, 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) {
|
|
tx, err := r.client.Begin(ctx)
|
|
if err != nil {
|
|
return role.RoleDTO{}, err
|
|
}
|
|
defer tx.Rollback(ctx)
|
|
|
|
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) {
|
|
tx, err := r.client.Begin(ctx)
|
|
if err != nil {
|
|
return role.RoleDTO{}, 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 {
|
|
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, &scope, &item.IsSuper, &item.IsSystem, &codes, &item.UsersCount,
|
|
&item.CreatedAt, &item.UpdatedAt,
|
|
); err != nil {
|
|
return role.RoleDTO{}, err
|
|
}
|
|
item.Scope = rbac.Scope(scope)
|
|
item.ScopeName = item.Scope.Name()
|
|
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"
|
|
}
|