generated from antoniopaya22/go-rest-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
crypto.go
59 lines (52 loc) · 1.37 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
package crypto
import (
"fmt"
"log"
"time"
"github.com/dgrijalva/jwt-go"
config2 "github.com/ebcp-dev/go-rest-sm/internal/pkg/config"
"golang.org/x/crypto/bcrypt"
)
func HashAndSalt(pwd []byte) string {
hash, err := bcrypt.GenerateFromPassword(pwd, bcrypt.MinCost)
if err != nil {
log.Println(err)
}
return string(hash)
}
func ComparePasswords(hashedPwd string, plainPwd []byte) bool {
byteHash := []byte(hashedPwd)
err := bcrypt.CompareHashAndPassword(byteHash, plainPwd)
if err != nil {
return false
}
return true
}
func CreateToken(username string) (string, error) {
config := config2.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
}
func ValidateToken(tokenString string) bool {
config := config2.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
}