fusenapi/utils/auth/user.go
2023-06-12 15:17:42 +08:00

54 lines
1.3 KiB
Go

package auth
import (
"context"
"encoding/json"
"errors"
"fmt"
"github.com/golang-jwt/jwt"
"github.com/zeromicro/go-zero/core/logx"
)
type UserInfo struct {
UserId int64 `json:"userid"`
}
// 获取登录信息
func GetUserInfoFormCtx(ctx context.Context) UserInfo {
uid, err := ctx.Value("userid").(json.Number).Int64()
if err != nil {
logx.Error("parse uid form context err:", err.Error())
return UserInfo{}
}
return UserInfo{UserId: uid}
}
// 获取登录信息
func GetUserInfoFormMapClaims(claims jwt.MapClaims) (*UserInfo, error) {
if userid, ok := claims["userid"]; ok {
uid, ok := userid.(float64)
if !ok {
err := errors.New(fmt.Sprint("parse uid form context err:", userid))
logx.Error("parse uid form context err:", err)
return nil, err
}
return &UserInfo{UserId: int64(uid)}, nil
} else {
err := errors.New(`userid not in claims`)
logx.Error(`userid not in claims`)
return nil, err
}
}
func GenerateJwtToken(accessSecret string, accessExpire, nowSec int64, userid int) (string, error) {
claims := make(jwt.MapClaims)
claims["exp"] = nowSec + accessExpire
claims["iat"] = nowSec
claims["userid"] = userid
token := jwt.New(jwt.SigningMethodHS256)
token.Claims = claims
return token.SignedString([]byte(accessSecret))
}