[PD2] Gateway login, logout and auth middleware done.
Co-authored-by: tsousa111 <tiagao2001@hotmail.com>
This commit is contained in:
parent
aa90bfddce
commit
69559f41ca
7 changed files with 277 additions and 28 deletions
62
Projs/PD2/internal/gateway/jwt.go
Normal file
62
Projs/PD2/internal/gateway/jwt.go
Normal file
|
@ -0,0 +1,62 @@
|
|||
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")
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue