active log add
This commit is contained in:
8
Makefile
8
Makefile
@@ -8,12 +8,12 @@ create-migration:
|
||||
|
||||
# --- for Macos
|
||||
migrate:
|
||||
migrate -database 'postgres://bank_admin:bank@#23#@_password@localhost:5424/bank_db?sslmode=disable' -path db/migrations up
|
||||
migrate -database 'postgres://bank_admin:bank%40%2323%23%40_password@localhost:5424/bank_db?sslmode=disable' -path db/migrations up
|
||||
migrate-rollback:
|
||||
migrate -database 'postgres://bank_admin:bank@#23#@_password@localhost:5424/bank_db?sslmode=disable' -path db/migrations down
|
||||
migrate -database 'postgres://bank_admin:bank%40%2323%23%40_password@localhost:5424/bank_db?sslmode=disable' -path db/migrations down
|
||||
|
||||
# ---- for linux
|
||||
# migrate:
|
||||
# migrate -database 'postgresql://bank_admin:bank@#23#@_password@localhost:5454/bank_db?sslmode=disable' -path db/migrations up
|
||||
# migrate -database 'postgresql://bank_admin:bank%40%2323%23%40_password@localhost:5454/bank_db?sslmode=disable' -path db/migrations up
|
||||
# migrate-rollback:
|
||||
# migrate -database 'postgresql://bank_admin:bank@#23#@_password@localhost:5454/bank_db?sslmode=disable' -path db/migrations down
|
||||
# migrate -database 'postgresql://bank_admin:bank%40%2323%23%40_password@localhost:5454/bank_db?sslmode=disable' -path db/migrations down
|
||||
|
||||
2
app.go
2
app.go
@@ -41,6 +41,8 @@ import (
|
||||
// @tag.description Loan repayments
|
||||
// @tag.name card-orders
|
||||
// @tag.description Card orders
|
||||
// @tag.name activity-logs
|
||||
// @tag.description User activity audit trail
|
||||
func main() {
|
||||
docs.SwaggerInfo.Title = "Service APIs"
|
||||
docs.SwaggerInfo.Version = "1.0"
|
||||
|
||||
@@ -1,28 +1,3 @@
|
||||
CREATE TABLE IF NOT EXISTS roles (
|
||||
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
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS role_user (
|
||||
id bigserial PRIMARY KEY,
|
||||
role_id bigint REFERENCES roles(id),
|
||||
user_id bigint REFERENCES users(id),
|
||||
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 permission_user (
|
||||
id bigserial PRIMARY KEY,
|
||||
permission_id bigint REFERENCES permissions(id),
|
||||
user_id bigint REFERENCES users(id),
|
||||
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 users (
|
||||
"id" bigserial primary key,
|
||||
"email" character varying(250) NOT NULL DEFAULT '',
|
||||
@@ -114,6 +89,31 @@ CREATE TABLE IF NOT EXISTS permissions (
|
||||
updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS roles (
|
||||
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
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS role_user (
|
||||
id bigserial PRIMARY KEY,
|
||||
role_id bigint REFERENCES roles(id),
|
||||
user_id bigint REFERENCES users(id),
|
||||
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 permission_user (
|
||||
id bigserial PRIMARY KEY,
|
||||
permission_id bigint REFERENCES permissions(id),
|
||||
user_id bigint REFERENCES users(id),
|
||||
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 branch_user (
|
||||
id bigserial PRIMARY KEY,
|
||||
branch_id bigint REFERENCES branches(id),
|
||||
|
||||
1
db/migrations/20260716170338_activity_logs.down.sql
Normal file
1
db/migrations/20260716170338_activity_logs.down.sql
Normal file
@@ -0,0 +1 @@
|
||||
DROP TABLE IF EXISTS activity_logs;
|
||||
18
db/migrations/20260716170338_activity_logs.up.sql
Normal file
18
db/migrations/20260716170338_activity_logs.up.sql
Normal file
@@ -0,0 +1,18 @@
|
||||
CREATE TABLE IF NOT EXISTS activity_logs (
|
||||
id bigserial PRIMARY KEY,
|
||||
user_id bigint,
|
||||
method character varying(10) NOT NULL DEFAULT '',
|
||||
path character varying(255) NOT NULL DEFAULT '',
|
||||
module character varying(100) NOT NULL DEFAULT '',
|
||||
action character varying(50) NOT NULL DEFAULT '',
|
||||
status_code integer NOT NULL DEFAULT 0,
|
||||
request_body jsonb,
|
||||
ip character varying(50) NOT NULL DEFAULT '',
|
||||
created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
|
||||
CONSTRAINT activity_logs_user_id_fkey
|
||||
FOREIGN KEY ("user_id") REFERENCES users(id)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_activity_logs_user_id ON activity_logs(user_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_activity_logs_module ON activity_logs(module);
|
||||
CREATE INDEX IF NOT EXISTS idx_activity_logs_created_at ON activity_logs(created_at);
|
||||
123
docs/docs.go
123
docs/docs.go
@@ -15,6 +15,129 @@ const docTemplate = `{
|
||||
"host": "{{.Host}}",
|
||||
"basePath": "{{.BasePath}}",
|
||||
"paths": {
|
||||
"/activity-logs": {
|
||||
"get": {
|
||||
"security": [
|
||||
{
|
||||
"BearerAuth": []
|
||||
}
|
||||
],
|
||||
"description": "Returns a paginated audit trail of user actions (create/update/delete)",
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
"tags": [
|
||||
"activity-logs"
|
||||
],
|
||||
"summary": "List activity logs",
|
||||
"parameters": [
|
||||
{
|
||||
"type": "integer",
|
||||
"description": "Filter by user ID",
|
||||
"name": "user_id",
|
||||
"in": "query"
|
||||
},
|
||||
{
|
||||
"type": "string",
|
||||
"description": "Filter by module (e.g. cards, branch-users)",
|
||||
"name": "module",
|
||||
"in": "query"
|
||||
},
|
||||
{
|
||||
"type": "string",
|
||||
"description": "Filter by action (create, update, delete)",
|
||||
"name": "action",
|
||||
"in": "query"
|
||||
},
|
||||
{
|
||||
"type": "integer",
|
||||
"default": 1,
|
||||
"description": "Page number",
|
||||
"name": "page",
|
||||
"in": "query"
|
||||
},
|
||||
{
|
||||
"type": "integer",
|
||||
"default": 10,
|
||||
"description": "Items per page",
|
||||
"name": "limit",
|
||||
"in": "query"
|
||||
}
|
||||
],
|
||||
"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"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/activity-logs/{id}": {
|
||||
"get": {
|
||||
"security": [
|
||||
{
|
||||
"BearerAuth": []
|
||||
}
|
||||
],
|
||||
"description": "Returns a single activity log entry",
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
"tags": [
|
||||
"activity-logs"
|
||||
],
|
||||
"summary": "Get activity log by ID",
|
||||
"parameters": [
|
||||
{
|
||||
"type": "integer",
|
||||
"description": "Activity log ID",
|
||||
"name": "id",
|
||||
"in": "path",
|
||||
"required": true
|
||||
}
|
||||
],
|
||||
"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"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/branch-users": {
|
||||
"get": {
|
||||
"security": [
|
||||
|
||||
@@ -9,6 +9,129 @@
|
||||
"host": "localhost:5050",
|
||||
"basePath": "/api/admin",
|
||||
"paths": {
|
||||
"/activity-logs": {
|
||||
"get": {
|
||||
"security": [
|
||||
{
|
||||
"BearerAuth": []
|
||||
}
|
||||
],
|
||||
"description": "Returns a paginated audit trail of user actions (create/update/delete)",
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
"tags": [
|
||||
"activity-logs"
|
||||
],
|
||||
"summary": "List activity logs",
|
||||
"parameters": [
|
||||
{
|
||||
"type": "integer",
|
||||
"description": "Filter by user ID",
|
||||
"name": "user_id",
|
||||
"in": "query"
|
||||
},
|
||||
{
|
||||
"type": "string",
|
||||
"description": "Filter by module (e.g. cards, branch-users)",
|
||||
"name": "module",
|
||||
"in": "query"
|
||||
},
|
||||
{
|
||||
"type": "string",
|
||||
"description": "Filter by action (create, update, delete)",
|
||||
"name": "action",
|
||||
"in": "query"
|
||||
},
|
||||
{
|
||||
"type": "integer",
|
||||
"default": 1,
|
||||
"description": "Page number",
|
||||
"name": "page",
|
||||
"in": "query"
|
||||
},
|
||||
{
|
||||
"type": "integer",
|
||||
"default": 10,
|
||||
"description": "Items per page",
|
||||
"name": "limit",
|
||||
"in": "query"
|
||||
}
|
||||
],
|
||||
"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"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/activity-logs/{id}": {
|
||||
"get": {
|
||||
"security": [
|
||||
{
|
||||
"BearerAuth": []
|
||||
}
|
||||
],
|
||||
"description": "Returns a single activity log entry",
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
"tags": [
|
||||
"activity-logs"
|
||||
],
|
||||
"summary": "Get activity log by ID",
|
||||
"parameters": [
|
||||
{
|
||||
"type": "integer",
|
||||
"description": "Activity log ID",
|
||||
"name": "id",
|
||||
"in": "path",
|
||||
"required": true
|
||||
}
|
||||
],
|
||||
"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"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/branch-users": {
|
||||
"get": {
|
||||
"security": [
|
||||
|
||||
@@ -1221,6 +1221,85 @@ info:
|
||||
title: Service APIs
|
||||
version: "1.0"
|
||||
paths:
|
||||
/activity-logs:
|
||||
get:
|
||||
description: Returns a paginated audit trail of user actions (create/update/delete)
|
||||
parameters:
|
||||
- description: Filter by user ID
|
||||
in: query
|
||||
name: user_id
|
||||
type: integer
|
||||
- description: Filter by module (e.g. cards, branch-users)
|
||||
in: query
|
||||
name: module
|
||||
type: string
|
||||
- description: Filter by action (create, update, delete)
|
||||
in: query
|
||||
name: action
|
||||
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 activity logs
|
||||
tags:
|
||||
- activity-logs
|
||||
/activity-logs/{id}:
|
||||
get:
|
||||
description: Returns a single activity log entry
|
||||
parameters:
|
||||
- description: Activity log 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 activity log by ID
|
||||
tags:
|
||||
- activity-logs
|
||||
/branch-users:
|
||||
get:
|
||||
description: Returns the authenticated user's branch-user assignments with the
|
||||
|
||||
@@ -6,6 +6,8 @@ import (
|
||||
"online-back/internal/cards"
|
||||
"online-back/internal/config"
|
||||
"online-back/internal/identity"
|
||||
"online-back/internal/identity/activitylog"
|
||||
activitylogdb "online-back/internal/identity/activitylog/db"
|
||||
"online-back/internal/lending"
|
||||
"online-back/internal/org"
|
||||
"online-back/pkg/logging"
|
||||
@@ -41,6 +43,7 @@ func New(cfg *config.Config, client *pgxpool.Pool, logger *logging.Logger) *gin.
|
||||
}))
|
||||
|
||||
adminGroup := router.Group(adminAPIPrefix)
|
||||
adminGroup.Use(activitylog.Record(activitylogdb.NewRepository(client, logger), logger))
|
||||
|
||||
// Each bounded context registers its own modules' handlers.
|
||||
// Add new modules inside the relevant context's router.go rather than here.
|
||||
|
||||
97
internal/identity/activitylog/db/postgresql.go
Normal file
97
internal/identity/activitylog/db/postgresql.go
Normal file
@@ -0,0 +1,97 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"online-back/internal/identity/activitylog"
|
||||
"online-back/pkg/client/postgresql"
|
||||
"online-back/pkg/logging"
|
||||
"online-back/pkg/repository/genericrepo"
|
||||
)
|
||||
|
||||
type repository struct {
|
||||
client postgresql.Client
|
||||
generic *genericrepo.Repository[activitylog.ActivityLogDTO]
|
||||
logger *logging.Logger
|
||||
}
|
||||
|
||||
func NewRepository(client postgresql.Client, logger *logging.Logger) activitylog.Repository {
|
||||
return &repository{
|
||||
client: client,
|
||||
generic: genericrepo.New(client, "activity_logs", activityLogColumnsSQL, scanActivityLog),
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
var activityLogColumns = []string{
|
||||
"id", "user_id", "method", "path", "module", "action", "status_code", "request_body", "ip", "created_at",
|
||||
}
|
||||
|
||||
var activityLogColumnsSQL = strings.Join(activityLogColumns, ", ")
|
||||
|
||||
func (r *repository) List(ctx context.Context, filter activitylog.ListFilter) (activitylog.ListActivityLogDTO, error) {
|
||||
whereClause, args := buildListQuery(filter)
|
||||
|
||||
items, count, err := r.generic.List(ctx, whereClause, args, filter.Page, filter.Limit, "id DESC")
|
||||
if err != nil {
|
||||
return activitylog.ListActivityLogDTO{}, err
|
||||
}
|
||||
|
||||
return activitylog.ListActivityLogDTO{Count: count, Logs: items}, nil
|
||||
}
|
||||
|
||||
func buildListQuery(filter activitylog.ListFilter) (whereClause string, args []interface{}) {
|
||||
var conditions []string
|
||||
|
||||
if filter.UserId != nil {
|
||||
args = append(args, *filter.UserId)
|
||||
conditions = append(conditions, fmt.Sprintf("user_id = $%d", len(args)))
|
||||
}
|
||||
|
||||
if filter.Module != "" {
|
||||
args = append(args, filter.Module)
|
||||
conditions = append(conditions, fmt.Sprintf("module = $%d", len(args)))
|
||||
}
|
||||
|
||||
if filter.Action != "" {
|
||||
args = append(args, filter.Action)
|
||||
conditions = append(conditions, fmt.Sprintf("action = $%d", len(args)))
|
||||
}
|
||||
|
||||
if len(conditions) == 0 {
|
||||
return "", args
|
||||
}
|
||||
|
||||
return " WHERE " + strings.Join(conditions, " AND "), args
|
||||
}
|
||||
|
||||
func (r *repository) GetByID(ctx context.Context, id int64) (activitylog.ActivityLogDTO, error) {
|
||||
return r.generic.GetByID(ctx, id)
|
||||
}
|
||||
|
||||
func (r *repository) Create(ctx context.Context, dto activitylog.CreateActivityLogDTO) (activitylog.ActivityLogDTO, error) {
|
||||
query := `INSERT INTO activity_logs (user_id, method, path, module, action, status_code, request_body, ip)
|
||||
VALUES ($1,$2,$3,$4,$5,$6,$7,$8) RETURNING ` + activityLogColumnsSQL
|
||||
|
||||
row := r.client.QueryRow(ctx, query,
|
||||
dto.UserId, dto.Method, dto.Path, dto.Module, dto.Action, dto.StatusCode, dto.RequestBody, dto.Ip,
|
||||
)
|
||||
return scanActivityLog(row)
|
||||
}
|
||||
|
||||
func scanActivityLog(row genericrepo.Scanner) (activitylog.ActivityLogDTO, error) {
|
||||
var item activitylog.ActivityLogDTO
|
||||
var requestBody []byte
|
||||
|
||||
err := row.Scan(
|
||||
&item.Id, &item.UserId, &item.Method, &item.Path, &item.Module, &item.Action,
|
||||
&item.StatusCode, &requestBody, &item.Ip, &item.CreatedAt,
|
||||
)
|
||||
if err != nil {
|
||||
return activitylog.ActivityLogDTO{}, err
|
||||
}
|
||||
item.RequestBody = requestBody
|
||||
return item, nil
|
||||
}
|
||||
45
internal/identity/activitylog/dto.go
Normal file
45
internal/identity/activitylog/dto.go
Normal file
@@ -0,0 +1,45 @@
|
||||
package activitylog
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"time"
|
||||
)
|
||||
|
||||
type ActivityLogDTO struct {
|
||||
Id int64 `json:"id"`
|
||||
UserId *int64 `json:"userId"`
|
||||
Method string `json:"method"`
|
||||
Path string `json:"path"`
|
||||
Module string `json:"module"`
|
||||
Action string `json:"action"`
|
||||
StatusCode int `json:"statusCode"`
|
||||
RequestBody json.RawMessage `json:"requestBody"`
|
||||
Ip string `json:"ip"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
}
|
||||
|
||||
// CreateActivityLogDTO is filled in by the Record middleware for every
|
||||
// mutating request made by an authenticated user.
|
||||
type CreateActivityLogDTO struct {
|
||||
UserId *int64
|
||||
Method string
|
||||
Path string
|
||||
Module string
|
||||
Action string
|
||||
StatusCode int
|
||||
RequestBody []byte
|
||||
Ip string
|
||||
}
|
||||
|
||||
type ListFilter struct {
|
||||
UserId *int64
|
||||
Module string
|
||||
Action string
|
||||
Page int
|
||||
Limit int
|
||||
}
|
||||
|
||||
type ListActivityLogDTO struct {
|
||||
Count int64 `json:"count"`
|
||||
Logs []ActivityLogDTO `json:"logs"`
|
||||
}
|
||||
148
internal/identity/activitylog/handler.go
Normal file
148
internal/identity/activitylog/handler.go
Normal file
@@ -0,0 +1,148 @@
|
||||
package activitylog
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"online-back/internal/appresult"
|
||||
"online-back/internal/handlers"
|
||||
"online-back/pkg/logging"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/jackc/pgx/v4"
|
||||
)
|
||||
|
||||
const baseURL = "/activity-logs"
|
||||
|
||||
type handler struct {
|
||||
logger *logging.Logger
|
||||
repository Repository
|
||||
}
|
||||
|
||||
func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler {
|
||||
return &handler{logger: logger, repository: repository}
|
||||
}
|
||||
|
||||
// Register only wires read endpoints: activity log entries are written by
|
||||
// the Record middleware, never through the API.
|
||||
func (h *handler) Register(router *gin.RouterGroup) {
|
||||
group := router.Group(baseURL, appresult.JwtTokenCheck())
|
||||
group.GET("", h.list)
|
||||
group.GET("/:id", h.getByID)
|
||||
}
|
||||
|
||||
// list godoc
|
||||
// @Summary List activity logs
|
||||
// @Description Returns a paginated audit trail of user actions (create/update/delete)
|
||||
// @Tags activity-logs
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param user_id query int false "Filter by user ID"
|
||||
// @Param module query string false "Filter by module (e.g. cards, branch-users)"
|
||||
// @Param action query string false "Filter by action (create, update, delete)"
|
||||
// @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 /activity-logs [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 activity logs failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
|
||||
}
|
||||
|
||||
// getByID godoc
|
||||
// @Summary Get activity log by ID
|
||||
// @Description Returns a single activity log entry
|
||||
// @Tags activity-logs
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "Activity log ID"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /activity-logs/{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 activity log failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
|
||||
}
|
||||
|
||||
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("user_id"); raw != "" {
|
||||
id, ok := parseID(raw)
|
||||
if !ok {
|
||||
return ListFilter{}, false
|
||||
}
|
||||
filter.UserId = &id
|
||||
}
|
||||
|
||||
filter.Module = c.Query("module")
|
||||
filter.Action = c.Query("action")
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
return filter, true
|
||||
}
|
||||
176
internal/identity/activitylog/middleware.go
Normal file
176
internal/identity/activitylog/middleware.go
Normal file
@@ -0,0 +1,176 @@
|
||||
package activitylog
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"online-back/pkg/logging"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// sensitiveFieldSubstrings marks request body keys that must never be
|
||||
// persisted verbatim (login passwords, branch billing credentials, etc).
|
||||
var sensitiveFieldSubstrings = []string{"password", "token", "secret"}
|
||||
|
||||
const writeTimeout = 5 * time.Second
|
||||
|
||||
// Record returns a global gin middleware that persists every mutating
|
||||
// (POST/PUT/PATCH/DELETE) request made by an authenticated user into
|
||||
// activity_logs - e.g. creating a card or attaching a user to a branch.
|
||||
// Read-only (GET) requests are not recorded. It must run after
|
||||
// appresult.JwtTokenCheck has set "id" in the context, which happens
|
||||
// naturally here since c.Next() runs the rest of the chain first.
|
||||
func Record(repository Repository, logger *logging.Logger) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
if !shouldRecord(c.Request.Method) {
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
|
||||
body := readAndRestoreBody(c)
|
||||
|
||||
c.Next()
|
||||
|
||||
userID := currentUserID(c)
|
||||
if userID == nil {
|
||||
return
|
||||
}
|
||||
|
||||
module, action := describeRoute(c)
|
||||
entry := CreateActivityLogDTO{
|
||||
UserId: userID,
|
||||
Method: c.Request.Method,
|
||||
Path: c.Request.URL.Path,
|
||||
Module: module,
|
||||
Action: action,
|
||||
StatusCode: c.Writer.Status(),
|
||||
RequestBody: redact(body),
|
||||
Ip: c.ClientIP(),
|
||||
}
|
||||
|
||||
go func() {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), writeTimeout)
|
||||
defer cancel()
|
||||
if _, err := repository.Create(ctx, entry); err != nil {
|
||||
logger.Errorf("record activity log failed: %v", err)
|
||||
}
|
||||
}()
|
||||
}
|
||||
}
|
||||
|
||||
func shouldRecord(method string) bool {
|
||||
switch method {
|
||||
case http.MethodPost, http.MethodPut, http.MethodPatch, http.MethodDelete:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func readAndRestoreBody(c *gin.Context) []byte {
|
||||
if c.Request.Body == nil {
|
||||
return nil
|
||||
}
|
||||
data, err := io.ReadAll(c.Request.Body)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
c.Request.Body = io.NopCloser(bytes.NewReader(data))
|
||||
return data
|
||||
}
|
||||
|
||||
func currentUserID(c *gin.Context) *int64 {
|
||||
raw, exists := c.Get("id")
|
||||
if !exists {
|
||||
return nil
|
||||
}
|
||||
|
||||
switch v := raw.(type) {
|
||||
case int64:
|
||||
return &v
|
||||
case int:
|
||||
id := int64(v)
|
||||
return &id
|
||||
case string:
|
||||
id, err := strconv.ParseInt(v, 10, 64)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
return &id
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// describeRoute derives a module (e.g. "cards", "branch-users") and an
|
||||
// action (create/update/delete) from the matched route so entries stay
|
||||
// meaningful even though logging is wired generically for every module.
|
||||
func describeRoute(c *gin.Context) (module, action string) {
|
||||
action = actionFromMethod(c.Request.Method)
|
||||
|
||||
route := c.FullPath()
|
||||
if route == "" {
|
||||
route = c.Request.URL.Path
|
||||
}
|
||||
|
||||
segments := strings.Split(strings.Trim(route, "/"), "/")
|
||||
for i, segment := range segments {
|
||||
if segment == "admin" && i+1 < len(segments) {
|
||||
return segments[i+1], action
|
||||
}
|
||||
}
|
||||
if len(segments) > 0 {
|
||||
return segments[0], action
|
||||
}
|
||||
return "", action
|
||||
}
|
||||
|
||||
func actionFromMethod(method string) string {
|
||||
switch method {
|
||||
case http.MethodPost:
|
||||
return "create"
|
||||
case http.MethodPut, http.MethodPatch:
|
||||
return "update"
|
||||
case http.MethodDelete:
|
||||
return "delete"
|
||||
default:
|
||||
return strings.ToLower(method)
|
||||
}
|
||||
}
|
||||
|
||||
// redact blanks out sensitive fields (passwords, tokens, secrets) before a
|
||||
// request body is stored. Bodies that aren't a JSON object are dropped
|
||||
// entirely rather than risk leaking something unparsed.
|
||||
func redact(body []byte) []byte {
|
||||
if len(body) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
var payload map[string]interface{}
|
||||
if err := json.Unmarshal(body, &payload); err != nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
for key := range payload {
|
||||
lower := strings.ToLower(key)
|
||||
for _, needle := range sensitiveFieldSubstrings {
|
||||
if strings.Contains(lower, needle) {
|
||||
payload[key] = "***"
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
redacted, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
return redacted
|
||||
}
|
||||
9
internal/identity/activitylog/storage.go
Normal file
9
internal/identity/activitylog/storage.go
Normal file
@@ -0,0 +1,9 @@
|
||||
package activitylog
|
||||
|
||||
import "context"
|
||||
|
||||
type Repository interface {
|
||||
List(ctx context.Context, filter ListFilter) (ListActivityLogDTO, error)
|
||||
GetByID(ctx context.Context, id int64) (ActivityLogDTO, error)
|
||||
Create(ctx context.Context, dto CreateActivityLogDTO) (ActivityLogDTO, error)
|
||||
}
|
||||
@@ -5,6 +5,8 @@ package identity
|
||||
|
||||
import (
|
||||
"online-back/internal/handlers"
|
||||
"online-back/internal/identity/activitylog"
|
||||
activitylogdb "online-back/internal/identity/activitylog/db"
|
||||
"online-back/internal/identity/auth"
|
||||
authdb "online-back/internal/identity/auth/db"
|
||||
"online-back/internal/identity/permission"
|
||||
@@ -34,6 +36,7 @@ func Register(router *gin.RouterGroup, client postgresql.Client, logger *logging
|
||||
|
||||
func Handlers(client postgresql.Client, logger *logging.Logger) []handlers.Handler {
|
||||
return []handlers.Handler{
|
||||
activitylog.NewHandler(logger, activitylogdb.NewRepository(client, logger)),
|
||||
auth.NewHandler(logger, authdb.NewRepository(client, logger)),
|
||||
user.NewHandler(logger, userdb.NewRepository(client, logger)),
|
||||
role.NewHandler(logger, roledb.NewRepository(client, logger)),
|
||||
|
||||
Reference in New Issue
Block a user