fusenapi/utils/auth/auth.go
laodaming 92b29d8006 fix
2023-06-02 19:24:58 +08:00

72 lines
1.6 KiB
Go

package auth
import (
"encoding/json"
"github.com/golang-jwt/jwt"
"github.com/zeromicro/go-zero/core/logx"
"net/http"
"time"
)
type UserInfo struct {
UserId int64 `json:"user_id"` //网站前台登录uid
BackendUserId int64 `json:"backend_user_id"` //管理后台uid
}
// 签名key
var signKey = "FushenFGbhgfhgKgGH556HGlXrsfJKhhjYFGKLO=="
var expireTime = int64(3600)
// 生成token
func GenJwtToken(userInfo UserInfo) (token string, err error) {
t := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"user_id": userInfo.UserId,
"backend_user_id": userInfo.BackendUserId,
"exp": time.Now().Add(time.Second * time.Duration(expireTime)).Unix(), //过期时间
"iss": "fusen",
})
token, err = t.SignedString([]byte(signKey))
if err != nil {
return "", err
}
return
}
// 解释token
func ParseJwtToken(token string) (UserInfo, error) {
t, err := jwt.ParseWithClaims(token, jwt.MapClaims{}, func(token *jwt.Token) (interface{}, error) {
return []byte(signKey), nil
})
if err != nil {
return UserInfo{}, err
}
d, err := json.Marshal(t.Claims)
if err != nil {
return UserInfo{}, err
}
var userInfo UserInfo
if err = json.Unmarshal(d, &userInfo); err != nil {
return UserInfo{}, err
}
return userInfo, nil
}
// 检测授权
func CheckAuth(r *http.Request) UserInfo {
token := r.Header.Get("Authorization")
if token == "" {
token = r.Header.Get("Auth-Key")
}
if token == "" {
logx.Error("token is empty")
return UserInfo{}
}
//解析token
userInfo, err := ParseJwtToken(token)
if err != nil {
logx.Error(err)
return UserInfo{}
}
return userInfo
}