96 lines
2.0 KiB
Go
96 lines
2.0 KiB
Go
package common
|
||
|
||
import (
|
||
"net/http"
|
||
"strings"
|
||
|
||
"github.com/gogf/gf/v2/net/ghttp"
|
||
)
|
||
|
||
var publicPaths = []string{
|
||
"/user/login",
|
||
}
|
||
|
||
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
|
||
}
|
||
|
||
// 前端静态资源放行(合并部署后 UI 由后端服务,浏览器请求不带 Authorization):
|
||
// 仅放行 /(入口页)与 /assets/*(构建产物),hash 路由下 SPA 页面只会请求这两个路径;
|
||
// 其余路径(包括与 SPA 页面同名的 /drama、/customer 等)一律走 API 鉴权,无鉴权绕过
|
||
if r.Method == http.MethodGet && (path == "/" || strings.HasPrefix(path, "/assets/")) {
|
||
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"
|
||
}
|