Files
cpdaily_xiaozhushou/backed/internal/middleware/jwt.go
T
becomer 2e2c161770 feat: init cpdaily-xiaozhushou with blue-green deploy
- backed/: Go Fiber backend with cpdaily integration
- frondend/: Vue 3 + Vite frontend
- Dockerfile: multi-stage build (Node → Go → Alpine)
- deploy/docker-compose.yml: production compose file
- .woodpecker/build.yml: CI/CD with blue-green zero-downtime deploy
- /health endpoint for deployment health checks
- Port 8884/8885 blue-green swap via 1Panel OpenResty
2026-07-03 15:37:55 +08:00

57 lines
1.3 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package middleware
import (
"cpdaily-new/internal/service"
"cpdaily-new/internal/utils"
"strings"
"github.com/gofiber/fiber/v2"
)
func AuthRequired() fiber.Handler {
return func(c *fiber.Ctx) error {
tokenStr := ""
// 优先从 Authorization header 取
authHeader := c.Get("Authorization")
if authHeader != "" {
parts := strings.SplitN(authHeader, " ", 2)
if len(parts) == 2 && parts[0] == "Bearer" {
tokenStr = parts[1]
}
}
// 降级:从 query param ?token= 取(用于 SSE EventSource)
if tokenStr == "" {
tokenStr = c.Query("token")
}
if tokenStr == "" {
return utils.FailAuth(c, "缺少认证信息")
}
claims, err := service.ValidateToken(tokenStr)
if err != nil {
return utils.FailAuth(c, "token无效或已过期")
}
// 将用户信息存入 context
c.Locals("userId", claims.UserID)
c.Locals("username", claims.Username)
c.Locals("schoolId", claims.SchoolID)
return c.Next()
}
}
func CORS() fiber.Handler {
return func(c *fiber.Ctx) error {
c.Set("Access-Control-Allow-Origin", "*")
c.Set("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS")
c.Set("Access-Control-Allow-Headers", "Content-Type,Authorization")
c.Set("Access-Control-Allow-Credentials", "true")
if c.Method() == "OPTIONS" {
return c.SendStatus(204)
}
return c.Next()
}
}