-
Notifications
You must be signed in to change notification settings - Fork 0
/
bcrypt.go
47 lines (38 loc) · 1.24 KB
/
bcrypt.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package libs
import (
"time"
"golang.org/x/crypto/bcrypt"
"github.com/dgrijalva/jwt-go"
"fmt"
"os"
)
func HashPassword(password string) (string, error) {
bytes, err := bcrypt.GenerateFromPassword([]byte(password), 14)
return string(bytes), err
}
func CheckPasswordHash(password, hash string) bool {
err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
return err == nil
}
//GenerateToken -> generates token
func GenerateToken(userid int32) 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
})
}