updating rest-api

This commit is contained in:
2026-07-17 11:56:13 -05:00
parent 39433a0044
commit c4d7f52d37
15 changed files with 276 additions and 9 deletions

View File

@@ -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
View 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
}