1
2
3
4
5
6 package xsrftoken
7
8 import (
9 "crypto/hmac"
10 "crypto/sha1"
11 "crypto/subtle"
12 "encoding/base64"
13 "fmt"
14 "strconv"
15 "strings"
16 "time"
17 )
18
19
20
21 const Timeout = 24 * time.Hour
22
23
24 func clean(s string) string {
25 return strings.Replace(s, `:`, `::`, -1)
26 }
27
28
29
30
31
32
33 func Generate(key, userID, actionID string) string {
34 return generateTokenAtTime(key, userID, actionID, time.Now())
35 }
36
37
38 func generateTokenAtTime(key, userID, actionID string, now time.Time) string {
39 if len(key) == 0 {
40 panic("zero length xsrf secret key")
41 }
42
43 milliTime := (now.UnixNano() + 1e6 - 1) / 1e6
44
45 h := hmac.New(sha1.New, []byte(key))
46 fmt.Fprintf(h, "%s:%s:%d", clean(userID), clean(actionID), milliTime)
47
48
49 tok := string(h.Sum(nil))
50 tok = base64.URLEncoding.EncodeToString([]byte(tok))
51 tok = strings.TrimRight(tok, "=")
52
53 return fmt.Sprintf("%s:%d", tok, milliTime)
54 }
55
56
57
58 func Valid(token, key, userID, actionID string) bool {
59 return validTokenAtTime(token, key, userID, actionID, time.Now(), Timeout)
60 }
61
62
63
64 func ValidFor(token, key, userID, actionID string, timeout time.Duration) bool {
65 return validTokenAtTime(token, key, userID, actionID, time.Now(), timeout)
66 }
67
68
69 func validTokenAtTime(token, key, userID, actionID string, now time.Time, timeout time.Duration) bool {
70 if len(key) == 0 {
71 panic("zero length xsrf secret key")
72 }
73
74 sep := strings.LastIndex(token, ":")
75 if sep < 0 {
76 return false
77 }
78 millis, err := strconv.ParseInt(token[sep+1:], 10, 64)
79 if err != nil {
80 return false
81 }
82 issueTime := time.Unix(0, millis*1e6)
83
84
85 if now.Sub(issueTime) >= timeout {
86 return false
87 }
88
89
90
91
92 if issueTime.After(now.Add(1 * time.Minute)) {
93 return false
94 }
95
96 expected := generateTokenAtTime(key, userID, actionID, issueTime)
97
98
99
100 return subtle.ConstantTimeCompare([]byte(token), []byte(expected)) == 1
101 }
102
View as plain text