Files
slogan/server/common/auth_middleware.go
admin fc56b47406 server: web 静态托管完善 + 联调脚本 + 清理过期工具
- main.go/auth_middleware: web 静态目录托管与 history 回退、Chrome DevTools 探测处理
- 新增 scripts/build_web.sh(缓存判断构建 web)与 scripts/dev.sh(一键构建+启动)
- 删除已过时的 routes.sh(goframe 自动生成 api.json)与 split_db(数据库已拆分完毕)
- docs: 补充联调与测试规范(测试必须用真实用户数据 wenwu901/123456)
2026-08-04 17:15:37 +08:00

98 lines
1.8 KiB
Go
Raw Permalink 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 common
import (
"net/http"
"strings"
"github.com/gogf/gf/v2/net/ghttp"
)
var publicPaths = []string{
"/user/login",
"/user/register",
"/hairstyle/list",
"/api.json",
"/member/order/notify",
}
func Auth(r *ghttp.Request) {
path := r.URL.Path
// 公开路径(精确匹配)
for _, p := range publicPaths {
if path == p {
r.Middleware.Next()
return
}
}
// workspace 文件通过前缀匹配放行(浏览器图片请求不带 Authorization
if strings.HasPrefix(path, "/workspace/") {
r.Middleware.Next()
return
}
// web 静态资源与前端 history 路由放行(浏览器加载页面不带 Authorization
if IsWebAsset(path) || IsWebHistoryRoute(path) {
r.Middleware.Next()
return
}
auth := r.Header.Get("Authorization")
if auth == "" || !strings.HasPrefix(auth, "Bearer ") {
r.Response.WriteJson(ghttp.DefaultHandlerResponse{
Code: http.StatusUnauthorized,
Message: "未登录或登录已过期",
})
r.Exit()
return
}
claims, err := ParseToken(auth[7:])
if err != nil {
r.Response.WriteJson(ghttp.DefaultHandlerResponse{
Code: http.StatusUnauthorized,
Message: "登录已过期,请重新登录",
})
r.Exit()
return
}
r.SetCtxVar("userId", claims.UserId)
r.SetCtxVar("role", claims.Role)
r.SetCtxVar("agentId", claims.AgentId)
r.Middleware.Next()
}
func GetUserId(r *ghttp.Request) int64 {
v := r.GetCtxVar("userId")
if v == nil {
return 0
}
return v.Int64()
}
func GetRole(r *ghttp.Request) string {
v := r.GetCtxVar("role")
if v == nil {
return ""
}
return v.String()
}
func GetAgentId(r *ghttp.Request) int64 {
v := r.GetCtxVar("agentId")
if v == nil {
return 0
}
return v.Int64()
}
func CheckAdmin(r *ghttp.Request) bool {
return GetRole(r) == "admin"
}
func CheckAgent(r *ghttp.Request) bool {
return GetRole(r) == "agent"
}