-
Notifications
You must be signed in to change notification settings - Fork 0
/
subjects.go
93 lines (77 loc) · 1.69 KB
/
subjects.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
83
84
85
86
87
88
89
90
91
92
93
package ironclad
import (
"fmt"
"sync"
"time"
"github.com/dgrijalva/jwt-go"
"golang.org/x/net/context"
)
// generating and removing subjects
var (
hmacSecret []byte
hmacOnce sync.Once
)
func initHmac(c context.Context) {
hmacOnce.Do(func() {
s, err := getConfig(c, "jwt-hmac.key")
if err != nil {
panic(err)
}
hmacSecret = s
})
if len(hmacSecret) < 32 {
panic(fmt.Sprintf("hmac secret is only %d bits", len(hmacSecret)*8))
}
}
type Subject struct {
Name string `json:"cn"`
jwt.StandardClaims
}
func ParseSubject(c context.Context, tokenString string) (*Subject, error) {
initHmac(c)
if tokenString == "" {
return nil, nil
}
subject := &Subject{}
_, err := jwt.ParseWithClaims(tokenString, subject,
func(token *jwt.Token) (interface{}, error) {
// important! otherwise bad things happen
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method: %v",
token.Header["alg"])
}
return hmacSecret, nil
})
if err != nil {
return nil, err
} else if err := subject.Valid(); err != nil {
return nil, err
} else {
return subject, nil
}
}
func (s *Subject) Serialize(c context.Context) (string, error) {
initHmac(c)
if s == nil {
return "", nil
}
return jwt.NewWithClaims(jwt.SigningMethodHS256, s).SignedString(hmacSecret)
}
func (s *Subject) CanEdit(l *Listing) bool {
if s == nil {
return false
}
return l.Seller == s.Subject
}
func (s *Subject) CanCreate() bool {
return s != nil
}
func newSubject(name, email string) *Subject {
return &Subject{
Name: name,
StandardClaims: jwt.StandardClaims{
ExpiresAt: time.Now().Add(7 * 24 * time.Hour).Unix(),
Subject: email,
},
}
}