fix: 管理员活跃时间记录

This commit is contained in:
yokowu
2025-07-17 16:45:27 +08:00
parent d447fa4a11
commit 5cd90f681c
12 changed files with 79 additions and 33 deletions

View File

@@ -6,9 +6,10 @@ import (
"log/slog"
"time"
"github.com/chaitin/MonkeyCode/backend/consts"
"github.com/labstack/echo/v4"
"github.com/redis/go-redis/v9"
"github.com/chaitin/MonkeyCode/backend/consts"
)
type ActiveMiddleware struct {
@@ -23,14 +24,24 @@ func NewActiveMiddleware(redis *redis.Client, logger *slog.Logger) *ActiveMiddle
}
}
func (a *ActiveMiddleware) Active() echo.MiddlewareFunc {
func (a *ActiveMiddleware) Active(scope string) echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
if apikey := GetApiKey(c); apikey != nil {
if err := a.redis.Set(context.Background(), fmt.Sprintf(consts.UserActiveKeyFmt, apikey.UserID), time.Now().Unix(), 0).Err(); err != nil {
a.logger.With("error", err).ErrorContext(c.Request().Context(), "failed to set user active status in Redis")
switch scope {
case "admin":
if user := GetUser(c); user != nil {
if err := a.redis.Set(context.Background(), fmt.Sprintf(consts.AdminActiveKeyFmt, user.ID), time.Now().Unix(), 0).Err(); err != nil {
a.logger.With("error", err).ErrorContext(c.Request().Context(), "failed to set admin active status in Redis")
}
}
case "user":
if apikey := GetApiKey(c); apikey != nil {
if err := a.redis.Set(context.Background(), fmt.Sprintf(consts.UserActiveKeyFmt, apikey.UserID), time.Now().Unix(), 0).Err(); err != nil {
a.logger.With("error", err).ErrorContext(c.Request().Context(), "failed to set user active status in Redis")
}
}
}
return next(c)
}
}