CSI-ES-2324/Projs/PD2/internal/gateway/jwt.go
afonso 69559f41ca
[PD2] Gateway login, logout and auth middleware done.
Co-authored-by: tsousa111 <tiagao2001@hotmail.com>
2024-05-30 00:55:59 +01:00

62 lines
1.7 KiB
Go

package gateway
import (
"errors"
"os"
"time"
"github.com/golang-jwt/jwt/v4"
"golang.org/x/crypto/bcrypt"
)
// HashPassword hashes the given password and returns the hashed password as a byte slice.
func HashPassword(password string) ([]byte, error) {
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
if err != nil {
return nil, err
}
return hashedPassword, nil
}
// CheckPassword compares a bcrypt hashed password with its possible plaintext equivalent.
func CheckPassword(hashedPassword []byte, password string) error {
return bcrypt.CompareHashAndPassword(hashedPassword, []byte(password))
}
// GenerateJWT generates a JWT token with a specified user ID and expiry time.
func GenerateJWT(uid string) (string, error) {
claims := &jwt.MapClaims{
"sub": uid,
"exp": time.Now().Add(time.Hour * 24).Unix(),
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
tokenString, err := token.SignedString([]byte(os.Getenv("SECRET_KEY")))
if err != nil {
return "", err
}
return tokenString, nil
}
// ValidateJWT validates the given JWT token and returns the user id if valid.
func ValidateJWT(tokenString string) (string, error) {
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
return []byte(os.Getenv("SECRET_KEY")), nil
})
if err != nil {
return "", err
}
if !token.Valid {
return "", errors.New("invalid token")
}
if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
if time.Now().Unix() > claims["exp"].(int64) {
return "", errors.New("JWT token has expired")
}
return claims["sub"].(string),nil
} else {
return "",errors.New("Failed to get jwt claims")
}
}