-
Notifications
You must be signed in to change notification settings - Fork 0
/
jwt.go
75 lines (61 loc) · 1.81 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
package jwt
import (
"fmt"
"strings"
"time"
"github.com/dgrijalva/jwt-go"
andro "github.com/soldevx/kuiper/andro/pkg/utl/model"
)
var minSecretLen = 128
// New generates new JWT service necessary for auth middleware
func New(algo, secret string, ttlMinutes, minSecretLength int) (Service, error) {
if minSecretLength > 0 {
minSecretLen = minSecretLength
}
if len(secret) < minSecretLen {
return Service{}, fmt.Errorf("jwt secret length is %v, which is less than required %v", len(secret), minSecretLen)
}
signingMethod := jwt.GetSigningMethod(algo)
if signingMethod == nil {
return Service{}, fmt.Errorf("invalid jwt signing method: %s", algo)
}
return Service{
key: []byte(secret),
algo: signingMethod,
ttl: time.Duration(ttlMinutes) * time.Minute,
}, nil
}
// Service provides a Json-Web-Token authentication implementation
type Service struct {
// Secret key used for signing.
key []byte
// Duration for which the jwt token is valid.
ttl time.Duration
// JWT signing algorithm
algo jwt.SigningMethod
}
// ParseToken parses token from Authorization header
func (s Service) ParseToken(authHeader string) (*jwt.Token, error) {
parts := strings.SplitN(authHeader, " ", 2)
if !(len(parts) == 2 && parts[0] == "Bearer") {
return nil, andro.ErrGeneric
}
return jwt.Parse(parts[1], func(token *jwt.Token) (interface{}, error) {
if s.algo != token.Method {
return nil, andro.ErrGeneric
}
return s.key, nil
})
}
// GenerateToken generates new JWT token and populates it with user data
func (s Service) GenerateToken(u andro.User) (string, error) {
return jwt.NewWithClaims(s.algo, jwt.MapClaims{
"id": u.Base.ID,
"u": u.Username,
"e": u.Email,
"r": u.Role.AccessLevel,
"c": u.CompanyID,
"l": u.LocationID,
"exp": time.Now().Add(s.ttl).Unix(),
}).SignedString(s.key)
}