Files
common/middleware/middleware.go
2026-03-12 08:51:25 +08:00

84 lines
2.1 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 (
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/net/ghttp"
"github.com/gogf/gf/v2/os/gtime"
"github.com/gogf/gf/v2/text/gstr"
)
// Logger 中间件
func Logger(r *ghttp.Request) {
startTime := gtime.TimestampMilli()
r.Middleware.Next()
endTime := gtime.TimestampMilli()
g.Log().Infof(r.GetCtx(),
"request: %s %s | status: %d | time: %dms",
r.Method,
r.URL.Path,
r.Response.Status,
endTime-startTime,
)
}
func Auth(r *ghttp.Request) {
//utils.GetUserInfo(r.GetCtx())
token := r.Header.Get("Authorization")
if token == "" || !gstr.HasPrefix(token, "Bearer ") {
r.Response.WriteStatusExit(401, "Unauthorized")
return
}
// 验证 token
// TODO: 实现完整的JWT验证逻辑
// 当前为占位实现实际使用时应替换为真实的token验证
// 例如使用gogf/gf/v2/os/gjwt或其他JWT库进行验证
if !validateToken(gstr.SubStrFrom(token, "7")) {
r.Response.WriteStatusExit(401, "Unauthorized")
return
}
r.Middleware.Next()
}
// validateToken 验证Token有效性
// 当前为简化实现实际生产环境应使用JWT或其他安全机制进行验证
// 示例:
// - 使用gogf/gf/v2/os/gjwt库解析和验证JWT token
// - 验证token签名、过期时间、签发者等
// - 从token中提取用户信息并存储到context
//
// 返回值:
// - true: token有效
// - false: token无效或过期
func validateToken(token string) bool {
// TODO: 实现真实的token验证逻辑
// 当前为占位实现返回true以允许基本功能运行
// 生产环境必须替换为真实的验证逻辑
// 简单的非空检查
if token == "" {
return false
}
// 建议的JWT验证示例需要引入jwt库:
/*
claims := &jwt.MapClaims{}
t, err := jwt.ParseWithClaims(token, claims, func(token *jwt.Token) (interface{}, error) {
return []byte("your-secret-key"), nil
})
if err != nil || !t.Valid {
return false
}
// 检查过期时间
if exp, ok := (*claims)["exp"].(float64); ok {
if time.Now().Unix() > int64(exp) {
return false
}
}
*/
// 临时返回true实际使用时应实现完整验证
return true
}