Compare commits
4 Commits
514b9ca5fc
...
6191b7536c
| Author | SHA1 | Date | |
|---|---|---|---|
| 6191b7536c | |||
| 71479f4355 | |||
| fb65d35d3c | |||
| 0788585c0e |
3
.gitignore
vendored
3
.gitignore
vendored
@@ -54,6 +54,9 @@ Desktop.ini
|
||||
docker-compose.override.yaml
|
||||
docker-compose.override.yml
|
||||
|
||||
# Local MinIO Ubuntu package (do not commit)
|
||||
deployment/minio.deb
|
||||
|
||||
# Temporary files
|
||||
tmp/
|
||||
temp/
|
||||
|
||||
@@ -12,9 +12,9 @@ storage:
|
||||
password: <your-db-password>
|
||||
pg_pool_max_conn: 10
|
||||
minio:
|
||||
endpoint: example-minio:9000 # use localhost:9003 when running outside Docker
|
||||
access_key: <your-minio-access-key>
|
||||
secret_key: <your-minio-secret-key>
|
||||
endpoint: 127.0.0.1:9000
|
||||
access_key: TX3H1H6XTS288QW07S8Z
|
||||
secret_key: FWWspiI4n4LMknnxYCmzFTCY1ObkGiuaU9SNwOCU
|
||||
bucket: dev-minio
|
||||
use_ssl: false
|
||||
app_version: 0.0.1
|
||||
|
||||
15
db/seed.sql
15
db/seed.sql
@@ -126,17 +126,10 @@ INSERT INTO permissions (code, name, guard_name) VALUES
|
||||
('loans.manage', 'Manage loans', 'admin'),
|
||||
('activity-logs.view', 'View activity logs', 'admin');
|
||||
|
||||
INSERT INTO role_user (role_id, user_id) VALUES
|
||||
(1, 1),
|
||||
(2, 2),
|
||||
(3, 3),
|
||||
(4, 4),
|
||||
(5, 5),
|
||||
(5, 6),
|
||||
(5, 7),
|
||||
(5, 8),
|
||||
(5, 9),
|
||||
(5, 10);
|
||||
INSERT INTO role_user (role_id, user_id)
|
||||
SELECT r.id, u.id
|
||||
FROM users u
|
||||
JOIN roles r ON r.code = u.role;
|
||||
|
||||
INSERT INTO permission_user (permission_id, user_id)
|
||||
SELECT p.id, 1 FROM permissions p;
|
||||
|
||||
74
deployment/install-minio-ubuntu.sh
Executable file
74
deployment/install-minio-ubuntu.sh
Executable file
@@ -0,0 +1,74 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
# Native MinIO for Ubuntu (no Docker). Binds only to 127.0.0.1.
|
||||
#
|
||||
# Fresh install (keeps existing data if present):
|
||||
# sudo bash install-minio-ubuntu.sh /path/to/minio.deb
|
||||
#
|
||||
# Wipe data + config, then install:
|
||||
# sudo bash install-minio-ubuntu.sh --wipe /path/to/minio.deb
|
||||
|
||||
WIPE=0
|
||||
DEB_PATH=""
|
||||
for arg in "$@"; do
|
||||
case "$arg" in
|
||||
--wipe) WIPE=1 ;;
|
||||
*) DEB_PATH="$arg" ;;
|
||||
esac
|
||||
done
|
||||
DEB_PATH="${DEB_PATH:-./minio.deb}"
|
||||
ENV_SRC="$(cd "$(dirname "$0")" && pwd)/minio.env"
|
||||
|
||||
if [[ "$(id -u)" -ne 0 ]]; then
|
||||
echo "run as root: sudo bash $0 [--wipe] $DEB_PATH" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [[ ! -f "$DEB_PATH" ]]; then
|
||||
echo "deb not found: $DEB_PATH" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [[ ! -f "$ENV_SRC" ]]; then
|
||||
echo "env file not found: $ENV_SRC" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
systemctl stop minio 2>/dev/null || true
|
||||
systemctl reset-failed minio 2>/dev/null || true
|
||||
pkill -x minio 2>/dev/null || true
|
||||
sleep 1
|
||||
|
||||
if [[ "$WIPE" -eq 1 ]]; then
|
||||
echo "wiping /data/minio and /etc/default/minio"
|
||||
rm -rf /data/minio
|
||||
rm -f /etc/default/minio
|
||||
fi
|
||||
|
||||
port_busy() {
|
||||
local port="$1"
|
||||
ss -H -tln | awk '{print $4}' | grep -E ":${port}$" >/dev/null
|
||||
}
|
||||
|
||||
for port in 9000 9001; do
|
||||
if port_busy "$port"; then
|
||||
echo "port $port is already in use:" >&2
|
||||
ss -tlnp | grep -E ":${port}\\b" >&2 || true
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
|
||||
id minio-user >/dev/null 2>&1 || useradd --system --home-dir /data/minio --shell /sbin/nologin minio-user
|
||||
mkdir -p /data/minio
|
||||
chown -R minio-user:minio-user /data/minio
|
||||
|
||||
cp "$ENV_SRC" /etc/default/minio
|
||||
chmod 600 /etc/default/minio
|
||||
|
||||
dpkg -i "$DEB_PATH"
|
||||
|
||||
systemctl daemon-reload
|
||||
systemctl enable minio
|
||||
systemctl start minio
|
||||
systemctl --no-pager --full status minio
|
||||
6
deployment/minio.env
Normal file
6
deployment/minio.env
Normal file
@@ -0,0 +1,6 @@
|
||||
MINIO_ROOT_USER=TX3H1H6XTS288QW07S8Z
|
||||
MINIO_ROOT_PASSWORD=FWWspiI4n4LMknnxYCmzFTCY1ObkGiuaU9SNwOCU
|
||||
MINIO_VOLUMES=/data/minio
|
||||
MINIO_ADDRESS=127.0.0.1:9000
|
||||
MINIO_CONSOLE_ADDRESS=127.0.0.1:9001
|
||||
MINIO_OPTS=
|
||||
@@ -41,8 +41,8 @@ services:
|
||||
- MINIO_ROOT_USER=TX3H1H6XTS288QW07S8Z
|
||||
- MINIO_ROOT_PASSWORD=FWWspiI4n4LMknnxYCmzFTCY1ObkGiuaU9SNwOCU
|
||||
ports:
|
||||
- '9003:9000'
|
||||
- '9093:9093'
|
||||
- '127.0.0.1:9003:9000'
|
||||
- '127.0.0.1:9093:9093'
|
||||
volumes:
|
||||
- main-minio-storage:/storage
|
||||
networks:
|
||||
|
||||
52
docs/docs.go
52
docs/docs.go
@@ -5324,7 +5324,13 @@ const docTemplate = `{
|
||||
"parameters": [
|
||||
{
|
||||
"type": "string",
|
||||
"description": "Filter by username",
|
||||
"description": "Search by username, first name, or last name",
|
||||
"name": "search",
|
||||
"in": "query"
|
||||
},
|
||||
{
|
||||
"type": "string",
|
||||
"description": "Alias for search",
|
||||
"name": "username",
|
||||
"in": "query"
|
||||
},
|
||||
@@ -5421,7 +5427,7 @@ const docTemplate = `{
|
||||
"BearerAuth": []
|
||||
}
|
||||
],
|
||||
"description": "Returns paginated users from the users table with role user",
|
||||
"description": "Returns paginated client users (role user, not assigned to any branch)",
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
@@ -5432,7 +5438,13 @@ const docTemplate = `{
|
||||
"parameters": [
|
||||
{
|
||||
"type": "string",
|
||||
"description": "Filter by username",
|
||||
"description": "Search by username, first name, or last name",
|
||||
"name": "search",
|
||||
"in": "query"
|
||||
},
|
||||
{
|
||||
"type": "string",
|
||||
"description": "Alias for search",
|
||||
"name": "username",
|
||||
"in": "query"
|
||||
},
|
||||
@@ -5491,7 +5503,13 @@ const docTemplate = `{
|
||||
"parameters": [
|
||||
{
|
||||
"type": "string",
|
||||
"description": "Filter by username",
|
||||
"description": "Search by username, first name, or last name",
|
||||
"name": "search",
|
||||
"in": "query"
|
||||
},
|
||||
{
|
||||
"type": "string",
|
||||
"description": "Alias for search",
|
||||
"name": "username",
|
||||
"in": "query"
|
||||
},
|
||||
@@ -7455,9 +7473,6 @@ const docTemplate = `{
|
||||
"lastName": {
|
||||
"type": "string"
|
||||
},
|
||||
"lightMode": {
|
||||
"type": "integer"
|
||||
},
|
||||
"name": {
|
||||
"type": "string"
|
||||
},
|
||||
@@ -7470,28 +7485,11 @@ const docTemplate = `{
|
||||
"role": {
|
||||
"type": "string"
|
||||
},
|
||||
"socialMedia": {
|
||||
"$ref": "#/definitions/user.SocialMedia"
|
||||
},
|
||||
"username": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"user.SocialMedia": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"facebook": {
|
||||
"type": "string"
|
||||
},
|
||||
"instagram": {
|
||||
"type": "string"
|
||||
},
|
||||
"telegram": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"user.UpdateUserDTO": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
@@ -7515,9 +7513,6 @@ const docTemplate = `{
|
||||
"lastName": {
|
||||
"type": "string"
|
||||
},
|
||||
"lightMode": {
|
||||
"type": "integer"
|
||||
},
|
||||
"name": {
|
||||
"type": "string"
|
||||
},
|
||||
@@ -7527,9 +7522,6 @@ const docTemplate = `{
|
||||
"role": {
|
||||
"type": "string"
|
||||
},
|
||||
"socialMedia": {
|
||||
"$ref": "#/definitions/user.SocialMedia"
|
||||
},
|
||||
"username": {
|
||||
"type": "string"
|
||||
}
|
||||
|
||||
@@ -5318,7 +5318,13 @@
|
||||
"parameters": [
|
||||
{
|
||||
"type": "string",
|
||||
"description": "Filter by username",
|
||||
"description": "Search by username, first name, or last name",
|
||||
"name": "search",
|
||||
"in": "query"
|
||||
},
|
||||
{
|
||||
"type": "string",
|
||||
"description": "Alias for search",
|
||||
"name": "username",
|
||||
"in": "query"
|
||||
},
|
||||
@@ -5415,7 +5421,7 @@
|
||||
"BearerAuth": []
|
||||
}
|
||||
],
|
||||
"description": "Returns paginated users from the users table with role user",
|
||||
"description": "Returns paginated client users (role user, not assigned to any branch)",
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
@@ -5426,7 +5432,13 @@
|
||||
"parameters": [
|
||||
{
|
||||
"type": "string",
|
||||
"description": "Filter by username",
|
||||
"description": "Search by username, first name, or last name",
|
||||
"name": "search",
|
||||
"in": "query"
|
||||
},
|
||||
{
|
||||
"type": "string",
|
||||
"description": "Alias for search",
|
||||
"name": "username",
|
||||
"in": "query"
|
||||
},
|
||||
@@ -5485,7 +5497,13 @@
|
||||
"parameters": [
|
||||
{
|
||||
"type": "string",
|
||||
"description": "Filter by username",
|
||||
"description": "Search by username, first name, or last name",
|
||||
"name": "search",
|
||||
"in": "query"
|
||||
},
|
||||
{
|
||||
"type": "string",
|
||||
"description": "Alias for search",
|
||||
"name": "username",
|
||||
"in": "query"
|
||||
},
|
||||
@@ -7449,9 +7467,6 @@
|
||||
"lastName": {
|
||||
"type": "string"
|
||||
},
|
||||
"lightMode": {
|
||||
"type": "integer"
|
||||
},
|
||||
"name": {
|
||||
"type": "string"
|
||||
},
|
||||
@@ -7464,28 +7479,11 @@
|
||||
"role": {
|
||||
"type": "string"
|
||||
},
|
||||
"socialMedia": {
|
||||
"$ref": "#/definitions/user.SocialMedia"
|
||||
},
|
||||
"username": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"user.SocialMedia": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"facebook": {
|
||||
"type": "string"
|
||||
},
|
||||
"instagram": {
|
||||
"type": "string"
|
||||
},
|
||||
"telegram": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"user.UpdateUserDTO": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
@@ -7509,9 +7507,6 @@
|
||||
"lastName": {
|
||||
"type": "string"
|
||||
},
|
||||
"lightMode": {
|
||||
"type": "integer"
|
||||
},
|
||||
"name": {
|
||||
"type": "string"
|
||||
},
|
||||
@@ -7521,9 +7516,6 @@
|
||||
"role": {
|
||||
"type": "string"
|
||||
},
|
||||
"socialMedia": {
|
||||
"$ref": "#/definitions/user.SocialMedia"
|
||||
},
|
||||
"username": {
|
||||
"type": "string"
|
||||
}
|
||||
|
||||
@@ -1202,8 +1202,6 @@ definitions:
|
||||
type: string
|
||||
lastName:
|
||||
type: string
|
||||
lightMode:
|
||||
type: integer
|
||||
name:
|
||||
type: string
|
||||
password:
|
||||
@@ -1212,8 +1210,6 @@ definitions:
|
||||
type: string
|
||||
role:
|
||||
type: string
|
||||
socialMedia:
|
||||
$ref: '#/definitions/user.SocialMedia'
|
||||
username:
|
||||
type: string
|
||||
required:
|
||||
@@ -1222,15 +1218,6 @@ definitions:
|
||||
- password
|
||||
- username
|
||||
type: object
|
||||
user.SocialMedia:
|
||||
properties:
|
||||
facebook:
|
||||
type: string
|
||||
instagram:
|
||||
type: string
|
||||
telegram:
|
||||
type: string
|
||||
type: object
|
||||
user.UpdateUserDTO:
|
||||
properties:
|
||||
active:
|
||||
@@ -1243,16 +1230,12 @@ definitions:
|
||||
type: string
|
||||
lastName:
|
||||
type: string
|
||||
lightMode:
|
||||
type: integer
|
||||
name:
|
||||
type: string
|
||||
phone:
|
||||
type: string
|
||||
role:
|
||||
type: string
|
||||
socialMedia:
|
||||
$ref: '#/definitions/user.SocialMedia'
|
||||
username:
|
||||
type: string
|
||||
required:
|
||||
@@ -4672,7 +4655,11 @@ paths:
|
||||
get:
|
||||
description: Returns paginated users with role user, with optional filters
|
||||
parameters:
|
||||
- description: Filter by username
|
||||
- description: Search by username, first name, or last name
|
||||
in: query
|
||||
name: search
|
||||
type: string
|
||||
- description: Alias for search
|
||||
in: query
|
||||
name: username
|
||||
type: string
|
||||
@@ -4844,9 +4831,13 @@ paths:
|
||||
- user
|
||||
/users/clients:
|
||||
get:
|
||||
description: Returns paginated users from the users table with role user
|
||||
description: Returns paginated client users (role user, not assigned to any branch)
|
||||
parameters:
|
||||
- description: Filter by username
|
||||
- description: Search by username, first name, or last name
|
||||
in: query
|
||||
name: search
|
||||
type: string
|
||||
- description: Alias for search
|
||||
in: query
|
||||
name: username
|
||||
type: string
|
||||
@@ -4885,7 +4876,11 @@ paths:
|
||||
description: Returns paginated users assigned to branches (from branch_user),
|
||||
including each user's branches.
|
||||
parameters:
|
||||
- description: Filter by username
|
||||
- description: Search by username, first name, or last name
|
||||
in: query
|
||||
name: search
|
||||
type: string
|
||||
- description: Alias for search
|
||||
in: query
|
||||
name: username
|
||||
type: string
|
||||
|
||||
@@ -55,7 +55,7 @@ func New(cfg *config.Config, client *pgxpool.Pool, logger *logging.Logger) *gin.
|
||||
|
||||
// Each bounded context registers its own modules' handlers.
|
||||
// Add new modules inside the relevant context's router.go rather than here.
|
||||
identity.Register(adminGroup, client, logger)
|
||||
identity.Register(adminGroup, router, client, logger)
|
||||
org.Register(adminGroup, client, logger)
|
||||
lending.Register(adminGroup, client, logger)
|
||||
cards.Register(adminGroup, client, logger)
|
||||
|
||||
@@ -190,6 +190,16 @@ func (r *repository) CompleteRegistration(ctx context.Context, v auth.Verificati
|
||||
return 0, err
|
||||
}
|
||||
|
||||
tag, err := tx.Exec(ctx, `
|
||||
INSERT INTO role_user (role_id, user_id)
|
||||
SELECT r.id, $1 FROM roles r WHERE r.code = 'user'`, userID)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if tag.RowsAffected() == 0 {
|
||||
return 0, errors.New(`role "user" not found`)
|
||||
}
|
||||
|
||||
if _, err := tx.Exec(ctx, `DELETE FROM registration_verifications WHERE id = $1`, v.ID); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
@@ -29,7 +29,12 @@ import (
|
||||
)
|
||||
|
||||
// Register wires every identity module's handler onto router.
|
||||
func Register(router *gin.RouterGroup, client postgresql.Client, logger *logging.Logger) {
|
||||
// engine is the root gin engine so public file GET can live at /file/:file_name.
|
||||
func Register(router *gin.RouterGroup, engine *gin.Engine, client postgresql.Client, logger *logging.Logger) {
|
||||
userH := user.NewHandler(logger, userdb.NewRepository(client, logger))
|
||||
userH.Register(router)
|
||||
userH.RegisterPublic(engine)
|
||||
|
||||
for _, h := range Handlers(client, logger) {
|
||||
h.Register(router)
|
||||
}
|
||||
@@ -41,7 +46,6 @@ func Handlers(client postgresql.Client, logger *logging.Logger) []handlers.Handl
|
||||
// Swap sms.NewLogSender for your SMS provider: it only needs to
|
||||
// implement sms.Sender (Send(ctx, phone, message)).
|
||||
auth.NewHandler(logger, authdb.NewRepository(client, logger), sms.NewLogSender(logger)),
|
||||
user.NewHandler(logger, userdb.NewRepository(client, logger)),
|
||||
role.NewHandler(logger, roledb.NewRepository(client, logger)),
|
||||
permission.NewHandler(logger, permissiondb.NewRepository(client, logger)),
|
||||
roleusers.NewHandler(logger, roleusersdb.NewRepository(client, logger)),
|
||||
|
||||
@@ -24,9 +24,9 @@ func NewRepository(client postgresql.Client, logger *logging.Logger) user.Reposi
|
||||
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.social_media, u.light_mode, u.role, u.active, u.created_at, u.updated_at`
|
||||
const userColumns = `u.id, u.email, u.name, u.first_name, u.last_name, u.username, u.phone, u.avatar, u.role, u.active, u.created_at, u.updated_at`
|
||||
|
||||
const userReturningColumns = `id, email, name, first_name, last_name, username, phone, avatar, social_media, light_mode, role, active, created_at, updated_at`
|
||||
const userReturningColumns = `id, email, name, first_name, last_name, username, phone, avatar, role, active, created_at, updated_at`
|
||||
|
||||
func (r *repository) List(ctx context.Context, filter user.ListFilter) (user.ListUserDTO, error) {
|
||||
fromClause, whereClause, args := buildFilteredListQuery(filter, listVisibleRoles...)
|
||||
@@ -88,10 +88,7 @@ func (r *repository) ListStaff(ctx context.Context, filter user.ListFilter) (use
|
||||
|
||||
func buildStaffWhere(filter user.ListFilter) (whereClause string, args []interface{}) {
|
||||
conditions := []string{`EXISTS (SELECT 1 FROM branch_user bu WHERE bu.user_id = u.id)`}
|
||||
if filter.Username != "" {
|
||||
args = append(args, likePattern(filter.Username))
|
||||
conditions = append(conditions, fmt.Sprintf(`u.username ILIKE $%d`, len(args)))
|
||||
}
|
||||
conditions, args = appendNameSearch(conditions, args, filter.Search)
|
||||
return " WHERE " + strings.Join(conditions, " AND "), args
|
||||
}
|
||||
|
||||
@@ -136,11 +133,7 @@ func buildFilteredListQuery(filter user.ListFilter, roles ...string) (fromClause
|
||||
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))
|
||||
}
|
||||
conditions, args = appendNameSearch(conditions, args, filter.Search)
|
||||
if len(roles) == 1 {
|
||||
args = append(args, roles[0])
|
||||
n := len(args)
|
||||
@@ -161,6 +154,19 @@ func buildFilteredListQuery(filter user.ListFilter, roles ...string) (fromClause
|
||||
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, 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 likePattern(term string) string {
|
||||
term = strings.ReplaceAll(term, `\`, `\\`)
|
||||
term = strings.ReplaceAll(term, `%`, `\%`)
|
||||
@@ -170,6 +176,12 @@ func likePattern(term string) string {
|
||||
|
||||
func (r *repository) GetByRole(ctx context.Context, role string, filter user.ListFilter) (user.ListUserDTO, error) {
|
||||
fromClause, whereClause, args := buildFilteredListQuery(filter, role)
|
||||
excludeStaff := `NOT EXISTS (SELECT 1 FROM branch_user bu WHERE bu.user_id = u.id)`
|
||||
if whereClause == "" {
|
||||
whereClause = " WHERE " + excludeStaff
|
||||
} else {
|
||||
whereClause += " AND " + excludeStaff
|
||||
}
|
||||
return r.paginateUsers(ctx, filter, fromClause, whereClause, args)
|
||||
}
|
||||
|
||||
@@ -183,11 +195,6 @@ func (r *repository) GetByID(ctx context.Context, id int64) (user.UserDTO, error
|
||||
}
|
||||
|
||||
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
|
||||
@@ -198,37 +205,77 @@ func (r *repository) Create(ctx context.Context, dto user.CreateUserDTO) (user.U
|
||||
active = *dto.Active
|
||||
}
|
||||
|
||||
role := strings.TrimSpace(dto.Role)
|
||||
if role == "" {
|
||||
role = "user"
|
||||
}
|
||||
|
||||
tx, err := r.client.Begin(ctx)
|
||||
if err != nil {
|
||||
return user.UserDTO{}, err
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
|
||||
query := fmt.Sprintf(`
|
||||
INSERT INTO users (email, password, name, first_name, last_name, username, phone, avatar, social_media, light_mode, role, active)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)
|
||||
INSERT INTO users (email, password, name, first_name, last_name, username, phone, avatar, 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.Name, dto.FirstName, dto.LastName, dto.Username, dto.Phone, dto.Avatar, socialMedia, dto.LightMode, dto.Role, active,
|
||||
item, err := scanUser(tx.QueryRow(ctx, query,
|
||||
dto.Email, hashedPassword, dto.Name, dto.FirstName, dto.LastName, dto.Username, dto.Phone, dto.Avatar, 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
|
||||
}
|
||||
|
||||
if err := assignRoleByCode(ctx, tx, item.Id, role); err != nil {
|
||||
return user.UserDTO{}, err
|
||||
}
|
||||
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return user.UserDTO{}, err
|
||||
}
|
||||
return item, nil
|
||||
}
|
||||
|
||||
func (r *repository) Update(ctx context.Context, id int64, dto user.UpdateUserDTO) (user.UserDTO, error) {
|
||||
role := strings.TrimSpace(dto.Role)
|
||||
if role == "" {
|
||||
role = "user"
|
||||
}
|
||||
|
||||
tx, err := r.client.Begin(ctx)
|
||||
if err != nil {
|
||||
return user.UserDTO{}, err
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
|
||||
query := fmt.Sprintf(`
|
||||
UPDATE users SET
|
||||
email = $1, name = $2, first_name = $3, last_name = $4, username = $5, phone = $6, avatar = $7,
|
||||
social_media = $8, light_mode = $9, role = $10, active = $11,
|
||||
role = $8, active = $9,
|
||||
updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
|
||||
WHERE id = $12
|
||||
WHERE id = $10
|
||||
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, socialMedia, dto.LightMode, dto.Role, dto.Active, id,
|
||||
item, err := scanUser(tx.QueryRow(ctx, query,
|
||||
dto.Email, dto.Name, dto.FirstName, dto.LastName, dto.Username, dto.Phone, dto.Avatar, role, dto.Active, id,
|
||||
))
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return user.UserDTO{}, err
|
||||
}
|
||||
return item, err
|
||||
if err != nil {
|
||||
return user.UserDTO{}, err
|
||||
}
|
||||
|
||||
if err := replaceRoleByCode(ctx, tx, item.Id, role); err != nil {
|
||||
return user.UserDTO{}, err
|
||||
}
|
||||
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return user.UserDTO{}, err
|
||||
}
|
||||
return item, nil
|
||||
}
|
||||
|
||||
func (r *repository) Delete(ctx context.Context, id int64) error {
|
||||
@@ -242,38 +289,50 @@ func (r *repository) Delete(ctx context.Context, id int64) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func assignRoleByCode(ctx context.Context, tx pgx.Tx, userID int64, roleCode string) error {
|
||||
tag, err := tx.Exec(ctx, `
|
||||
INSERT INTO role_user (role_id, user_id)
|
||||
SELECT r.id, $1 FROM roles r WHERE r.code = $2`, userID, roleCode)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if tag.RowsAffected() == 0 {
|
||||
return fmt.Errorf("role %q not found", roleCode)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func replaceRoleByCode(ctx context.Context, tx pgx.Tx, userID int64, roleCode string) error {
|
||||
if _, err := tx.Exec(ctx, `DELETE FROM role_user WHERE user_id = $1`, userID); err != nil {
|
||||
return err
|
||||
}
|
||||
return assignRoleByCode(ctx, tx, userID, roleCode)
|
||||
}
|
||||
|
||||
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.Name, &item.FirstName, &item.LastName, &item.Username, &item.Phone, &item.Avatar,
|
||||
&socialMedia, &item.LightMode, &item.Role, &item.Active, &item.CreatedAt, &item.UpdatedAt,
|
||||
&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
|
||||
}
|
||||
|
||||
func scanStaffUser(row scannable) (user.UserDTO, error) {
|
||||
var item user.UserDTO
|
||||
var socialMedia []byte
|
||||
var branchesJSON []byte
|
||||
if err := row.Scan(
|
||||
&item.Id, &item.Email, &item.Name, &item.FirstName, &item.LastName, &item.Username, &item.Phone, &item.Avatar,
|
||||
&socialMedia, &item.LightMode, &item.Role, &item.Active, &item.CreatedAt, &item.UpdatedAt, &branchesJSON,
|
||||
&item.Role, &item.Active, &item.CreatedAt, &item.UpdatedAt, &branchesJSON,
|
||||
); err != nil {
|
||||
return user.UserDTO{}, err
|
||||
}
|
||||
if err := json.Unmarshal(socialMedia, &item.SocialMedia); err != nil {
|
||||
return user.UserDTO{}, err
|
||||
}
|
||||
if len(branchesJSON) == 0 || string(branchesJSON) == "null" {
|
||||
item.Branches = []user.StaffBranchDTO{}
|
||||
return item, nil
|
||||
|
||||
@@ -2,12 +2,6 @@ package user
|
||||
|
||||
import "time"
|
||||
|
||||
type SocialMedia struct {
|
||||
Facebook string `json:"facebook"`
|
||||
Instagram string `json:"instagram"`
|
||||
Telegram string `json:"telegram"`
|
||||
}
|
||||
|
||||
type LocalizedText struct {
|
||||
En string `json:"en"`
|
||||
Ru string `json:"ru"`
|
||||
@@ -21,56 +15,50 @@ type StaffBranchDTO struct {
|
||||
}
|
||||
|
||||
type UserDTO struct {
|
||||
Id int64 `json:"id"`
|
||||
Email string `json:"email"`
|
||||
Name string `json:"name"`
|
||||
FirstName string `json:"firstName"`
|
||||
LastName string `json:"lastName"`
|
||||
Username string `json:"username"`
|
||||
Phone string `json:"phone"`
|
||||
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"`
|
||||
Branches []StaffBranchDTO `json:"branches,omitempty"`
|
||||
Id int64 `json:"id"`
|
||||
Email string `json:"email"`
|
||||
Name string `json:"name"`
|
||||
FirstName string `json:"firstName"`
|
||||
LastName string `json:"lastName"`
|
||||
Username string `json:"username"`
|
||||
Phone string `json:"phone"`
|
||||
Avatar string `json:"avatar"`
|
||||
Role string `json:"role"`
|
||||
Active bool `json:"active"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
Branches []StaffBranchDTO `json:"branches,omitempty"`
|
||||
}
|
||||
|
||||
type CreateUserDTO struct {
|
||||
Email string `json:"email" binding:"required"`
|
||||
Password string `json:"password" binding:"required"`
|
||||
Name string `json:"name" binding:"required"`
|
||||
FirstName string `json:"firstName"`
|
||||
LastName string `json:"lastName"`
|
||||
Username string `json:"username" binding:"required"`
|
||||
Phone string `json:"phone"`
|
||||
Avatar string `json:"avatar"`
|
||||
SocialMedia SocialMedia `json:"socialMedia"`
|
||||
LightMode int `json:"lightMode"`
|
||||
Role string `json:"role"`
|
||||
Active *bool `json:"active"`
|
||||
Email string `json:"email" binding:"required"`
|
||||
Password string `json:"password" binding:"required"`
|
||||
Name string `json:"name" binding:"required"`
|
||||
FirstName string `json:"firstName"`
|
||||
LastName string `json:"lastName"`
|
||||
Username string `json:"username" binding:"required"`
|
||||
Phone string `json:"phone"`
|
||||
Avatar string `json:"avatar"`
|
||||
Role string `json:"role"`
|
||||
Active *bool `json:"active"`
|
||||
}
|
||||
|
||||
type UpdateUserDTO struct {
|
||||
Email string `json:"email" binding:"required"`
|
||||
Name string `json:"name" binding:"required"`
|
||||
FirstName string `json:"firstName"`
|
||||
LastName string `json:"lastName"`
|
||||
Username string `json:"username" binding:"required"`
|
||||
Phone string `json:"phone"`
|
||||
Avatar string `json:"avatar"`
|
||||
SocialMedia SocialMedia `json:"socialMedia"`
|
||||
LightMode int `json:"lightMode"`
|
||||
Role string `json:"role"`
|
||||
Active bool `json:"active"`
|
||||
Email string `json:"email" binding:"required"`
|
||||
Name string `json:"name" binding:"required"`
|
||||
FirstName string `json:"firstName"`
|
||||
LastName string `json:"lastName"`
|
||||
Username string `json:"username" binding:"required"`
|
||||
Phone string `json:"phone"`
|
||||
Avatar string `json:"avatar"`
|
||||
Role string `json:"role"`
|
||||
Active bool `json:"active"`
|
||||
}
|
||||
|
||||
type ListFilter struct {
|
||||
Username string
|
||||
Page int
|
||||
Limit int
|
||||
Search string
|
||||
Page int
|
||||
Limit int
|
||||
}
|
||||
|
||||
type ListUserDTO struct {
|
||||
|
||||
@@ -13,7 +13,6 @@ import (
|
||||
|
||||
"online-back/internal/appresult"
|
||||
"online-back/internal/config"
|
||||
"online-back/internal/handlers"
|
||||
"online-back/pkg/logging"
|
||||
minioUpload "online-back/pkg/minio"
|
||||
|
||||
@@ -23,9 +22,10 @@ import (
|
||||
)
|
||||
|
||||
const (
|
||||
baseURL = "/users"
|
||||
fileUploadURL = "/file"
|
||||
fileURL = "/file/:id"
|
||||
baseURL = "/users"
|
||||
fileUploadURL = "/file"
|
||||
fileURL = "/file/:id"
|
||||
publicFileURL = "/file/:file_name"
|
||||
)
|
||||
|
||||
type handler struct {
|
||||
@@ -33,7 +33,7 @@ type handler struct {
|
||||
repository Repository
|
||||
}
|
||||
|
||||
func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler {
|
||||
func NewHandler(logger *logging.Logger, repository Repository) *handler {
|
||||
return &handler{logger: logger, repository: repository}
|
||||
}
|
||||
|
||||
@@ -47,22 +47,25 @@ func (h *handler) Register(router *gin.RouterGroup) {
|
||||
group.PUT("/:id", h.update)
|
||||
group.DELETE("/:id", h.delete)
|
||||
|
||||
// Avatar/profile file storage — kept at the top-level /file path (not
|
||||
// nested under /users) to preserve the existing API contract; this used
|
||||
// to live in the auth handler purely incidentally.
|
||||
// Upload/delete stay on the admin API (JWT). GET is public at /file/:file_name
|
||||
// so nginx can serve avatars as https://host/file/<file_name>.
|
||||
files := router.Group("", appresult.JwtTokenCheck())
|
||||
files.POST(fileUploadURL, h.fileUpload)
|
||||
files.GET(fileURL, h.getFile)
|
||||
files.DELETE(fileURL, h.deleteFile)
|
||||
}
|
||||
|
||||
func (h *handler) RegisterPublic(engine *gin.Engine) {
|
||||
engine.GET(publicFileURL, h.getFile)
|
||||
}
|
||||
|
||||
// list godoc
|
||||
// @Summary List users
|
||||
// @Description Returns paginated users with role user, with optional filters
|
||||
// @Tags user
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param username query string false "Filter by username"
|
||||
// @Param search query string false "Search by username, first name, or last name"
|
||||
// @Param username query string false "Alias for search"
|
||||
// @Param page query int false "Page number" default(1)
|
||||
// @Param limit query int false "Items per page" default(10)
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
@@ -88,11 +91,12 @@ func (h *handler) list(c *gin.Context) {
|
||||
|
||||
// listClients godoc
|
||||
// @Summary List client users
|
||||
// @Description Returns paginated users from the users table with role user
|
||||
// @Description Returns paginated client users (role user, not assigned to any branch)
|
||||
// @Tags user
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param username query string false "Filter by username"
|
||||
// @Param search query string false "Search by username, first name, or last name"
|
||||
// @Param username query string false "Alias for search"
|
||||
// @Param page query int false "Page number" default(1)
|
||||
// @Param limit query int false "Items per page" default(10)
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
@@ -122,7 +126,8 @@ func (h *handler) listClients(c *gin.Context) {
|
||||
// @Tags user
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param username query string false "Filter by username"
|
||||
// @Param search query string false "Search by username, first name, or last name"
|
||||
// @Param username query string false "Alias for search"
|
||||
// @Param page query int false "Page number" default(1)
|
||||
// @Param limit query int false "Items per page" default(10)
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
@@ -316,8 +321,10 @@ func parseListFilter(c *gin.Context) (ListFilter, bool) {
|
||||
filter.Limit = limit
|
||||
}
|
||||
|
||||
if raw := strings.TrimSpace(c.Query("username")); raw != "" {
|
||||
filter.Username = raw
|
||||
if raw := strings.TrimSpace(c.Query("search")); raw != "" {
|
||||
filter.Search = raw
|
||||
} else if raw := strings.TrimSpace(c.Query("username")); raw != "" {
|
||||
filter.Search = raw
|
||||
}
|
||||
|
||||
return filter, true
|
||||
@@ -370,16 +377,21 @@ func (h *handler) fileUpload(c *gin.Context) {
|
||||
}
|
||||
|
||||
// getFile godoc
|
||||
// @Description download file
|
||||
// @Description download file by object name (public; not under /api/admin)
|
||||
// @Tags file-upload
|
||||
// @Produce octet-stream
|
||||
// @Param id path string true "object name"
|
||||
// @Security BearerAuth
|
||||
// @Param file_name path string true "object name"
|
||||
// @Success 200 {file} binary
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /file/{id} [get]
|
||||
// @Router /file/{file_name} [get]
|
||||
func (h *handler) getFile(c *gin.Context) {
|
||||
id := c.Param("id")
|
||||
fileName := c.Param("file_name")
|
||||
if fileName == "" || strings.Contains(fileName, "..") || strings.ContainsAny(fileName, "/\\") {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
minioCfg := config.GetConfig().Minio
|
||||
minioClient, ok := h.connectMinio(c, minioCfg)
|
||||
@@ -387,7 +399,7 @@ func (h *handler) getFile(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
object, err := minioClient.GetObject(c.Request.Context(), minioCfg.Bucket, id, minio.GetObjectOptions{})
|
||||
object, err := minioClient.GetObject(c.Request.Context(), minioCfg.Bucket, fileName, minio.GetObjectOptions{})
|
||||
if err != nil {
|
||||
h.logger.Errorf("get object from minio failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrNotAcceptable)
|
||||
|
||||
19
nginx/file.conf
Normal file
19
nginx/file.conf
Normal file
@@ -0,0 +1,19 @@
|
||||
# Public file download (MinIO objects).
|
||||
# Copy into the HTTPS server block, or:
|
||||
# sudo cp nginx/file.conf /etc/nginx/snippets/online-back-file.conf
|
||||
# include /etc/nginx/snippets/online-back-file.conf;
|
||||
#
|
||||
# URL: https://<host>/file/<file_name>
|
||||
# App: GET http://127.0.0.1:5005/file/<file_name>
|
||||
|
||||
location /file/ {
|
||||
proxy_pass http://127.0.0.1:5005/file/;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
|
||||
expires 7d;
|
||||
add_header Cache-Control "public, max-age=604800";
|
||||
}
|
||||
@@ -30,6 +30,19 @@ server {
|
||||
include /etc/letsencrypt/options-ssl-nginx.conf;
|
||||
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;
|
||||
|
||||
# Public MinIO files: https://test.webulgam.com/file/<file_name>
|
||||
# Snippet lives at nginx/file.conf — copy to snippets if you prefer include.
|
||||
location /file/ {
|
||||
proxy_pass http://127.0.0.1:5005/file/;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
expires 7d;
|
||||
add_header Cache-Control "public, max-age=604800";
|
||||
}
|
||||
|
||||
# --- existing project → :5050 ---
|
||||
location /admin {
|
||||
proxy_pass http://127.0.0.1:5050;
|
||||
|
||||
Reference in New Issue
Block a user