You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
65 lines
1.5 KiB
65 lines
1.5 KiB
package service
|
|
|
|
import (
|
|
"fmt"
|
|
"gf_demo_02/internal/consts"
|
|
"gf_demo_02/internal/model"
|
|
"strings"
|
|
|
|
"github.com/gogf/gf/v2/frame/g"
|
|
"github.com/gogf/gf/v2/net/ghttp"
|
|
"github.com/golang-jwt/jwt/v5"
|
|
)
|
|
|
|
func JWTMiddleware(r *ghttp.Request) {
|
|
url := r.GetUrl()
|
|
if strings.HasSuffix(url, "/login") || strings.HasSuffix(url, "/loginPage") {
|
|
r.Middleware.Next()
|
|
return
|
|
}
|
|
tokenStr := r.Header.Get("Authorization")
|
|
tokenStr = strings.TrimSpace(tokenStr)
|
|
tokenStr = strings.TrimPrefix(tokenStr, "Bearer ")
|
|
if g.IsEmpty(tokenStr) {
|
|
r.Response.WriteStatus(401, "no token")
|
|
return
|
|
}
|
|
token, err := jwt.ParseWithClaims(tokenStr, &model.UserClaim{}, func(token *jwt.Token) (interface{}, error) {
|
|
_, ok := token.Method.(*jwt.SigningMethodHMAC)
|
|
if !ok {
|
|
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
|
|
}
|
|
return []byte(consts.TOKEN_KEY), nil
|
|
})
|
|
if err != nil {
|
|
r.Response.WriteStatus(401, "token invalid")
|
|
return
|
|
}
|
|
claim, ok := token.Claims.(*model.UserClaim)
|
|
if !ok || !token.Valid {
|
|
r.Response.WriteStatus(401, "token invalid")
|
|
return
|
|
}
|
|
id := claim.UserId
|
|
name := claim.UserName
|
|
cond := g.Map{
|
|
"id": id,
|
|
"name": name,
|
|
}
|
|
user, err := User().GetUser(cond)
|
|
if err != nil || user == nil {
|
|
r.Response.WriteStatus(401, "token invalid")
|
|
return
|
|
}
|
|
if user.Id != id || user.Name != name {
|
|
r.Response.WriteStatus(401, "token invalid")
|
|
return
|
|
}
|
|
r.SetCtxVar("user", user)
|
|
r.Middleware.Next()
|
|
}
|
|
|
|
func CorsMiddleware(r *ghttp.Request) {
|
|
r.Response.CORSDefault()
|
|
r.Middleware.Next()
|
|
}
|