Files
MonkeyCode/backend/internal/middleware/active.go

55 lines
1.6 KiB
Go
Raw Normal View History

2025-07-04 10:56:03 +08:00
package middleware
import (
"context"
"fmt"
"log/slog"
"time"
"github.com/labstack/echo/v4"
"github.com/redis/go-redis/v9"
2025-07-17 16:45:27 +08:00
"github.com/chaitin/MonkeyCode/backend/consts"
2025-07-04 10:56:03 +08:00
)
type ActiveMiddleware struct {
redis *redis.Client
logger *slog.Logger
}
func NewActiveMiddleware(redis *redis.Client, logger *slog.Logger) *ActiveMiddleware {
return &ActiveMiddleware{
redis: redis,
logger: logger,
}
}
2025-07-17 16:45:27 +08:00
func (a *ActiveMiddleware) Active(scope string) echo.MiddlewareFunc {
2025-07-04 10:56:03 +08:00
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
2025-07-17 16:45:27 +08:00
switch scope {
case "admin":
2025-07-21 12:24:00 +08:00
if user := GetAdmin(c); user != nil {
2025-07-17 16:45:27 +08:00
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":
2025-07-21 15:04:03 +08:00
if user := GetUser((c)); user != nil {
if err := a.redis.Set(context.Background(), fmt.Sprintf(consts.UserActiveKeyFmt, user.ID), time.Now().Unix(), 0).Err(); err != nil {
a.logger.With("error", err).ErrorContext(c.Request().Context(), "failed to set user active status in Redis")
}
}
case "apikey":
2025-07-17 16:45:27 +08:00
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")
}
2025-07-04 10:56:03 +08:00
}
}
2025-07-17 16:45:27 +08:00
2025-07-04 10:56:03 +08:00
return next(c)
}
}
}