🎉初步完成用户
This commit is contained in:
55
component/captcha.go
Normal file
55
component/captcha.go
Normal file
@@ -0,0 +1,55 @@
|
||||
package component
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"website-nav/global/client"
|
||||
"website-nav/global/constant"
|
||||
)
|
||||
|
||||
type Captcha struct{}
|
||||
|
||||
// Set
|
||||
// @description: 验证码放入指定存储
|
||||
// @receiver Captcha
|
||||
// @param id
|
||||
// @param value
|
||||
// @return error
|
||||
func (Captcha) Set(id string, value string) error {
|
||||
return client.Cache.Set([]byte(fmt.Sprintf("%s:%s", constant.Captcha, id)), []byte(value), 2*60)
|
||||
}
|
||||
|
||||
// Get
|
||||
// @description: 获取验证码信息
|
||||
// @receiver Captcha
|
||||
// @param id
|
||||
// @param clear
|
||||
// @return string
|
||||
func (Captcha) Get(id string, clear bool) string {
|
||||
val, err := client.Cache.Get([]byte(fmt.Sprintf("%s:%s", constant.Captcha, id)))
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
|
||||
if clear {
|
||||
client.Cache.Del([]byte(fmt.Sprintf("%s:%s", constant.Captcha, id)))
|
||||
return string(val)
|
||||
}
|
||||
|
||||
return string(val)
|
||||
}
|
||||
|
||||
// Verify
|
||||
// @description: 校验
|
||||
// @receiver Captcha
|
||||
// @param id
|
||||
// @param answer
|
||||
// @param clear
|
||||
// @return bool
|
||||
func (c Captcha) Verify(id, answer string, clear bool) bool {
|
||||
if os.Getenv("GIN_MODE") != "release" {
|
||||
return true
|
||||
}
|
||||
return strings.ToUpper(answer) == strings.ToUpper(c.Get(id, clear))
|
||||
}
|
135
component/jwt.go
Normal file
135
component/jwt.go
Normal file
@@ -0,0 +1,135 @@
|
||||
package component
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"gitee.ltd/lxh/logger/log"
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
"github.com/google/uuid"
|
||||
"math/rand"
|
||||
"strings"
|
||||
"time"
|
||||
"website-nav/config"
|
||||
"website-nav/global/client"
|
||||
"website-nav/global/constant"
|
||||
"website-nav/utils"
|
||||
)
|
||||
|
||||
type JwtComponent struct {
|
||||
ID string `json:"id"`
|
||||
jwt.RegisteredClaims
|
||||
}
|
||||
|
||||
// JWT
|
||||
// @description: 初始化JWT组件
|
||||
// @return JwtComponent
|
||||
func JWT() JwtComponent {
|
||||
return JwtComponent{}
|
||||
}
|
||||
|
||||
// GenerateToken
|
||||
// @description: 生成token
|
||||
// @receiver JwtComponent
|
||||
// @param userId
|
||||
// @param password
|
||||
// @return token
|
||||
// @return expireTime
|
||||
// @return err
|
||||
func (JwtComponent) GenerateToken(userId, secret string, times ...time.Time) (token string, expireTime *jwt.NumericDate, err error) {
|
||||
var notBefore, issuedAt *jwt.NumericDate
|
||||
if len(times) != 0 {
|
||||
expireTime = jwt.NewNumericDate(times[0])
|
||||
notBefore = jwt.NewNumericDate(times[1])
|
||||
issuedAt = jwt.NewNumericDate(times[1])
|
||||
} else {
|
||||
timeNow := time.Now().Local()
|
||||
expireTime = jwt.NewNumericDate(timeNow.Add(7 * time.Hour))
|
||||
notBefore = jwt.NewNumericDate(timeNow)
|
||||
issuedAt = jwt.NewNumericDate(timeNow)
|
||||
}
|
||||
|
||||
claims := JwtComponent{
|
||||
ID: userId,
|
||||
RegisteredClaims: jwt.RegisteredClaims{
|
||||
Issuer: config.GlobalConfig.Http.Endpoint, // 颁发站点
|
||||
Subject: "you can you up,no can no bb", // 发布主题
|
||||
ExpiresAt: expireTime, // 过期时间
|
||||
NotBefore: notBefore, // token不得早于该时间
|
||||
IssuedAt: issuedAt, // token颁发时间
|
||||
ID: strings.ReplaceAll(uuid.NewString(), "-", ""), // 该token的id
|
||||
},
|
||||
}
|
||||
|
||||
t := jwt.NewWithClaims(jwt.SigningMethodHS512, claims)
|
||||
token, err = t.SignedString([]byte(secret))
|
||||
if err != nil {
|
||||
log.Errorf("生成token失败: %v", err.Error())
|
||||
return "", nil, errors.New("生成token失败")
|
||||
}
|
||||
|
||||
_ = client.Cache.Set([]byte(fmt.Sprintf("%s:%s", constant.UserToken, userId)),
|
||||
[]byte(token),
|
||||
int(expireTime.Sub(time.Now()).Abs().Seconds()))
|
||||
return
|
||||
}
|
||||
|
||||
// ParseToken
|
||||
// @description: 解析token
|
||||
// @receiver JwtComponent
|
||||
// @param token
|
||||
// @return *JwtComponent
|
||||
// @return error
|
||||
func (JwtComponent) ParseToken(token, secret string) (*JwtComponent, error) {
|
||||
tokenStr := strings.Split(token, "Bearer ")[1]
|
||||
|
||||
t, err := jwt.ParseWithClaims(tokenStr, &JwtComponent{}, func(token *jwt.Token) (any, error) {
|
||||
return []byte(secret), nil
|
||||
})
|
||||
|
||||
if claims, ok := t.Claims.(*JwtComponent); ok && t.Valid {
|
||||
userToken, err := client.Cache.Get([]byte(fmt.Sprintf("%s:%s", constant.UserToken, claims.ID)))
|
||||
if err != nil {
|
||||
log.Errorf("缓存中用户[%s]的token查找失败: %v", claims.ID, err.Error())
|
||||
return nil, errors.New("token不存在")
|
||||
}
|
||||
|
||||
if string(userToken) != tokenStr {
|
||||
log.Errorf("token不一致")
|
||||
return nil, errors.New("token错误")
|
||||
}
|
||||
|
||||
return claims, nil
|
||||
} else {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
// GenerateSecret
|
||||
// @description: 生成token解析密钥【每个用户的secret不一样,提高安全性】
|
||||
// @receiver JwtComponent
|
||||
// @param secret
|
||||
// @return string
|
||||
func (JwtComponent) GenerateSecret(secret ...string) string {
|
||||
// 添加10个元素,增加随机性
|
||||
for i := 0; i <= 10; i++ {
|
||||
secret = append(secret, uuid.NewString())
|
||||
}
|
||||
// 混淆一下明文secret的顺序
|
||||
n := len(secret)
|
||||
for i := n - 1; i > 0; i-- {
|
||||
j := rand.Intn(i + 1)
|
||||
secret[i], secret[j] = secret[j], secret[i]
|
||||
}
|
||||
secretStr := strings.Join(secret, ".")
|
||||
return utils.Hash().MD5(utils.Hash().SHA256(utils.Hash().SHA512(secretStr)))
|
||||
}
|
||||
|
||||
// Logout
|
||||
// @description: 退出登陆
|
||||
// @receiver JwtComponent
|
||||
// @param userId
|
||||
// @return error
|
||||
func (JwtComponent) Logout(userId string) error {
|
||||
_ = client.Cache.Del([]byte(fmt.Sprintf("%s:%s", constant.UserToken, userId)))
|
||||
return nil
|
||||
}
|
97
component/validator.go
Normal file
97
component/validator.go
Normal file
@@ -0,0 +1,97 @@
|
||||
package component
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"gitee.ltd/lxh/logger/log"
|
||||
"github.com/gin-gonic/gin/binding"
|
||||
"github.com/go-playground/locales/en"
|
||||
"github.com/go-playground/locales/zh"
|
||||
ut "github.com/go-playground/universal-translator"
|
||||
"github.com/go-playground/validator/v10"
|
||||
zhTranslations "github.com/go-playground/validator/v10/translations/zh"
|
||||
"reflect"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type Validator struct{}
|
||||
|
||||
var validatorTrans ut.Translator
|
||||
|
||||
func init() {
|
||||
initValidatorTranslator()
|
||||
}
|
||||
|
||||
func Validate() Validator {
|
||||
return Validator{}
|
||||
}
|
||||
|
||||
func (v Validator) Error(err error) string {
|
||||
var errs validator.ValidationErrors
|
||||
if ok := errors.As(err, &errs); !ok {
|
||||
return err.Error()
|
||||
}
|
||||
|
||||
errMap := errs.Translate(validatorTrans)
|
||||
|
||||
var errMsg string
|
||||
for _, v := range errMap {
|
||||
errMsg = v
|
||||
}
|
||||
|
||||
return errMsg
|
||||
}
|
||||
|
||||
// initValidatorTranslator
|
||||
// @description: 初始化翻译机
|
||||
// @receiver vli
|
||||
func initValidatorTranslator() {
|
||||
//修改gin框架中的Validator属性,实现自定制
|
||||
if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
|
||||
// 注册一个获取json tag的自定义方法
|
||||
v.RegisterTagNameFunc(func(fld reflect.StructField) string {
|
||||
name := strings.SplitN(fld.Tag.Get("label"), ",", 2)[0]
|
||||
if name == "-" {
|
||||
return ""
|
||||
}
|
||||
return name
|
||||
})
|
||||
|
||||
zhT := zh.New() //中文翻译器
|
||||
enT := en.New() //英文翻译器
|
||||
|
||||
// 第一个参数是备用(fallback)的语言环境
|
||||
// 后面的参数是应该支持的语言环境(支持多个)
|
||||
// uni := ut.New(zhT, zhT) 也是可以的
|
||||
uni := ut.New(enT, zhT, enT)
|
||||
|
||||
// locale 通常取决于 http 请求头的 'Accept-Language'
|
||||
var ok bool
|
||||
// 也可以使用 uni.FindTranslator(...) 传入多个locale进行查找
|
||||
validatorTrans, ok = uni.GetTranslator("zh")
|
||||
if !ok {
|
||||
log.Errorf("获取翻译机失败")
|
||||
return
|
||||
}
|
||||
|
||||
err := overrideTranslator(v, validatorTrans)
|
||||
if err != nil {
|
||||
log.Errorf("覆盖原有翻译失败: %v", err.Error())
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// overrideTranslator
|
||||
// @description: 覆盖原有翻译
|
||||
// @param v
|
||||
// @param translator
|
||||
// @return error
|
||||
func overrideTranslator(v *validator.Validate, translator ut.Translator) error {
|
||||
err := zhTranslations.RegisterDefaultTranslations(v, translator)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
Reference in New Issue
Block a user