goweb/utils/bcrypt.go

50 lines
1.4 KiB
Go

package utils
import (
"fmt"
"github.com/golang-jwt/jwt"
"golang.org/x/crypto/bcrypt"
"os"
"time"
)
func HashPassword(pass *string) {
bytePass := []byte(*pass)
hPass, _ := bcrypt.GenerateFromPassword(bytePass, bcrypt.DefaultCost)
*pass = string(hPass)
}
func ComparePassword(dbPass, pass string) bool {
return bcrypt.CompareHashAndPassword([]byte(dbPass), []byte(pass)) == nil
}
//GenerateToken -> generates token
func GenerateToken(userId uint) string {
claims := jwt.MapClaims{
"exp": time.Now().Add(time.Hour * 3).Unix(),
"iat": time.Now().Unix(),
"userId": userId,
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
t, _ := token.SignedString([]byte(os.Getenv("JWT_SECRET")))
// 保存Token到Redis
//redisKey := fmt.Sprintf("auth:token:%v", userId)
//_ = global.RedisConn.SetWithTimeout(redisKey, t, "10800")
return t
}
//ValidateToken --> validate the given token
func ValidateToken(token string) (*jwt.Token, error) {
//2nd arg function return secret key after checking if the signing method is HMAC and returned key is used by 'Parse' to decode the token)
return jwt.Parse(token, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
//nil secret key
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}
return []byte(os.Getenv("JWT_SECRET")), nil
})
}