Files
yunzerwebsiteallinone/go/middleware/jwt.go
T
2026-11-16 17:22:50 +08:00

180 lines
3.9 KiB
Go

package middleware
import (
"log"
"net/http"
"strings"
"sync"
"server/pkg/jwtutil"
beego "github.com/beego/beego/v2/server/web"
"github.com/beego/beego/v2/server/web/context"
)
const (
AuthModeOff = "off"
AuthModeWarn = "warn"
AuthModeOn = "on"
)
var protectedPrefixes = []string{
"/backend/", "/platform/",
"/api/oa/", "/api/notebook/", "/api/schedule", "/api/currentUser",
"/api/activity/", "/api/home", "/api/quick-menus", "/api/changePassword",
}
var authWhitelist = []string{
"/auth/",
"/backend/login",
"/backend/sendLoginCode",
"/backend/register",
"/backend/sendRegisterCode",
"/backend/resetPassword",
"/backend/sendResetCode",
"/backend/verifyAccount",
"/backend/logout",
"/platform/login",
"/platform/sendLoginCode",
"/platform/register",
"/platform/sendRegisterCode",
"/platform/resetPassword",
"/platform/logout",
"/api/login",
"/api/sendLoginCode",
"/api/register",
"/api/sendRegisterCode",
"/api/resetPassword",
"/api/sendResetCode",
"/api/verifyAccount",
"/api/logout",
"/api/schedule/reminder/ack",
}
var (
modeOnce sync.Once
modeVal = AuthModeWarn
warnSeen sync.Map
)
func authMode() string {
modeOnce.Do(func() {
if v, err := beego.AppConfig.String("auth_enforce"); err == nil {
switch strings.ToLower(strings.TrimSpace(v)) {
case AuthModeOff, AuthModeWarn, AuthModeOn:
modeVal = strings.ToLower(strings.TrimSpace(v))
}
}
if extra, err := beego.AppConfig.String("auth_whitelist"); err == nil && strings.TrimSpace(extra) != "" {
for _, p := range strings.Split(extra, ",") {
if p = strings.TrimSpace(p); p != "" {
authWhitelist = append(authWhitelist, p)
}
}
}
log.Printf("[auth] JWT 全局鉴权模式=%s,受保护前缀=%v", modeVal, protectedPrefixes)
})
return modeVal
}
func cleanPath(uri string) string {
if i := strings.IndexAny(uri, "?#"); i >= 0 {
return uri[:i]
}
return uri
}
func isProtected(path string) bool {
for _, p := range protectedPrefixes {
if strings.HasPrefix(path, p) {
return true
}
}
return false
}
func isWhitelisted(path string) bool {
for _, p := range authWhitelist {
if strings.HasPrefix(path, p) {
return true
}
}
return false
}
func warnLog(path, reason string) {
if _, loaded := warnSeen.LoadOrStore(path, struct{}{}); loaded {
return
}
log.Printf("[auth][warn] 该接口在 enforce=on 时会被拦截: %s (%s)", path, reason)
}
func JWTAuthMiddleware() beego.FilterFunc {
return func(ctx *context.Context) {
mode := authMode()
if mode == AuthModeOff {
return
}
if ctx.Input.Method() == http.MethodOptions {
return
}
path := cleanPath(ctx.Request.RequestURI)
if !isProtected(path) || isWhitelisted(path) {
return
}
reject := func(status int, message string) {
if mode == AuthModeWarn {
warnLog(path, message)
return
}
ctx.Output.SetStatus(status)
ctx.Output.JSON(map[string]interface{}{
"success": false,
"message": message,
}, false, false)
}
authHeader := ctx.Request.Header.Get("Authorization")
if authHeader == "" {
reject(401, "未提供认证信息")
return
}
authParts := strings.SplitN(authHeader, " ", 2)
if !(len(authParts) == 2 && authParts[0] == "Bearer") {
reject(401, "认证信息格式错误")
return
}
claims, err := jwtutil.ParseToken(authParts[1])
if err != nil {
message := "无效的token"
if strings.Contains(err.Error(), "expired") {
message = "token已过期"
}
reject(401, message)
return
}
ctx.Input.SetData("userId", claims.UserID)
ctx.Input.SetData("username", claims.Username)
ctx.Input.SetData("tenantId", claims.TenantId)
ctx.Input.SetData("uid", uint64(claims.UserID))
ctx.Input.SetData("tid", uint64(claims.TenantId))
userType := claims.UserType
if userType == "" {
userType = "user"
}
ctx.Input.SetData("userType", userType)
ctx.Input.SetData("clientId", claims.ClientID)
ctx.Input.SetData("sid", claims.Sid)
}
}