/
nonceStore.go
89 lines (73 loc) · 1.64 KB
/
nonceStore.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
package gormid
import (
"errors"
"flag"
"fmt"
"log"
"sync"
"time"
"gorm.io/gorm"
"github.com/Schrodinger-Box/gormid/models"
)
var maxNonceAge = flag.Duration("max-nonce-age",
60*time.Second,
"Maximum accepted age for openid nonces. The bigger, the more"+
"memory is needed to store used nonces.")
type nonceStore struct {
db *gorm.DB
mu sync.Mutex
}
func (d *nonceStore) Accept(endpoint, nonce string) error {
if len(nonce) < 20 || len(nonce) > 256 {
return errors.New("invalid nonce")
}
ts, err := time.Parse(time.RFC3339, nonce[0:20])
if err != nil {
return err
}
now := time.Now()
diff := now.Sub(ts)
if diff > *maxNonceAge {
return fmt.Errorf("nonce too old: %fs", diff.Seconds())
}
s := nonce[20:]
d.mu.Lock()
defer d.mu.Unlock()
var nonces []*models.Nonce
if err := d.db.Where("endpoint = ?", endpoint).Find(&nonces).Error; err != nil {
return err
}
newNonces := []*models.Nonce{{ts, s, endpoint}}
if len(nonces) > 0 {
for _, n := range nonces {
if n.T.UTC() == ts && n.S == s {
return errors.New("nonce already used")
}
if now.Sub(n.T) < *maxNonceAge {
newNonces = append(newNonces, n)
}
}
if ok := storeNonces(d.db, newNonces); !ok {
return errors.New("could not store nonces")
}
} else {
if ok := storeNonces(d.db, newNonces); !ok {
return errors.New("could not store nonces")
}
}
return nil
}
func storeNonces(db *gorm.DB, nonces []*models.Nonce) bool {
var wg sync.WaitGroup
for _, n := range nonces {
wg.Add(1)
go func(nonce *models.Nonce) {
if err := db.Create(&nonce).Error; err != nil {
log.Println(err)
}
wg.Done()
}(n)
}
wg.Wait()
return true
}