fusenapi/utils/auth/auth.go

72 lines
1.6 KiB
Go
Raw Normal View History

2023-06-01 10:34:41 +00:00
package auth
import (
"encoding/json"
"github.com/golang-jwt/jwt"
2023-06-02 04:15:32 +00:00
"github.com/zeromicro/go-zero/core/logx"
2023-06-01 10:34:41 +00:00
"net/http"
"time"
)
type UserInfo struct {
2023-06-02 04:12:51 +00:00
UserId int64 `json:"user_id"` //网站前台登录uid
BackendUserId int64 `json:"backend_user_id"` //管理后台uid
2023-06-01 10:34:41 +00:00
}
// 签名key
var signKey = "FushenFGbhgfhgKgGH556HGlXrsfJKhhjYFGKLO=="
var expireTime = int64(3600)
// 生成token
func GenJwtToken(userInfo UserInfo) (token string, err error) {
t := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
2023-06-02 04:12:51 +00:00
"user_id": userInfo.UserId,
"backend_user_id": userInfo.BackendUserId,
"exp": time.Now().Add(time.Second * time.Duration(expireTime)).Unix(), //过期时间
"iss": "fusen",
2023-06-01 10:34:41 +00:00
})
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
}
// 检测授权
2023-06-02 04:12:51 +00:00
func CheckAuth(r *http.Request) UserInfo {
2023-06-01 10:34:41 +00:00
token := r.Header.Get("Authorization")
if token == "" {
2023-06-02 04:12:51 +00:00
token = r.Header.Get("Auth-Key")
}
if token == "" {
2023-06-02 11:24:58 +00:00
logx.Error("token is empty")
2023-06-02 04:12:51 +00:00
return UserInfo{}
2023-06-01 10:34:41 +00:00
}
//解析token
userInfo, err := ParseJwtToken(token)
if err != nil {
2023-06-02 11:24:58 +00:00
logx.Error(err)
2023-06-02 04:12:51 +00:00
return UserInfo{}
2023-06-01 10:34:41 +00:00
}
2023-06-02 04:12:51 +00:00
return userInfo
2023-06-01 10:34:41 +00:00
}