Add permission and user admin modules with updated user schema
Split user name into first_name/last_name/name and rename phone_number to phone; add permissions table and register the new permission/user handlers.
This commit is contained in:
@@ -1,12 +1,12 @@
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
"id" bigserial primary key,
|
||||
"email" character varying(250) NOT NULL DEFAULT '',
|
||||
"name" character varying(250) NOT NULL DEFAULT '',
|
||||
"password" character varying(250) NOT NULL DEFAULT '',
|
||||
"fullname" character varying(250) NOT NULL DEFAULT '',
|
||||
"first_name" character varying(250) NOT NULL DEFAULT '',
|
||||
"last_name" character varying(250) NOT NULL DEFAULT '',
|
||||
"username" character varying(250) NOT NULL DEFAULT '',
|
||||
"phone_number" character varying(250) NOT NULL DEFAULT '',
|
||||
"avatar" character varying(250) NOT NULL DEFAULT '',
|
||||
"social_media" json NOT NULL DEFAULT '{}'::json,
|
||||
"phone" character varying(250) NOT NULL DEFAULT '',
|
||||
"light_mode" integer DEFAULT 1 NOT NULL,
|
||||
"role" character varying(250) NOT NULL DEFAULT 'user',
|
||||
"active" boolean NOT NULL DEFAULT true,
|
||||
@@ -15,7 +15,7 @@ CREATE TABLE IF NOT EXISTS users (
|
||||
);
|
||||
|
||||
insert into users(
|
||||
phone_number, password, fullname, email, role
|
||||
phone, password, name, email, role
|
||||
) values (
|
||||
'61531216',
|
||||
'$2a$12$8ZbKmoSwna4CASQptM2/SubwvsBUR1YhABULd.2/QJB.13Wi2v55m',
|
||||
@@ -101,4 +101,13 @@ CREATE TABLE IF NOT EXISTS roles (
|
||||
guard_name character varying(255) NOT NULL,
|
||||
created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
|
||||
updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS permissions (
|
||||
id bigserial PRIMARY KEY,
|
||||
code character varying(255) NOT NULL DEFAULT '',
|
||||
name character varying(255) NOT NULL,
|
||||
guard_name character varying(255) NOT NULL,
|
||||
created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
|
||||
updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL
|
||||
);
|
||||
984
docs/docs.go
984
docs/docs.go
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -239,6 +239,32 @@ definitions:
|
||||
- price
|
||||
- title
|
||||
type: object
|
||||
permission.CreatePermissionDTO:
|
||||
properties:
|
||||
code:
|
||||
type: string
|
||||
guardName:
|
||||
type: string
|
||||
name:
|
||||
type: string
|
||||
required:
|
||||
- code
|
||||
- guardName
|
||||
- name
|
||||
type: object
|
||||
permission.UpdatePermissionDTO:
|
||||
properties:
|
||||
code:
|
||||
type: string
|
||||
guardName:
|
||||
type: string
|
||||
name:
|
||||
type: string
|
||||
required:
|
||||
- code
|
||||
- guardName
|
||||
- name
|
||||
type: object
|
||||
province.CreateProvinceDTO:
|
||||
properties:
|
||||
active:
|
||||
@@ -309,6 +335,94 @@ definitions:
|
||||
- price
|
||||
- title
|
||||
type: object
|
||||
role.CreateRoleDTO:
|
||||
properties:
|
||||
code:
|
||||
type: string
|
||||
guardName:
|
||||
type: string
|
||||
name:
|
||||
type: string
|
||||
required:
|
||||
- code
|
||||
- guardName
|
||||
- name
|
||||
type: object
|
||||
role.UpdateRoleDTO:
|
||||
properties:
|
||||
code:
|
||||
type: string
|
||||
guardName:
|
||||
type: string
|
||||
name:
|
||||
type: string
|
||||
required:
|
||||
- code
|
||||
- guardName
|
||||
- name
|
||||
type: object
|
||||
user.CreateUserDTO:
|
||||
properties:
|
||||
active:
|
||||
type: boolean
|
||||
avatar:
|
||||
type: string
|
||||
email:
|
||||
type: string
|
||||
fullname:
|
||||
type: string
|
||||
lightMode:
|
||||
type: integer
|
||||
password:
|
||||
type: string
|
||||
phoneNumber:
|
||||
type: string
|
||||
role:
|
||||
type: string
|
||||
socialMedia:
|
||||
$ref: '#/definitions/user.SocialMedia'
|
||||
username:
|
||||
type: string
|
||||
required:
|
||||
- email
|
||||
- fullname
|
||||
- password
|
||||
- username
|
||||
type: object
|
||||
user.SocialMedia:
|
||||
properties:
|
||||
facebook:
|
||||
type: string
|
||||
instagram:
|
||||
type: string
|
||||
telegram:
|
||||
type: string
|
||||
type: object
|
||||
user.UpdateUserDTO:
|
||||
properties:
|
||||
active:
|
||||
type: boolean
|
||||
avatar:
|
||||
type: string
|
||||
email:
|
||||
type: string
|
||||
fullname:
|
||||
type: string
|
||||
lightMode:
|
||||
type: integer
|
||||
phoneNumber:
|
||||
type: string
|
||||
role:
|
||||
type: string
|
||||
socialMedia:
|
||||
$ref: '#/definitions/user.SocialMedia'
|
||||
username:
|
||||
type: string
|
||||
required:
|
||||
- email
|
||||
- fullname
|
||||
- username
|
||||
type: object
|
||||
host: localhost:5050
|
||||
info:
|
||||
contact: {}
|
||||
@@ -1144,6 +1258,180 @@ paths:
|
||||
summary: Update payment card active
|
||||
tags:
|
||||
- payment-card
|
||||
/permissions:
|
||||
get:
|
||||
description: Returns paginated permissions with optional filters
|
||||
parameters:
|
||||
- description: Filter by name
|
||||
in: query
|
||||
name: permission_name
|
||||
type: string
|
||||
- default: 1
|
||||
description: Page number
|
||||
in: query
|
||||
name: page
|
||||
type: integer
|
||||
- default: 10
|
||||
description: Items per page
|
||||
in: query
|
||||
name: limit
|
||||
type: integer
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
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: List permissions
|
||||
tags:
|
||||
- permission
|
||||
post:
|
||||
consumes:
|
||||
- application/json
|
||||
description: Creates a new permission
|
||||
parameters:
|
||||
- description: Permission payload
|
||||
in: body
|
||||
name: body
|
||||
required: true
|
||||
schema:
|
||||
$ref: '#/definitions/permission.CreatePermissionDTO'
|
||||
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: Create permission
|
||||
tags:
|
||||
- permission
|
||||
/permissions/{id}:
|
||||
delete:
|
||||
description: Deletes a permission
|
||||
parameters:
|
||||
- description: Permission ID
|
||||
in: path
|
||||
name: id
|
||||
required: true
|
||||
type: integer
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
schema:
|
||||
$ref: '#/definitions/appresult.AppSuccess'
|
||||
"400":
|
||||
description: Bad Request
|
||||
schema:
|
||||
$ref: '#/definitions/appresult.AppError'
|
||||
"404":
|
||||
description: Not Found
|
||||
schema:
|
||||
$ref: '#/definitions/appresult.AppError'
|
||||
"500":
|
||||
description: Internal Server Error
|
||||
schema:
|
||||
$ref: '#/definitions/appresult.AppError'
|
||||
security:
|
||||
- BearerAuth: []
|
||||
summary: Delete permission
|
||||
tags:
|
||||
- permission
|
||||
get:
|
||||
description: Returns a single permission
|
||||
parameters:
|
||||
- description: Permission ID
|
||||
in: path
|
||||
name: id
|
||||
required: true
|
||||
type: integer
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
schema:
|
||||
$ref: '#/definitions/appresult.AppSuccess'
|
||||
"400":
|
||||
description: Bad Request
|
||||
schema:
|
||||
$ref: '#/definitions/appresult.AppError'
|
||||
"404":
|
||||
description: Not Found
|
||||
schema:
|
||||
$ref: '#/definitions/appresult.AppError'
|
||||
"500":
|
||||
description: Internal Server Error
|
||||
schema:
|
||||
$ref: '#/definitions/appresult.AppError'
|
||||
security:
|
||||
- BearerAuth: []
|
||||
summary: Get permission by ID
|
||||
tags:
|
||||
- permission
|
||||
put:
|
||||
consumes:
|
||||
- application/json
|
||||
description: Updates an existing permission
|
||||
parameters:
|
||||
- description: Permission ID
|
||||
in: path
|
||||
name: id
|
||||
required: true
|
||||
type: integer
|
||||
- description: Permission payload
|
||||
in: body
|
||||
name: body
|
||||
required: true
|
||||
schema:
|
||||
$ref: '#/definitions/permission.UpdatePermissionDTO'
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
schema:
|
||||
$ref: '#/definitions/appresult.AppSuccess'
|
||||
"400":
|
||||
description: Bad Request
|
||||
schema:
|
||||
$ref: '#/definitions/appresult.AppError'
|
||||
"404":
|
||||
description: Not Found
|
||||
schema:
|
||||
$ref: '#/definitions/appresult.AppError'
|
||||
"500":
|
||||
description: Internal Server Error
|
||||
schema:
|
||||
$ref: '#/definitions/appresult.AppError'
|
||||
security:
|
||||
- BearerAuth: []
|
||||
summary: Update permission
|
||||
tags:
|
||||
- permission
|
||||
/profile:
|
||||
get:
|
||||
description: Returns the authenticated user's profile
|
||||
@@ -1504,6 +1792,180 @@ paths:
|
||||
summary: Update reason card
|
||||
tags:
|
||||
- reason-card
|
||||
/roles:
|
||||
get:
|
||||
description: Returns paginated roles with optional filters
|
||||
parameters:
|
||||
- description: Filter by name
|
||||
in: query
|
||||
name: role_name
|
||||
type: string
|
||||
- default: 1
|
||||
description: Page number
|
||||
in: query
|
||||
name: page
|
||||
type: integer
|
||||
- default: 10
|
||||
description: Items per page
|
||||
in: query
|
||||
name: limit
|
||||
type: integer
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
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: List roles
|
||||
tags:
|
||||
- role
|
||||
post:
|
||||
consumes:
|
||||
- application/json
|
||||
description: Creates a new role
|
||||
parameters:
|
||||
- description: Role payload
|
||||
in: body
|
||||
name: body
|
||||
required: true
|
||||
schema:
|
||||
$ref: '#/definitions/role.CreateRoleDTO'
|
||||
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: Create role
|
||||
tags:
|
||||
- role
|
||||
/roles/{id}:
|
||||
delete:
|
||||
description: Deletes a role
|
||||
parameters:
|
||||
- description: Role ID
|
||||
in: path
|
||||
name: id
|
||||
required: true
|
||||
type: integer
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
schema:
|
||||
$ref: '#/definitions/appresult.AppSuccess'
|
||||
"400":
|
||||
description: Bad Request
|
||||
schema:
|
||||
$ref: '#/definitions/appresult.AppError'
|
||||
"404":
|
||||
description: Not Found
|
||||
schema:
|
||||
$ref: '#/definitions/appresult.AppError'
|
||||
"500":
|
||||
description: Internal Server Error
|
||||
schema:
|
||||
$ref: '#/definitions/appresult.AppError'
|
||||
security:
|
||||
- BearerAuth: []
|
||||
summary: Delete role
|
||||
tags:
|
||||
- role
|
||||
get:
|
||||
description: Returns a single role
|
||||
parameters:
|
||||
- description: Role ID
|
||||
in: path
|
||||
name: id
|
||||
required: true
|
||||
type: integer
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
schema:
|
||||
$ref: '#/definitions/appresult.AppSuccess'
|
||||
"400":
|
||||
description: Bad Request
|
||||
schema:
|
||||
$ref: '#/definitions/appresult.AppError'
|
||||
"404":
|
||||
description: Not Found
|
||||
schema:
|
||||
$ref: '#/definitions/appresult.AppError'
|
||||
"500":
|
||||
description: Internal Server Error
|
||||
schema:
|
||||
$ref: '#/definitions/appresult.AppError'
|
||||
security:
|
||||
- BearerAuth: []
|
||||
summary: Get role by ID
|
||||
tags:
|
||||
- role
|
||||
put:
|
||||
consumes:
|
||||
- application/json
|
||||
description: Updates an existing role
|
||||
parameters:
|
||||
- description: Role ID
|
||||
in: path
|
||||
name: id
|
||||
required: true
|
||||
type: integer
|
||||
- description: Role payload
|
||||
in: body
|
||||
name: body
|
||||
required: true
|
||||
schema:
|
||||
$ref: '#/definitions/role.UpdateRoleDTO'
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
schema:
|
||||
$ref: '#/definitions/appresult.AppSuccess'
|
||||
"400":
|
||||
description: Bad Request
|
||||
schema:
|
||||
$ref: '#/definitions/appresult.AppError'
|
||||
"404":
|
||||
description: Not Found
|
||||
schema:
|
||||
$ref: '#/definitions/appresult.AppError'
|
||||
"500":
|
||||
description: Internal Server Error
|
||||
schema:
|
||||
$ref: '#/definitions/appresult.AppError'
|
||||
security:
|
||||
- BearerAuth: []
|
||||
summary: Update role
|
||||
tags:
|
||||
- role
|
||||
/token:
|
||||
post:
|
||||
consumes:
|
||||
@@ -1534,6 +1996,180 @@ paths:
|
||||
summary: Refresh tokens
|
||||
tags:
|
||||
- auth
|
||||
/users:
|
||||
get:
|
||||
description: Returns paginated users with optional filters
|
||||
parameters:
|
||||
- description: Filter by username
|
||||
in: query
|
||||
name: username
|
||||
type: string
|
||||
- default: 1
|
||||
description: Page number
|
||||
in: query
|
||||
name: page
|
||||
type: integer
|
||||
- default: 10
|
||||
description: Items per page
|
||||
in: query
|
||||
name: limit
|
||||
type: integer
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
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: List users
|
||||
tags:
|
||||
- user
|
||||
post:
|
||||
consumes:
|
||||
- application/json
|
||||
description: Creates a new user
|
||||
parameters:
|
||||
- description: User payload
|
||||
in: body
|
||||
name: body
|
||||
required: true
|
||||
schema:
|
||||
$ref: '#/definitions/user.CreateUserDTO'
|
||||
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: Create user
|
||||
tags:
|
||||
- user
|
||||
/users/{id}:
|
||||
delete:
|
||||
description: Deletes a user
|
||||
parameters:
|
||||
- description: User ID
|
||||
in: path
|
||||
name: id
|
||||
required: true
|
||||
type: integer
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
schema:
|
||||
$ref: '#/definitions/appresult.AppSuccess'
|
||||
"400":
|
||||
description: Bad Request
|
||||
schema:
|
||||
$ref: '#/definitions/appresult.AppError'
|
||||
"404":
|
||||
description: Not Found
|
||||
schema:
|
||||
$ref: '#/definitions/appresult.AppError'
|
||||
"500":
|
||||
description: Internal Server Error
|
||||
schema:
|
||||
$ref: '#/definitions/appresult.AppError'
|
||||
security:
|
||||
- BearerAuth: []
|
||||
summary: Delete user
|
||||
tags:
|
||||
- user
|
||||
get:
|
||||
description: Returns a single user
|
||||
parameters:
|
||||
- description: User ID
|
||||
in: path
|
||||
name: id
|
||||
required: true
|
||||
type: integer
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
schema:
|
||||
$ref: '#/definitions/appresult.AppSuccess'
|
||||
"400":
|
||||
description: Bad Request
|
||||
schema:
|
||||
$ref: '#/definitions/appresult.AppError'
|
||||
"404":
|
||||
description: Not Found
|
||||
schema:
|
||||
$ref: '#/definitions/appresult.AppError'
|
||||
"500":
|
||||
description: Internal Server Error
|
||||
schema:
|
||||
$ref: '#/definitions/appresult.AppError'
|
||||
security:
|
||||
- BearerAuth: []
|
||||
summary: Get user by ID
|
||||
tags:
|
||||
- user
|
||||
put:
|
||||
consumes:
|
||||
- application/json
|
||||
description: Updates an existing user
|
||||
parameters:
|
||||
- description: User ID
|
||||
in: path
|
||||
name: id
|
||||
required: true
|
||||
type: integer
|
||||
- description: User payload
|
||||
in: body
|
||||
name: body
|
||||
required: true
|
||||
schema:
|
||||
$ref: '#/definitions/user.UpdateUserDTO'
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
schema:
|
||||
$ref: '#/definitions/appresult.AppSuccess'
|
||||
"400":
|
||||
description: Bad Request
|
||||
schema:
|
||||
$ref: '#/definitions/appresult.AppError'
|
||||
"404":
|
||||
description: Not Found
|
||||
schema:
|
||||
$ref: '#/definitions/appresult.AppError'
|
||||
"500":
|
||||
description: Internal Server Error
|
||||
schema:
|
||||
$ref: '#/definitions/appresult.AppError'
|
||||
security:
|
||||
- BearerAuth: []
|
||||
summary: Update user
|
||||
tags:
|
||||
- user
|
||||
securityDefinitions:
|
||||
BearerAuth:
|
||||
in: header
|
||||
|
||||
146
internal/admin/permission/db/postgresql.go
Normal file
146
internal/admin/permission/db/postgresql.go
Normal file
@@ -0,0 +1,146 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"online-back/internal/admin/permission"
|
||||
"online-back/pkg/client/postgresql"
|
||||
"online-back/pkg/logging"
|
||||
|
||||
"github.com/jackc/pgx/v4"
|
||||
)
|
||||
|
||||
type repository struct {
|
||||
client postgresql.Client
|
||||
logger *logging.Logger
|
||||
}
|
||||
|
||||
func NewRepository(client postgresql.Client, logger *logging.Logger) permission.Repository {
|
||||
return &repository{client: client, logger: logger}
|
||||
}
|
||||
|
||||
const permissionColumns = `p.id, p.code, p.name, p.guard_name, p.created_at, p.updated_at`
|
||||
|
||||
const permissionReturningColumns = `id, code, name, guard_name, created_at, updated_at`
|
||||
|
||||
func (r *repository) List(ctx context.Context, filter permission.ListFilter) (permission.ListPermissionDTO, error) {
|
||||
fromClause, whereClause, args := buildListQuery(filter)
|
||||
|
||||
var count int64
|
||||
if err := r.client.QueryRow(ctx, `SELECT COUNT(*) `+fromClause+whereClause, args...).Scan(&count); err != nil {
|
||||
return permission.ListPermissionDTO{}, err
|
||||
}
|
||||
|
||||
offset := (filter.Page - 1) * filter.Limit
|
||||
limitPlaceholder := len(args) + 1
|
||||
offsetPlaceholder := len(args) + 2
|
||||
listQuery := fmt.Sprintf(
|
||||
`SELECT %s%s%s ORDER BY p.id LIMIT $%d OFFSET $%d`,
|
||||
permissionColumns, fromClause, whereClause, limitPlaceholder, offsetPlaceholder,
|
||||
)
|
||||
|
||||
rows, err := r.client.Query(ctx, listQuery, append(args, filter.Limit, offset)...)
|
||||
if err != nil {
|
||||
return permission.ListPermissionDTO{}, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var items []permission.PermissionDTO
|
||||
for rows.Next() {
|
||||
item, err := scanPermission(rows)
|
||||
if err != nil {
|
||||
return permission.ListPermissionDTO{}, err
|
||||
}
|
||||
items = append(items, item)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return permission.ListPermissionDTO{}, err
|
||||
}
|
||||
|
||||
return permission.ListPermissionDTO{Count: count, Permissions: items}, nil
|
||||
}
|
||||
|
||||
func buildListQuery(filter permission.ListFilter) (fromClause, whereClause string, args []interface{}) {
|
||||
fromClause = ` FROM permissions p`
|
||||
|
||||
var conditions []string
|
||||
if filter.PermissionName != "" {
|
||||
args = append(args, likePattern(filter.PermissionName))
|
||||
n := len(args)
|
||||
conditions = append(conditions, fmt.Sprintf(`p.name ILIKE $%d`, n))
|
||||
}
|
||||
|
||||
if len(conditions) == 0 {
|
||||
return fromClause, "", args
|
||||
}
|
||||
|
||||
return fromClause, " 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) {
|
||||
query := fmt.Sprintf(`SELECT %s FROM permissions p WHERE p.id = $1`, permissionColumns)
|
||||
item, err := scanPermission(r.client.QueryRow(ctx, query, id))
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return permission.PermissionDTO{}, err
|
||||
}
|
||||
return item, err
|
||||
}
|
||||
|
||||
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)
|
||||
RETURNING %s`, permissionReturningColumns)
|
||||
|
||||
return scanPermission(r.client.QueryRow(ctx, query, dto.Code, dto.Name, dto.GuardName))
|
||||
}
|
||||
|
||||
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,
|
||||
updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
|
||||
WHERE id = $4
|
||||
RETURNING %s`, permissionReturningColumns)
|
||||
|
||||
item, err := scanPermission(r.client.QueryRow(ctx, query, dto.Code, dto.Name, dto.GuardName, id))
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return permission.PermissionDTO{}, err
|
||||
}
|
||||
return item, err
|
||||
}
|
||||
|
||||
func (r *repository) Delete(ctx context.Context, id int64) error {
|
||||
tag, err := r.client.Exec(ctx, `DELETE FROM permissions WHERE id = $1`, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if tag.RowsAffected() == 0 {
|
||||
return pgx.ErrNoRows
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type scannable interface {
|
||||
Scan(dest ...interface{}) error
|
||||
}
|
||||
|
||||
func scanPermission(row scannable) (permission.PermissionDTO, error) {
|
||||
var item permission.PermissionDTO
|
||||
if err := row.Scan(
|
||||
&item.Id, &item.Code, &item.Name, &item.GuardName, &item.CreatedAt, &item.UpdatedAt,
|
||||
); err != nil {
|
||||
return permission.PermissionDTO{}, err
|
||||
}
|
||||
return item, nil
|
||||
}
|
||||
35
internal/admin/permission/dto.go
Normal file
35
internal/admin/permission/dto.go
Normal file
@@ -0,0 +1,35 @@
|
||||
package permission
|
||||
|
||||
import "time"
|
||||
|
||||
type PermissionDTO struct {
|
||||
Id int64 `json:"id"`
|
||||
Code string `json:"code"`
|
||||
Name string `json:"name"`
|
||||
GuardName string `json:"guardName"`
|
||||
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"`
|
||||
}
|
||||
|
||||
type UpdatePermissionDTO struct {
|
||||
Code string `json:"code" binding:"required"`
|
||||
Name string `json:"name" binding:"required"`
|
||||
GuardName string `json:"guardName" binding:"required"`
|
||||
}
|
||||
|
||||
type ListFilter struct {
|
||||
PermissionName string
|
||||
Page int
|
||||
Limit int
|
||||
}
|
||||
|
||||
type ListPermissionDTO struct {
|
||||
Count int64 `json:"count"`
|
||||
Permissions []PermissionDTO `json:"permissions"`
|
||||
}
|
||||
242
internal/admin/permission/handler.go
Normal file
242
internal/admin/permission/handler.go
Normal file
@@ -0,0 +1,242 @@
|
||||
package permission
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"online-back/internal/appresult"
|
||||
"online-back/internal/handlers"
|
||||
"online-back/pkg/logging"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/jackc/pgx/v4"
|
||||
)
|
||||
|
||||
const baseURL = "/permissions"
|
||||
|
||||
type handler struct {
|
||||
logger *logging.Logger
|
||||
repository Repository
|
||||
}
|
||||
|
||||
func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler {
|
||||
return &handler{logger: logger, repository: repository}
|
||||
}
|
||||
|
||||
func (h *handler) Register(router *gin.RouterGroup) {
|
||||
group := router.Group(baseURL, appresult.JwtTokenCheck())
|
||||
group.GET("", h.list)
|
||||
group.GET("/:id", h.getByID)
|
||||
group.POST("", h.create)
|
||||
group.PUT("/:id", h.update)
|
||||
group.DELETE("/:id", h.delete)
|
||||
}
|
||||
|
||||
// list godoc
|
||||
// @Summary List permissions
|
||||
// @Description Returns paginated permissions with optional filters
|
||||
// @Tags permission
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param permission_name query string false "Filter by name"
|
||||
// @Param page query int false "Page number" default(1)
|
||||
// @Param limit query int false "Items per page" default(10)
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /permissions [get]
|
||||
func (h *handler) list(c *gin.Context) {
|
||||
filter, ok := parseListFilter(c)
|
||||
if !ok {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
result, err := h.repository.List(c.Request.Context(), filter)
|
||||
if err != nil {
|
||||
h.logger.Errorf("list permissions 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
|
||||
// @Tags permission
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "Permission ID"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /permissions/{id} [get]
|
||||
func (h *handler) getByID(c *gin.Context) {
|
||||
id, ok := parseID(c.Param("id"))
|
||||
if !ok {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
item, err := h.repository.GetByID(c.Request.Context(), id)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
h.logger.Errorf("get permission failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
|
||||
}
|
||||
|
||||
// create godoc
|
||||
// @Summary Create permission
|
||||
// @Description Creates a new permission
|
||||
// @Tags permission
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param body body CreatePermissionDTO true "Permission payload"
|
||||
// @Success 201 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /permissions [post]
|
||||
func (h *handler) create(c *gin.Context) {
|
||||
var dto CreatePermissionDTO
|
||||
if err := c.ShouldBindJSON(&dto); err != nil {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
item, err := h.repository.Create(c.Request.Context(), dto)
|
||||
if err != nil {
|
||||
h.logger.Errorf("create permission failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusCreated, appresult.SuccessWithData(item))
|
||||
}
|
||||
|
||||
// update godoc
|
||||
// @Summary Update permission
|
||||
// @Description Updates an existing permission
|
||||
// @Tags permission
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "Permission ID"
|
||||
// @Param body body UpdatePermissionDTO true "Permission payload"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /permissions/{id} [put]
|
||||
func (h *handler) update(c *gin.Context) {
|
||||
id, ok := parseID(c.Param("id"))
|
||||
if !ok {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
var dto UpdatePermissionDTO
|
||||
if err := c.ShouldBindJSON(&dto); err != nil {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
item, err := h.repository.Update(c.Request.Context(), id, dto)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
h.logger.Errorf("update permission failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
|
||||
}
|
||||
|
||||
// delete godoc
|
||||
// @Summary Delete permission
|
||||
// @Description Deletes a permission
|
||||
// @Tags permission
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "Permission ID"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /permissions/{id} [delete]
|
||||
func (h *handler) delete(c *gin.Context) {
|
||||
id, ok := 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 failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
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,
|
||||
}
|
||||
|
||||
if raw := c.Query("page"); raw != "" {
|
||||
page, err := strconv.Atoi(raw)
|
||||
if err != nil || page < 1 {
|
||||
return ListFilter{}, false
|
||||
}
|
||||
filter.Page = page
|
||||
}
|
||||
|
||||
if raw := c.Query("limit"); raw != "" {
|
||||
limit, err := strconv.Atoi(raw)
|
||||
if err != nil || limit < 1 || limit > maxLimit {
|
||||
return ListFilter{}, false
|
||||
}
|
||||
filter.Limit = limit
|
||||
}
|
||||
|
||||
if raw := strings.TrimSpace(c.Query("permission_name")); raw != "" {
|
||||
filter.PermissionName = raw
|
||||
}
|
||||
|
||||
return filter, true
|
||||
}
|
||||
11
internal/admin/permission/storage.go
Normal file
11
internal/admin/permission/storage.go
Normal file
@@ -0,0 +1,11 @@
|
||||
package permission
|
||||
|
||||
import "context"
|
||||
|
||||
type Repository interface {
|
||||
List(ctx context.Context, filter ListFilter) (ListPermissionDTO, 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)
|
||||
Delete(ctx context.Context, id int64) error
|
||||
}
|
||||
178
internal/admin/user/db/postgresql.go
Normal file
178
internal/admin/user/db/postgresql.go
Normal file
@@ -0,0 +1,178 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"online-back/internal/admin/user"
|
||||
"online-back/pkg/client/postgresql"
|
||||
"online-back/pkg/logging"
|
||||
|
||||
"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.fullname, u.username, u.phone_number, u.avatar, u.social_media, u.light_mode, u.role, u.active, u.created_at, u.updated_at`
|
||||
|
||||
const userReturningColumns = `id, email, fullname, username, phone_number, avatar, social_media, light_mode, role, active, created_at, updated_at`
|
||||
|
||||
func (r *repository) List(ctx context.Context, filter user.ListFilter) (user.ListUserDTO, error) {
|
||||
fromClause, whereClause, args := buildListQuery(filter)
|
||||
|
||||
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 := scanUser(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 buildListQuery(filter user.ListFilter) (fromClause, whereClause string, args []interface{}) {
|
||||
fromClause = ` FROM users u`
|
||||
|
||||
var conditions []string
|
||||
if filter.Username != "" {
|
||||
args = append(args, likePattern(filter.Username))
|
||||
n := len(args)
|
||||
conditions = append(conditions, fmt.Sprintf(`u.username ILIKE $%d`, n))
|
||||
}
|
||||
|
||||
if len(conditions) == 0 {
|
||||
return fromClause, "", args
|
||||
}
|
||||
|
||||
return fromClause, " 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) (user.UserDTO, error) {
|
||||
query := fmt.Sprintf(`SELECT %s FROM users u WHERE u.id = $1`, userColumns)
|
||||
item, err := scanUser(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) (user.UserDTO, error) {
|
||||
socialMedia, err := json.Marshal(dto.SocialMedia)
|
||||
if err != nil {
|
||||
return user.UserDTO{}, err
|
||||
}
|
||||
|
||||
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, fullname, username, phone_number, avatar, social_media, light_mode, role, active)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
|
||||
RETURNING %s`, userReturningColumns)
|
||||
|
||||
return scanUser(r.client.QueryRow(ctx, query,
|
||||
dto.Email, hashedPassword, dto.Fullname, dto.Username, dto.PhoneNumber, dto.Avatar, socialMedia, dto.LightMode, dto.Role, active,
|
||||
))
|
||||
}
|
||||
|
||||
func (r *repository) Update(ctx context.Context, id int64, dto user.UpdateUserDTO) (user.UserDTO, error) {
|
||||
socialMedia, err := json.Marshal(dto.SocialMedia)
|
||||
if err != nil {
|
||||
return user.UserDTO{}, err
|
||||
}
|
||||
|
||||
query := fmt.Sprintf(`
|
||||
UPDATE users SET
|
||||
email = $1, fullname = $2, username = $3, phone_number = $4, avatar = $5,
|
||||
social_media = $6, light_mode = $7, role = $8, active = $9,
|
||||
updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
|
||||
WHERE id = $10
|
||||
RETURNING %s`, userReturningColumns)
|
||||
|
||||
item, err := scanUser(r.client.QueryRow(ctx, query,
|
||||
dto.Email, dto.Fullname, dto.Username, dto.PhoneNumber, dto.Avatar, socialMedia, dto.LightMode, dto.Role, dto.Active, id,
|
||||
))
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return user.UserDTO{}, err
|
||||
}
|
||||
return item, err
|
||||
}
|
||||
|
||||
func (r *repository) Delete(ctx context.Context, id int64) error {
|
||||
tag, err := r.client.Exec(ctx, `DELETE FROM users WHERE id = $1`, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if tag.RowsAffected() == 0 {
|
||||
return pgx.ErrNoRows
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type scannable interface {
|
||||
Scan(dest ...interface{}) error
|
||||
}
|
||||
|
||||
func scanUser(row scannable) (user.UserDTO, error) {
|
||||
var item user.UserDTO
|
||||
var socialMedia []byte
|
||||
if err := row.Scan(
|
||||
&item.Id, &item.Email, &item.Fullname, &item.Username, &item.PhoneNumber, &item.Avatar,
|
||||
&socialMedia, &item.LightMode, &item.Role, &item.Active, &item.CreatedAt, &item.UpdatedAt,
|
||||
); err != nil {
|
||||
return user.UserDTO{}, err
|
||||
}
|
||||
if err := json.Unmarshal(socialMedia, &item.SocialMedia); err != nil {
|
||||
return user.UserDTO{}, err
|
||||
}
|
||||
return item, nil
|
||||
}
|
||||
60
internal/admin/user/dto.go
Normal file
60
internal/admin/user/dto.go
Normal file
@@ -0,0 +1,60 @@
|
||||
package user
|
||||
|
||||
import "time"
|
||||
|
||||
type SocialMedia struct {
|
||||
Facebook string `json:"facebook"`
|
||||
Instagram string `json:"instagram"`
|
||||
Telegram string `json:"telegram"`
|
||||
}
|
||||
|
||||
type UserDTO struct {
|
||||
Id int64 `json:"id"`
|
||||
Email string `json:"email"`
|
||||
Fullname string `json:"fullname"`
|
||||
Username string `json:"username"`
|
||||
PhoneNumber string `json:"phoneNumber"`
|
||||
Avatar string `json:"avatar"`
|
||||
SocialMedia SocialMedia `json:"socialMedia"`
|
||||
LightMode int `json:"lightMode"`
|
||||
Role string `json:"role"`
|
||||
Active bool `json:"active"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
}
|
||||
|
||||
type CreateUserDTO struct {
|
||||
Email string `json:"email" binding:"required"`
|
||||
Password string `json:"password" binding:"required"`
|
||||
Fullname string `json:"fullname" binding:"required"`
|
||||
Username string `json:"username" binding:"required"`
|
||||
PhoneNumber string `json:"phoneNumber"`
|
||||
Avatar string `json:"avatar"`
|
||||
SocialMedia SocialMedia `json:"socialMedia"`
|
||||
LightMode int `json:"lightMode"`
|
||||
Role string `json:"role"`
|
||||
Active *bool `json:"active"`
|
||||
}
|
||||
|
||||
type UpdateUserDTO struct {
|
||||
Email string `json:"email" binding:"required"`
|
||||
Fullname string `json:"fullname" binding:"required"`
|
||||
Username string `json:"username" binding:"required"`
|
||||
PhoneNumber string `json:"phoneNumber"`
|
||||
Avatar string `json:"avatar"`
|
||||
SocialMedia SocialMedia `json:"socialMedia"`
|
||||
LightMode int `json:"lightMode"`
|
||||
Role string `json:"role"`
|
||||
Active bool `json:"active"`
|
||||
}
|
||||
|
||||
type ListFilter struct {
|
||||
Username string
|
||||
Page int
|
||||
Limit int
|
||||
}
|
||||
|
||||
type ListUserDTO struct {
|
||||
Count int64 `json:"count"`
|
||||
Users []UserDTO `json:"users"`
|
||||
}
|
||||
242
internal/admin/user/handler.go
Normal file
242
internal/admin/user/handler.go
Normal file
@@ -0,0 +1,242 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"online-back/internal/appresult"
|
||||
"online-back/internal/handlers"
|
||||
"online-back/pkg/logging"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/jackc/pgx/v4"
|
||||
)
|
||||
|
||||
const baseURL = "/users"
|
||||
|
||||
type handler struct {
|
||||
logger *logging.Logger
|
||||
repository Repository
|
||||
}
|
||||
|
||||
func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler {
|
||||
return &handler{logger: logger, repository: repository}
|
||||
}
|
||||
|
||||
func (h *handler) Register(router *gin.RouterGroup) {
|
||||
group := router.Group(baseURL, appresult.JwtTokenCheck())
|
||||
group.GET("", h.list)
|
||||
group.GET("/:id", h.getByID)
|
||||
group.POST("", h.create)
|
||||
group.PUT("/:id", h.update)
|
||||
group.DELETE("/:id", h.delete)
|
||||
}
|
||||
|
||||
// list godoc
|
||||
// @Summary List users
|
||||
// @Description Returns paginated users with optional filters
|
||||
// @Tags user
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param username query string false "Filter by username"
|
||||
// @Param page query int false "Page number" default(1)
|
||||
// @Param limit query int false "Items per page" default(10)
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /users [get]
|
||||
func (h *handler) list(c *gin.Context) {
|
||||
filter, ok := parseListFilter(c)
|
||||
if !ok {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
result, err := h.repository.List(c.Request.Context(), filter)
|
||||
if err != nil {
|
||||
h.logger.Errorf("list users failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
|
||||
}
|
||||
|
||||
// getByID godoc
|
||||
// @Summary Get user by ID
|
||||
// @Description Returns a single user
|
||||
// @Tags user
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "User ID"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /users/{id} [get]
|
||||
func (h *handler) getByID(c *gin.Context) {
|
||||
id, ok := parseID(c.Param("id"))
|
||||
if !ok {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
item, err := h.repository.GetByID(c.Request.Context(), id)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
h.logger.Errorf("get user failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
|
||||
}
|
||||
|
||||
// create godoc
|
||||
// @Summary Create user
|
||||
// @Description Creates a new user
|
||||
// @Tags user
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param body body CreateUserDTO true "User payload"
|
||||
// @Success 201 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /users [post]
|
||||
func (h *handler) create(c *gin.Context) {
|
||||
var dto CreateUserDTO
|
||||
if err := c.ShouldBindJSON(&dto); err != nil {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
item, err := h.repository.Create(c.Request.Context(), dto)
|
||||
if err != nil {
|
||||
h.logger.Errorf("create user failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusCreated, appresult.SuccessWithData(item))
|
||||
}
|
||||
|
||||
// update godoc
|
||||
// @Summary Update user
|
||||
// @Description Updates an existing user
|
||||
// @Tags user
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "User ID"
|
||||
// @Param body body UpdateUserDTO true "User payload"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /users/{id} [put]
|
||||
func (h *handler) update(c *gin.Context) {
|
||||
id, ok := parseID(c.Param("id"))
|
||||
if !ok {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
var dto UpdateUserDTO
|
||||
if err := c.ShouldBindJSON(&dto); err != nil {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
item, err := h.repository.Update(c.Request.Context(), id, dto)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
h.logger.Errorf("update user failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
|
||||
}
|
||||
|
||||
// delete godoc
|
||||
// @Summary Delete user
|
||||
// @Description Deletes a user
|
||||
// @Tags user
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "User ID"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /users/{id} [delete]
|
||||
func (h *handler) delete(c *gin.Context) {
|
||||
id, ok := 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 user failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData("user 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,
|
||||
}
|
||||
|
||||
if raw := c.Query("page"); raw != "" {
|
||||
page, err := strconv.Atoi(raw)
|
||||
if err != nil || page < 1 {
|
||||
return ListFilter{}, false
|
||||
}
|
||||
filter.Page = page
|
||||
}
|
||||
|
||||
if raw := c.Query("limit"); raw != "" {
|
||||
limit, err := strconv.Atoi(raw)
|
||||
if err != nil || limit < 1 || limit > maxLimit {
|
||||
return ListFilter{}, false
|
||||
}
|
||||
filter.Limit = limit
|
||||
}
|
||||
|
||||
if raw := strings.TrimSpace(c.Query("username")); raw != "" {
|
||||
filter.Username = raw
|
||||
}
|
||||
|
||||
return filter, true
|
||||
}
|
||||
11
internal/admin/user/storage.go
Normal file
11
internal/admin/user/storage.go
Normal file
@@ -0,0 +1,11 @@
|
||||
package user
|
||||
|
||||
import "context"
|
||||
|
||||
type Repository interface {
|
||||
List(ctx context.Context, filter ListFilter) (ListUserDTO, error)
|
||||
GetByID(ctx context.Context, id int64) (UserDTO, error)
|
||||
Create(ctx context.Context, dto CreateUserDTO) (UserDTO, error)
|
||||
Update(ctx context.Context, id int64, dto UpdateUserDTO) (UserDTO, error)
|
||||
Delete(ctx context.Context, id int64) error
|
||||
}
|
||||
@@ -7,18 +7,22 @@ import (
|
||||
authdb "online-back/internal/admin/auth/db"
|
||||
"online-back/internal/admin/branches"
|
||||
branchesdb "online-back/internal/admin/branches/db"
|
||||
"online-back/internal/admin/loantype"
|
||||
loantypedb "online-back/internal/admin/loantype/db"
|
||||
"online-back/internal/admin/loansdocument"
|
||||
loansdocumentdb "online-back/internal/admin/loansdocument/db"
|
||||
"online-back/internal/admin/loantype"
|
||||
loantypedb "online-back/internal/admin/loantype/db"
|
||||
"online-back/internal/admin/paymentcard"
|
||||
paymentcarddb "online-back/internal/admin/paymentcard/db"
|
||||
"online-back/internal/admin/permission"
|
||||
permissiondb "online-back/internal/admin/permission/db"
|
||||
"online-back/internal/admin/province"
|
||||
provincedb "online-back/internal/admin/province/db"
|
||||
"online-back/internal/admin/reasonscard"
|
||||
reasonscarddb "online-back/internal/admin/reasonscard/db"
|
||||
"online-back/internal/admin/role"
|
||||
roledb "online-back/internal/admin/role/db"
|
||||
"online-back/internal/admin/user"
|
||||
userdb "online-back/internal/admin/user/db"
|
||||
"online-back/internal/config"
|
||||
"online-back/internal/handlers"
|
||||
"online-back/pkg/logging"
|
||||
@@ -73,5 +77,7 @@ func adminHandlers(client *pgxpool.Pool, logger *logging.Logger) []handlers.Hand
|
||||
loantype.NewHandler(logger, loantypedb.NewRepository(client, logger)),
|
||||
loansdocument.NewHandler(logger, loansdocumentdb.NewRepository(client, logger)),
|
||||
role.NewHandler(logger, roledb.NewRepository(client, logger)),
|
||||
permission.NewHandler(logger, permissiondb.NewRepository(client, logger)),
|
||||
user.NewHandler(logger, userdb.NewRepository(client, logger)),
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user