active log add

This commit is contained in:
2026-07-16 17:53:45 +05:00
parent 585ba63bc2
commit 3636e1ca53
15 changed files with 856 additions and 29 deletions

View File

@@ -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.

View 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
}

View 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"`
}

View 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
}

View 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
}

View 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)
}

View File

@@ -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)),