-
Notifications
You must be signed in to change notification settings - Fork 6
/
urlsigner.go
72 lines (59 loc) · 1.71 KB
/
urlsigner.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
package slimhttp
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"errors"
"net/url"
uuid "github.com/satori/go.uuid"
)
var (
TokenKey = "token"
ErrNoTokenFound = errors.New("No token on request")
ErrInvalidToken = errors.New("Invalid token recieved")
)
// URLSigner contains the secret used to sign URLs
type URLSigner struct{ secret string }
// NewURLSigner creates a new URLSigner instance
func NewURLSigner() *URLSigner {
return &URLSigner{secret: uuid.NewV4().String()}
}
// NewURLSignerFromSecret creates a new URSigner instance
// from a passed secret
func NewURLSignerFromSecret(secret string) *URLSigner {
return &URLSigner{secret: secret}
}
// SignURL takes a url and securely signs it using sha256
// and the secret on the URLSigner and returns the token
func (s *URLSigner) SignURL(u *url.URL) string {
// Create a new query with the token
query := u.Query()
query.Add(TokenKey, s.generateToken(u.String()))
// Encode and return the URL
u.RawQuery = query.Encode()
return u.String()
}
// ValidateURL takes a url
func (s *URLSigner) ValidateURL(u *url.URL) error {
oldToken := u.Query().Get(TokenKey)
// Verify a token exists on the request URL
if oldToken == "" {
return ErrNoTokenFound
}
// Clean the token off the old URL
query := u.Query()
query.Del(TokenKey)
u.RawQuery = query.Encode()
// Check the old token against a newly generated one
if oldToken != s.generateToken(u.String()) {
return ErrInvalidToken
}
return nil
}
// generateToken signs the passed URL and add the token to the
// parsed url.URL
func (s *URLSigner) generateToken(rawurl string) string {
mac := hmac.New(sha256.New, []byte(s.secret))
mac.Write([]byte(rawurl))
return hex.EncodeToString(mac.Sum(nil))
}