This repository has been archived by the owner on Mar 29, 2018. It is now read-only.
forked from mrhenry/go-getstream
-
Notifications
You must be signed in to change notification settings - Fork 10
/
signer.go
102 lines (83 loc) · 2.44 KB
/
signer.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
94
95
96
97
98
99
100
101
102
package getstream
import (
"crypto/hmac"
"crypto/sha1"
"encoding/base64"
"strings"
"gopkg.in/dgrijalva/jwt-go.v3"
)
// Credits to https://github.com/hyperworks/go-getstream for the urlSafe and generateToken methods
// Signer is responsible for generating Tokens
type Signer struct {
Secret string
}
// SignFeed sets the token on a Feed
func (s Signer) SignFeed(feedID string) string {
return s.GenerateToken(feedID)
}
func (s Signer) UrlSafe(src string) string {
src = strings.Replace(src, "+", "-", -1)
src = strings.Replace(src, "/", "_", -1)
src = strings.Trim(src, "=")
return src
}
// generateToken will use the Secret of the signer and the message passed as an argument to generate a Token
func (s Signer) GenerateToken(message string) string {
hash := sha1.New()
hash.Write([]byte(s.Secret))
key := hash.Sum(nil)
mac := hmac.New(sha1.New, key)
mac.Write([]byte(message))
digest := base64.StdEncoding.EncodeToString(mac.Sum(nil))
return s.UrlSafe(digest)
}
// GenerateFeedScopeToken returns a jwt
func (s Signer) GenerateFeedScopeToken(context ScopeContext, action ScopeAction, feedIDWithoutColon string) (string, error) {
claims := jwt.MapClaims{
"resource": context.Value(),
"action": action.Value(),
// "aud":
// "exp": time.Now().UTC().Add(time.Hour * 1),
// "jti": uuid.New(),
// "iat": time.Now(),
// "iss":
// "nbf": time.Now().Unix(),
// "sub":
}
if feedIDWithoutColon != "" {
claims["feed_id"] = feedIDWithoutColon
} else {
claims["feed_id"] = "*"
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
// Sign and get the complete encoded token as a string using the secret
tokenString, err := token.SignedString([]byte(s.Secret))
if err != nil {
return "", err
}
return tokenString, nil
}
// GenerateUserScopeToken returns a jwt
func (s Signer) GenerateUserScopeToken(context ScopeContext, action ScopeAction, userID string) (string, error) {
claims := jwt.MapClaims{
"resource": context.Value(),
"action": action.Value(),
// "aud":
// "exp": time.Now().UTC().Add(time.Hour * 1),
// "jti": uuid.New(),
// "iat": time.Now(),
// "iss":
// "nbf": time.Now().Unix(),
// "sub":
}
if userID != "" {
claims["user_id"] = userID
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
// Sign and get the complete encoded token as a string using the secret
tokenString, err := token.SignedString([]byte(s.Secret))
if err != nil {
return "", err
}
return tokenString, nil
}