398 lines
13 KiB
Go
398 lines
13 KiB
Go
package db
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"strings"
|
|
|
|
"online-back/internal/identity/rbac"
|
|
"online-back/internal/identity/user"
|
|
"online-back/internal/shared"
|
|
"online-back/pkg/client/postgresql"
|
|
"online-back/pkg/logging"
|
|
"online-back/pkg/repository/genericrepo"
|
|
|
|
"github.com/jackc/pgx/v4"
|
|
"golang.org/x/crypto/bcrypt"
|
|
)
|
|
|
|
type repository struct {
|
|
client postgresql.Client
|
|
logger *logging.Logger
|
|
}
|
|
|
|
func NewRepository(client postgresql.Client, logger *logging.Logger) user.Repository {
|
|
return &repository{client: client, logger: logger}
|
|
}
|
|
|
|
const userColumns = `u.id, u.email, u.name, u.first_name, u.last_name, u.username, u.phone, u.avatar, u.active, u.created_at, u.updated_at, r.id, r.code`
|
|
|
|
const userReturningColumns = `id, email, name, first_name, last_name, username, phone, avatar, active, created_at, updated_at`
|
|
|
|
const userFromClause = ` FROM users u
|
|
LEFT JOIN roles r ON r.id = u.role_id AND r.deleted_at IS NULL `
|
|
|
|
const userBranchesJSON = `COALESCE((
|
|
SELECT json_agg(jsonb_build_object(
|
|
'id', b.id,
|
|
'uniqueCode', b.unique_code,
|
|
'name', b.name
|
|
) ORDER BY b.id)
|
|
FROM (
|
|
SELECT DISTINCT ON (b.id) b.id, b.unique_code, b.name
|
|
FROM branch_user bu
|
|
JOIN branches b ON b.id = bu.branch_id
|
|
WHERE bu.user_id = u.id AND bu.deleted_at IS NULL AND b.deleted_at IS NULL
|
|
ORDER BY b.id
|
|
) b
|
|
), '[]'::json)`
|
|
|
|
// userPermissionsJSON lists the effective permissions: every one for an
|
|
// is_super role, else the role's role_permissions.
|
|
const userPermissionsJSON = `COALESCE((
|
|
SELECT json_agg(jsonb_build_object('code', p.code, 'name', p.name) ORDER BY p.code)
|
|
FROM permissions p
|
|
WHERE r.is_super OR EXISTS (
|
|
SELECT 1 FROM role_permissions rp WHERE rp.role_id = r.id AND rp.permission_code = p.code
|
|
)
|
|
), '[]'::json)`
|
|
|
|
func (r *repository) List(ctx context.Context, filter user.ListFilter) (user.ListUserDTO, error) {
|
|
roles := listVisibleRoles
|
|
if filter.AllRoles {
|
|
roles = nil
|
|
}
|
|
fromClause, whereClause, args := buildFilteredListQuery(filter, roles...)
|
|
return r.paginateUsers(ctx, filter, fromClause, whereClause, args)
|
|
}
|
|
|
|
func (r *repository) ListStaff(ctx context.Context, filter user.ListFilter) (user.ListUserDTO, error) {
|
|
whereClause, args := buildStaffWhere(filter)
|
|
|
|
var count int64
|
|
countQuery := `SELECT COUNT(*)` + userFromClause + whereClause
|
|
if err := r.client.QueryRow(ctx, countQuery, args...).Scan(&count); err != nil {
|
|
return user.ListUserDTO{}, err
|
|
}
|
|
|
|
offset := (filter.Page - 1) * filter.Limit
|
|
limitPlaceholder := len(args) + 1
|
|
offsetPlaceholder := len(args) + 2
|
|
listQuery := fmt.Sprintf(
|
|
`SELECT %s, %s%s%s ORDER BY u.id LIMIT $%d OFFSET $%d`,
|
|
userColumns, userBranchesJSON, userFromClause, whereClause, limitPlaceholder, offsetPlaceholder,
|
|
)
|
|
|
|
rows, err := r.client.Query(ctx, listQuery, append(args, filter.Limit, offset)...)
|
|
if err != nil {
|
|
return user.ListUserDTO{}, err
|
|
}
|
|
defer rows.Close()
|
|
|
|
var items []user.UserDTO
|
|
for rows.Next() {
|
|
item, err := scanStaffUser(rows)
|
|
if err != nil {
|
|
return user.ListUserDTO{}, err
|
|
}
|
|
items = append(items, item)
|
|
}
|
|
if err := rows.Err(); err != nil {
|
|
return user.ListUserDTO{}, err
|
|
}
|
|
|
|
return user.ListUserDTO{Count: count, Users: items}, nil
|
|
}
|
|
|
|
func buildStaffWhere(filter user.ListFilter) (whereClause string, args []interface{}) {
|
|
conditions := []string{"u.deleted_at IS NULL"}
|
|
if len(filter.BranchIds) > 0 {
|
|
args = append(args, filter.BranchIds)
|
|
conditions = append(conditions, fmt.Sprintf(`EXISTS (SELECT 1 FROM branch_user bu WHERE bu.user_id = u.id AND bu.branch_id = ANY($%d) AND bu.deleted_at IS NULL)`, len(args)))
|
|
} else {
|
|
conditions = append(conditions, `EXISTS (SELECT 1 FROM branch_user bu WHERE bu.user_id = u.id AND bu.deleted_at IS NULL)`)
|
|
}
|
|
conditions, args = appendNameSearch(conditions, args, filter.Search)
|
|
return " WHERE " + strings.Join(conditions, " AND "), args
|
|
}
|
|
|
|
func (r *repository) paginateUsers(ctx context.Context, filter user.ListFilter, fromClause, whereClause string, args []interface{}) (user.ListUserDTO, error) {
|
|
var count int64
|
|
if err := r.client.QueryRow(ctx, `SELECT COUNT(*) `+fromClause+whereClause, args...).Scan(&count); err != nil {
|
|
return user.ListUserDTO{}, err
|
|
}
|
|
|
|
offset := (filter.Page - 1) * filter.Limit
|
|
limitPlaceholder := len(args) + 1
|
|
offsetPlaceholder := len(args) + 2
|
|
listQuery := fmt.Sprintf(
|
|
`SELECT %s%s%s ORDER BY u.id LIMIT $%d OFFSET $%d`,
|
|
userColumns, fromClause, whereClause, limitPlaceholder, offsetPlaceholder,
|
|
)
|
|
|
|
rows, err := r.client.Query(ctx, listQuery, append(args, filter.Limit, offset)...)
|
|
if err != nil {
|
|
return user.ListUserDTO{}, err
|
|
}
|
|
defer rows.Close()
|
|
|
|
var items []user.UserDTO
|
|
for rows.Next() {
|
|
item, err := scanUserWithRoleID(rows)
|
|
if err != nil {
|
|
return user.ListUserDTO{}, err
|
|
}
|
|
items = append(items, item)
|
|
}
|
|
if err := rows.Err(); err != nil {
|
|
return user.ListUserDTO{}, err
|
|
}
|
|
|
|
return user.ListUserDTO{Count: count, Users: items}, nil
|
|
}
|
|
|
|
var listVisibleRoles = []string{"user"}
|
|
|
|
func buildFilteredListQuery(filter user.ListFilter, roles ...string) (fromClause, whereClause string, args []interface{}) {
|
|
fromClause = userFromClause
|
|
|
|
conditions := []string{"u.deleted_at IS NULL"}
|
|
conditions, args = appendNameSearch(conditions, args, filter.Search)
|
|
if len(roles) > 0 {
|
|
placeholders := make([]string, len(roles))
|
|
for i, role := range roles {
|
|
args = append(args, role)
|
|
placeholders[i] = fmt.Sprintf("$%d", len(args))
|
|
}
|
|
if len(roles) == 1 {
|
|
conditions = append(conditions, fmt.Sprintf(`r.code = %s`, placeholders[0]))
|
|
} else {
|
|
conditions = append(conditions, fmt.Sprintf(`r.code IN (%s)`, strings.Join(placeholders, ", ")))
|
|
}
|
|
}
|
|
|
|
if len(filter.BranchIds) > 0 {
|
|
args = append(args, filter.BranchIds)
|
|
conditions = append(conditions, rbac.UserInBranchSQL("u.id", len(args)))
|
|
}
|
|
|
|
return fromClause, " WHERE " + strings.Join(conditions, " AND "), args
|
|
}
|
|
|
|
func appendNameSearch(conditions []string, args []interface{}, term string) ([]string, []interface{}) {
|
|
if term == "" {
|
|
return conditions, args
|
|
}
|
|
args = append(args, shared.LikePattern(term))
|
|
n := len(args)
|
|
conditions = append(conditions, fmt.Sprintf(
|
|
`(u.username ILIKE $%d OR u.first_name ILIKE $%d OR u.last_name ILIKE $%d OR CONCAT_WS(' ', u.first_name, u.last_name) ILIKE $%d)`,
|
|
n, n, n, n,
|
|
))
|
|
return conditions, args
|
|
}
|
|
|
|
func (r *repository) GetByRole(ctx context.Context, role string, filter user.ListFilter) (user.ListUserDTO, error) {
|
|
fromClause, whereClause, args := buildFilteredListQuery(filter, role)
|
|
if len(filter.BranchIds) == 0 {
|
|
whereClause += ` AND NOT EXISTS (SELECT 1 FROM branch_user bu WHERE bu.user_id = u.id AND bu.deleted_at IS NULL)`
|
|
}
|
|
return r.paginateUsers(ctx, filter, fromClause, whereClause, args)
|
|
}
|
|
|
|
func (r *repository) GetByID(ctx context.Context, id int64) (user.UserDTO, error) {
|
|
query := fmt.Sprintf(`SELECT %s, %s, %s%s WHERE u.id = $1 AND u.deleted_at IS NULL`, userColumns, userBranchesJSON, userPermissionsJSON, userFromClause)
|
|
item, err := scanUserDetail(r.client.QueryRow(ctx, query, id))
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return user.UserDTO{}, err
|
|
}
|
|
return item, err
|
|
}
|
|
|
|
func (r *repository) Create(ctx context.Context, dto user.CreateUserDTO, roleID int64) (user.UserDTO, error) {
|
|
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(dto.Password), bcrypt.DefaultCost)
|
|
if err != nil {
|
|
return user.UserDTO{}, err
|
|
}
|
|
|
|
active := true
|
|
if dto.Active != nil {
|
|
active = *dto.Active
|
|
}
|
|
|
|
query := fmt.Sprintf(`
|
|
INSERT INTO users (email, password, name, first_name, last_name, username, phone, avatar, role_id, active)
|
|
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
|
|
RETURNING %s`, userReturningColumns)
|
|
|
|
item, err := scanUser(r.client.QueryRow(ctx, query,
|
|
dto.Email, hashedPassword, dto.Name, dto.FirstName, dto.LastName, dto.Username, dto.Phone, dto.Avatar, roleID, active,
|
|
))
|
|
if err != nil {
|
|
return user.UserDTO{}, err
|
|
}
|
|
return r.withRole(ctx, item, roleID)
|
|
}
|
|
|
|
func (r *repository) Update(ctx context.Context, id int64, dto user.UpdateUserDTO, roleID int64) (user.UserDTO, error) {
|
|
query := fmt.Sprintf(`
|
|
UPDATE users SET
|
|
email = $1, name = $2, first_name = $3, last_name = $4, username = $5, phone = $6, avatar = $7,
|
|
role_id = $8, active = $9,
|
|
updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
|
|
WHERE id = $10 AND deleted_at IS NULL
|
|
RETURNING %s`, userReturningColumns)
|
|
|
|
item, err := scanUser(r.client.QueryRow(ctx, query,
|
|
dto.Email, dto.Name, dto.FirstName, dto.LastName, dto.Username, dto.Phone, dto.Avatar, roleID, dto.Active, id,
|
|
))
|
|
if err != nil {
|
|
return user.UserDTO{}, err
|
|
}
|
|
return r.withRole(ctx, item, roleID)
|
|
}
|
|
|
|
func (r *repository) SetRole(ctx context.Context, id, roleID int64) error {
|
|
tag, err := r.client.Exec(ctx, `
|
|
UPDATE users SET role_id = $1, updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
|
|
WHERE id = $2 AND deleted_at IS NULL`, roleID, id)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if tag.RowsAffected() == 0 {
|
|
return pgx.ErrNoRows
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (r *repository) withRole(ctx context.Context, item user.UserDTO, roleID int64) (user.UserDTO, error) {
|
|
if err := r.client.QueryRow(ctx, `SELECT code FROM roles WHERE id = $1`, roleID).Scan(&item.Role); err != nil {
|
|
return user.UserDTO{}, err
|
|
}
|
|
item.RoleId = &roleID
|
|
return item, nil
|
|
}
|
|
|
|
func (r *repository) Delete(ctx context.Context, id int64) error {
|
|
return genericrepo.Delete(ctx, r.client, "users", id)
|
|
}
|
|
|
|
func (r *repository) RoleByCode(ctx context.Context, code string) (*rbac.RoleInfo, error) {
|
|
return rbac.ScanRoleInfo(r.client.QueryRow(ctx,
|
|
rbac.RoleInfoSelect+`WHERE r.code = $1 AND r.deleted_at IS NULL`, strings.TrimSpace(code)))
|
|
}
|
|
|
|
func (r *repository) RoleByID(ctx context.Context, id int64) (*rbac.RoleInfo, error) {
|
|
return rbac.ScanRoleInfo(r.client.QueryRow(ctx,
|
|
rbac.RoleInfoSelect+`WHERE r.id = $1 AND r.deleted_at IS NULL`, id))
|
|
}
|
|
|
|
func (r *repository) RoleOfUser(ctx context.Context, userID int64) (*rbac.RoleInfo, error) {
|
|
return rbac.ScanRoleInfo(r.client.QueryRow(ctx,
|
|
rbac.RoleInfoSelect+`JOIN users u ON u.role_id = r.id
|
|
WHERE u.id = $1 AND u.deleted_at IS NULL AND r.deleted_at IS NULL`, userID))
|
|
}
|
|
|
|
func (r *repository) CountSuperUsers(ctx context.Context) (int64, error) {
|
|
var count int64
|
|
err := r.client.QueryRow(ctx, `
|
|
SELECT COUNT(*) FROM users u
|
|
JOIN roles r ON r.id = u.role_id AND r.deleted_at IS NULL
|
|
WHERE r.is_super AND u.deleted_at IS NULL`).Scan(&count)
|
|
return count, err
|
|
}
|
|
|
|
func scanUser(row genericrepo.Scanner) (user.UserDTO, error) {
|
|
var item user.UserDTO
|
|
if err := row.Scan(
|
|
&item.Id, &item.Email, &item.Name, &item.FirstName, &item.LastName, &item.Username, &item.Phone, &item.Avatar,
|
|
&item.Active, &item.CreatedAt, &item.UpdatedAt,
|
|
); err != nil {
|
|
return user.UserDTO{}, err
|
|
}
|
|
return item, nil
|
|
}
|
|
|
|
func scanUserWithRoleID(row genericrepo.Scanner) (user.UserDTO, error) {
|
|
var item user.UserDTO
|
|
var roleID sql.NullInt64
|
|
var roleCode sql.NullString
|
|
if err := row.Scan(
|
|
&item.Id, &item.Email, &item.Name, &item.FirstName, &item.LastName, &item.Username, &item.Phone, &item.Avatar,
|
|
&item.Active, &item.CreatedAt, &item.UpdatedAt, &roleID, &roleCode,
|
|
); err != nil {
|
|
return user.UserDTO{}, err
|
|
}
|
|
applyJoinedRole(&item, roleID, roleCode)
|
|
return item, nil
|
|
}
|
|
|
|
func scanStaffUser(row genericrepo.Scanner) (user.UserDTO, error) {
|
|
var item user.UserDTO
|
|
var roleID sql.NullInt64
|
|
var roleCode sql.NullString
|
|
var branchesJSON []byte
|
|
if err := row.Scan(
|
|
&item.Id, &item.Email, &item.Name, &item.FirstName, &item.LastName, &item.Username, &item.Phone, &item.Avatar,
|
|
&item.Active, &item.CreatedAt, &item.UpdatedAt, &roleID, &roleCode, &branchesJSON,
|
|
); err != nil {
|
|
return user.UserDTO{}, err
|
|
}
|
|
applyJoinedRole(&item, roleID, roleCode)
|
|
if err := unmarshalJSON(branchesJSON, &item.Branches); err != nil {
|
|
return user.UserDTO{}, err
|
|
}
|
|
if item.Branches == nil {
|
|
item.Branches = []user.StaffBranchDTO{}
|
|
}
|
|
return item, nil
|
|
}
|
|
|
|
func scanUserDetail(row genericrepo.Scanner) (user.UserDTO, error) {
|
|
var item user.UserDTO
|
|
var roleID sql.NullInt64
|
|
var roleCode sql.NullString
|
|
var branchesJSON []byte
|
|
var permissionsJSON []byte
|
|
if err := row.Scan(
|
|
&item.Id, &item.Email, &item.Name, &item.FirstName, &item.LastName, &item.Username, &item.Phone, &item.Avatar,
|
|
&item.Active, &item.CreatedAt, &item.UpdatedAt, &roleID, &roleCode, &branchesJSON, &permissionsJSON,
|
|
); err != nil {
|
|
return user.UserDTO{}, err
|
|
}
|
|
applyJoinedRole(&item, roleID, roleCode)
|
|
if err := unmarshalJSON(branchesJSON, &item.Branches); err != nil {
|
|
return user.UserDTO{}, err
|
|
}
|
|
if err := unmarshalJSON(permissionsJSON, &item.Permissions); err != nil {
|
|
return user.UserDTO{}, err
|
|
}
|
|
if item.Branches == nil {
|
|
item.Branches = []user.StaffBranchDTO{}
|
|
}
|
|
if item.Permissions == nil {
|
|
item.Permissions = []user.UserPermissionDTO{}
|
|
}
|
|
return item, nil
|
|
}
|
|
|
|
func unmarshalJSON(raw []byte, dest interface{}) error {
|
|
if len(raw) == 0 || string(raw) == "null" {
|
|
return nil
|
|
}
|
|
return json.Unmarshal(raw, dest)
|
|
}
|
|
|
|
func applyJoinedRole(item *user.UserDTO, roleID sql.NullInt64, roleCode sql.NullString) {
|
|
if roleCode.Valid {
|
|
item.Role = roleCode.String
|
|
}
|
|
if roleID.Valid {
|
|
id := roleID.Int64
|
|
item.RoleId = &id
|
|
}
|
|
}
|