/
crypto.go
65 lines (57 loc) · 1.54 KB
/
crypto.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package crypto
import (
"fmt"
"time"
"github.com/dgrijalva/jwt-go"
"golang.org/x/crypto/bcrypt"
"github.com/Aibier/go-aml-service/internal/pkg/config"
log "github.com/sirupsen/logrus"
)
// HashAndSalt ...
func HashAndSalt(pwd []byte) string {
hash, err := bcrypt.GenerateFromPassword(pwd, bcrypt.MinCost)
if err != nil {
log.Println(err)
}
return string(hash)
}
// ComparePasswords ...
func ComparePasswords(hashedPwd string, plainPwd []byte) bool {
byteHash := []byte(hashedPwd)
err := bcrypt.CompareHashAndPassword(byteHash, plainPwd)
if err != nil {
log.WithError(err).Logger.Printf("Something went wrong at %s", err)
return false
}
return true
}
// CreateToken ...
func CreateToken(username string) (string, error) {
config := config.GetConfig()
var err error
//Creating Access Token
atClaims := jwt.MapClaims{}
atClaims["authorized"] = true
atClaims["username"] = username
atClaims["exp"] = time.Now().Add(time.Hour * 24 * 365).Unix()
at := jwt.NewWithClaims(jwt.SigningMethodHS512, atClaims)
token, err := at.SignedString([]byte(config.Server.Secret)) // SECRET
if err != nil {
return "token creation error", err
}
return token, nil
}
// ValidateToken ...
func ValidateToken(tokenString string) bool {
config := config.GetConfig()
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("there was an error")
}
return []byte(config.Server.Secret), nil
})
if err != nil {
return false
}
return token.Valid
}