Created
June 24, 2021 11:41
-
-
Save dipeshhkc/269513d0adc49d6e4ada5dda68864e3a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"))) | |
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 | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment