first commit

This commit is contained in:
2025-08-16 18:46:29 +08:00
commit 5f008b3228
511 changed files with 53667 additions and 0 deletions

View File

@@ -0,0 +1,54 @@
package middleware
import (
"context"
"net/http"
"znc-server/app/main/api/internal/config"
jwtx "znc-server/common/jwt"
"znc-server/common/xerr"
"github.com/pkg/errors"
"github.com/zeromicro/go-zero/rest/httpx"
)
const (
// 定义错误码
ErrCodeUnauthorized = 401
)
type AuthInterceptorMiddleware struct {
Config config.Config
}
func NewAuthInterceptorMiddleware(c config.Config) *AuthInterceptorMiddleware {
return &AuthInterceptorMiddleware{
Config: c,
}
}
func (m *AuthInterceptorMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// 从请求头中获取Authorization字段
authHeader := r.Header.Get("Authorization")
// 如果没有Authorization头直接放行
if authHeader == "" {
next(w, r)
return
}
// 解析JWT令牌
claims, err := jwtx.ParseJwtToken(authHeader, m.Config.JwtAuth.AccessSecret)
if err != nil {
// JWT解析失败返回401错误
httpx.Error(w, errors.Wrapf(xerr.NewErrCode(ErrCodeUnauthorized), "token解析失败: %v", err))
return
}
ctx := context.WithValue(r.Context(), jwtx.ExtraKey, claims)
// 使用新的上下文继续处理请求
next(w, r.WithContext(ctx))
}
}

View File

@@ -0,0 +1,29 @@
package middleware
import (
"context"
"net/http"
)
const (
PlatformKey = "X-Platform"
)
func GlobalSourceInterceptor(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// 获取请求头 X-Platform 的值
platform := r.Header.Get(PlatformKey)
// 将值放入新的 context 中
ctx := r.Context()
if platform != "" {
ctx = context.WithValue(ctx, "platform", platform)
}
// 通过 r.WithContext 将更新后的 ctx 传递给后续的处理函数
r = r.WithContext(ctx)
// 传递给下一个处理器
next(w, r)
}
}

View File

@@ -0,0 +1,33 @@
package middleware
import (
"net/http"
"znc-server/app/main/model"
"znc-server/common/ctxdata"
"znc-server/common/xerr"
"github.com/pkg/errors"
"github.com/zeromicro/go-zero/rest/httpx"
)
type UserAuthInterceptorMiddleware struct {
}
func NewUserAuthInterceptorMiddleware() *UserAuthInterceptorMiddleware {
return &UserAuthInterceptorMiddleware{}
}
func (m *UserAuthInterceptorMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
claims, err := ctxdata.GetClaimsFromCtx(r.Context())
if err != nil {
httpx.Error(w, errors.Wrapf(xerr.NewErrCode(ErrCodeUnauthorized), "token解析失败: %v", err))
return
}
if claims.UserType == model.UserTypeTemp {
httpx.Error(w, errors.Wrapf(xerr.NewErrCode(xerr.USER_NEED_BIND_MOBILE), "token解析失败: %v", err))
return
}
next(w, r)
}
}