first commit
This commit is contained in:
@@ -0,0 +1,54 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"github.com/zeromicro/go-zero/core/logx"
|
||||
xhttp "github.com/zeromicro/x/http"
|
||||
"tianyuan-api/apps/gateway/internal/config"
|
||||
jwtx "tianyuan-api/pkg/jwt"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
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) {
|
||||
// 从 Cookie 中获取 JWT
|
||||
cookie, err := r.Cookie("Authorization")
|
||||
if err != nil {
|
||||
xhttp.JsonBaseResponseCtx(r.Context(), w, errors.New("用户未登录"))
|
||||
return
|
||||
}
|
||||
|
||||
tokenStr := cookie.Value
|
||||
// 验证并解析 JWT
|
||||
userId, err := jwtx.ParseJwtToken(tokenStr, m.Config.AuthJWT.AccessSecret)
|
||||
if err != nil {
|
||||
// 设置过期的 Cookie 来删除无效的 Token
|
||||
http.SetCookie(w, &http.Cookie{
|
||||
Name: "Authorization",
|
||||
Value: "",
|
||||
Path: "/",
|
||||
HttpOnly: true,
|
||||
Expires: time.Unix(0, 0), // 过期时间设置为过去
|
||||
})
|
||||
logx.Error("Invalid JWT: ", err)
|
||||
xhttp.JsonBaseResponseCtx(r.Context(), w, errors.New("未经授权的访问"))
|
||||
return
|
||||
}
|
||||
|
||||
// 将 userId 存入 context,供后续逻辑使用
|
||||
ctx := context.WithValue(r.Context(), "userId", userId)
|
||||
next(w, r.WithContext(ctx))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"github.com/zeromicro/go-zero/core/logx"
|
||||
xhttp "github.com/zeromicro/x/http"
|
||||
"tianyuan-api/apps/user/user"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type EntAuthInterceptorMiddleware struct {
|
||||
UserRpc user.UserClient
|
||||
}
|
||||
|
||||
func NewEntAuthInterceptorMiddleware(userRpc user.UserClient) *EntAuthInterceptorMiddleware {
|
||||
return &EntAuthInterceptorMiddleware{
|
||||
UserRpc: userRpc,
|
||||
}
|
||||
}
|
||||
|
||||
func (m *EntAuthInterceptorMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
userId, ok := r.Context().Value("userId").(int64)
|
||||
if !ok {
|
||||
xhttp.JsonBaseResponseCtx(r.Context(), w, errors.New("无法获取 userId"))
|
||||
}
|
||||
status, err := m.UserRpc.GetEnterpriseAuthStatus(r.Context(), &user.GetEnterpriseAuthStatusReq{UserId: userId})
|
||||
if err != nil {
|
||||
logx.Error("校验认证状态错误: %v", err)
|
||||
xhttp.JsonBaseResponseCtx(r.Context(), w, errors.New("系统错误"))
|
||||
return
|
||||
}
|
||||
if !status.IsAuth {
|
||||
xhttp.JsonBaseResponseCtx(r.Context(), w, errors.New("请先通过企业认证"))
|
||||
return
|
||||
}
|
||||
next(w, r)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user