updating rest-api
This commit is contained in:
@@ -6,3 +6,8 @@ func HashPassword(password string) (string, error) {
|
||||
bytes, err := bcrypt.GenerateFromPassword([]byte(password), 14)
|
||||
return string(bytes), err
|
||||
}
|
||||
|
||||
func CheckPasswordHash(password, hashedPassword string) bool {
|
||||
err := bcrypt.CompareHashAndPassword([]byte(hashedPassword), []byte(password))
|
||||
return err == nil
|
||||
}
|
||||
|
||||
53
rest-api/utils/jwt.go
Normal file
53
rest-api/utils/jwt.go
Normal file
@@ -0,0 +1,53 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
)
|
||||
|
||||
const secretKey = "supersecret"
|
||||
|
||||
func GenerateToken(email string, userId int64) (string, error) {
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
|
||||
"email": "",
|
||||
"userId": "",
|
||||
"exp": time.Now().Add(time.Hour * 2).Unix(),
|
||||
})
|
||||
|
||||
return token.SignedString([]byte(secretKey))
|
||||
}
|
||||
|
||||
func VerifyToken(token string) (int64, error) {
|
||||
parsedToken, err := jwt.Parse(token, func(token *jwt.Token) (interface{}, error) {
|
||||
_, ok := token.Method.(*jwt.SigningMethodHMAC)
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("Unexpected signing method")
|
||||
}
|
||||
|
||||
return secretKey, nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return 0, errors.New("Could not parse token.")
|
||||
}
|
||||
|
||||
tokenIsValid := parsedToken.Valid
|
||||
|
||||
if !tokenIsValid {
|
||||
return 0, errors.New("Invalid token")
|
||||
}
|
||||
|
||||
claims, ok := parsedToken.Claims.(jwt.MapClaims)
|
||||
|
||||
if !ok {
|
||||
return 0, errors.New("Invalid token claims.")
|
||||
}
|
||||
|
||||
// email := claims["email"].(string)
|
||||
userId := int64(claims["userId"].(float64))
|
||||
|
||||
return userId, nil
|
||||
}
|
||||
Reference in New Issue
Block a user