This commit is contained in:
oneao committed 2026-02-26 17:31:08 +08:00
1 parent 4ce951dd56
commit 8a3dea8545
44 files changed
+1599 -30

No files matched your search

@@ -0,0 +1,47 @@
package middleware
import (
"allapp/utils/jwtx"
"allapp/utils/responsex"
"strings"
"github.com/gofiber/fiber/v3"
)
const CtxUserIDKey = "user_id"
// Auth 登录校验中间件
func Auth() fiber.Handler {
return func(c fiber.Ctx) error {
token := strings.TrimSpace(c.Get("Token"))
if token == "" {
return responsex.Unauthorized(c, "未登录")
}
verifyToken, ok := jwtx.VerifyToken(c.Context(), token)
if !ok {
return responsex.Unauthorized(c, "登录已过期")
}
c.Locals(CtxUserIDKey, verifyToken.UserID)
return c.Next()
}
}
func GetUserID(c fiber.Ctx) (int64, error) {
v := c.Locals(CtxUserIDKey)
if v == nil {
return 0, responsex.Unauthorized(c, "登录已过期")
}
userID, ok := v.(int64)
if !ok {
return 0, responsex.Unauthorized(c, "登录已过期")
}
return userID, nil
}
@@ -0,0 +1,33 @@
package middleware
import (
"context"
"time"
"github.com/gofiber/fiber/v3"
"github.com/gofiber/fiber/v3/log"
)
func Logger() fiber.Handler {
return func(c fiber.Ctx) error {
ctx := context.WithValue(c.Context(), "request_id", c.RequestID())
c.SetContext(ctx)
start := time.Now()
err := c.Next()
duration := time.Since(start)
// 记录日志
log.Infow("API Request",
"method", c.Method(),
"path", c.Path(),
"status", c.Response().StatusCode(),
"duration", duration.String(),
"ip", c.IP(),
)
return err
}
}
@@ -0,0 +1,62 @@
package middleware
import (
"allapp/db"
"allapp/db/repo"
"allapp/utils/errorx"
"allapp/utils/redisx"
"allapp/utils/responsex"
"strconv"
"strings"
"github.com/gofiber/fiber/v3"
)
const CtxSpaceIDKey = "space_id"
func SpaceGuard() fiber.Handler {
return func(c fiber.Ctx) error {
userID, err := GetUserID(c)
if err != nil {
return err
}
spaceIDStr := strings.TrimSpace(c.Get("SPACE_ID"))
spaceID, err := strconv.ParseInt(spaceIDStr, 10, 64)
if err != nil || spaceID <= 0 {
return responsex.SpaceError(c, "请选择空间")
}
// 校验
inSpace, err := redisx.SpaceIsMember(spaceID, userID)
if inSpace {
return c.Next()
}
// 检验空间是否存在
space, err := db.Queries.GetSpaceById(c.Context(), spaceID)
if err != nil {
if errorx.IsNotFound(err) {
// 未找到
return responsex.SpaceError(c, "空间已失效")
}
return err
}
// 空间有效,判断是否在该空间内
role, err := db.Queries.GetUserSpaceRole(c.Context(), repo.GetUserSpaceRoleParams{
SpaceID: spaceID,
UserID: spaceID,
})
if err != nil {
if errorx.IsNotFound(err) {
}
}
}
}
+10 -2
View File
@@ -1,7 +1,7 @@
package router
import (
"allapp/api/handler"
"allapp/api/handler/auth"
"allapp/config"
"github.com/gofiber/fiber/v3"
@@ -10,5 +10,13 @@ import (
func SetupRouters(app *fiber.App) {
api := app.Group(config.GetConf().Server.BaseUrl)
api.Get("/", handler.Hello)
public := api.Group("")
//private := api.Group("", middleware.Auth())
// auth
authRouter := public.Group("/auth")
authRouter.Post("/login/qq", auth.LoginQq)
authRouter.Post("/login/wechat", auth.LoginWechat)
// 其他的都带中间件
}