-
Notifications
You must be signed in to change notification settings - Fork 2
/
jwt.go
82 lines (63 loc) · 1.8 KB
/
jwt.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package main
import (
"log"
"time"
"github.com/golang-jwt/jwt"
"golang.org/x/crypto/bcrypt"
)
type User struct {
Username string `json:"username" yaml:"username"`
Password string `json:"password" yaml:"password"`
Permission []string `json:"permission" yaml:"permission"`
}
type Claims struct {
Token string `json:"token"`
Username string `json:"username"`
Permission []string `json:"permission"`
jwt.StandardClaims
}
var jwtKey = []byte("Change_me_$#BC@")
func generateJWT(u *User) (string, error) {
claims := Claims{
Username: u.Username,
Permission: u.Permission,
StandardClaims: jwt.StandardClaims{
ExpiresAt: time.Now().Add(time.Hour * 8).Unix(), // 8 hours session
},
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
tokenString, err := token.SignedString(jwtKey)
if err != nil {
log.Println("Signing Error: ", err)
}
return tokenString, nil
}
func generateAPIToken(permission []string, days int) (string, error) {
claims := Claims{
Permission: permission,
StandardClaims: jwt.StandardClaims{
ExpiresAt: time.Now().Add(time.Hour * time.Duration(24*days)).Unix(),
},
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
tokenString, err := token.SignedString(jwtKey)
if err != nil {
log.Println("Signing Error: ", err)
}
return tokenString, nil
}
func (user *User) HashPassword(password string) error {
bytes, err := bcrypt.GenerateFromPassword([]byte(password), 14)
if err != nil {
return err
}
user.Password = string(bytes)
return nil
}
func (user *User) CheckPassword(providedPassword string) error {
err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(providedPassword))
if err != nil {
return err
}
return nil
}