12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697 |
- package csrf
- import (
- "bytes"
- "crypto/hmac"
- "crypto/sha1"
- "crypto/subtle"
- "encoding/base64"
- "fmt"
- "strconv"
- "strings"
- "time"
- )
- const TIMEOUT = 24 * time.Hour
- func clean(s string) string {
- return strings.Replace(s, ":", "_", -1)
- }
- func GenerateToken(key, userID, actionID string) string {
- return generateTokenAtTime(key, userID, actionID, time.Now())
- }
- func generateTokenAtTime(key, userID, actionID string, now time.Time) string {
- h := hmac.New(sha1.New, []byte(key))
- fmt.Fprintf(h, "%s:%s:%d", clean(userID), clean(actionID), now.UnixNano())
- tok := fmt.Sprintf("%s:%d", h.Sum(nil), now.UnixNano())
- return base64.URLEncoding.EncodeToString([]byte(tok))
- }
- func ValidToken(token, key, userID, actionID string) bool {
- return validTokenAtTime(token, key, userID, actionID, time.Now())
- }
- func validTokenAtTime(token, key, userID, actionID string, now time.Time) bool {
-
- data, err := base64.URLEncoding.DecodeString(token)
- if err != nil {
- return false
- }
-
- sep := bytes.LastIndex(data, []byte{':'})
- if sep < 0 {
- return false
- }
- nanos, err := strconv.ParseInt(string(data[sep+1:]), 10, 64)
- if err != nil {
- return false
- }
- issueTime := time.Unix(0, nanos)
-
- if now.Sub(issueTime) >= TIMEOUT {
- return false
- }
-
-
-
- if issueTime.After(now.Add(1 * time.Minute)) {
- return false
- }
- expected := generateTokenAtTime(key, userID, actionID, issueTime)
-
-
- return subtle.ConstantTimeCompare([]byte(token), []byte(expected)) == 1
- }
|