-
Notifications
You must be signed in to change notification settings - Fork 0
/
webtoken.go
83 lines (73 loc) · 1.4 KB
/
webtoken.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
package main
import (
"crypto/rand"
"encoding/base32"
"sync"
"time"
)
type WebToken struct {
User string
Timestamp time.Time
}
func NewWebToken(user string) WebToken {
return WebToken{
User: user,
Timestamp: time.Now(),
}
}
func (t WebToken) Refresh() WebToken {
newToken := t
newToken.Timestamp = time.Now()
return newToken
}
type WebTokenStorage struct {
storage map[string]WebToken
mutex sync.Mutex
}
func NewWebTokenStorage() WebTokenStorage {
return WebTokenStorage{
storage: make(map[string]WebToken),
}
}
func (w *WebTokenStorage) computeToken() string {
var tmp [32]byte
if _, err := rand.Read(tmp[:]); err != nil {
panic(err)
}
return base32.StdEncoding.EncodeToString(tmp[:])
}
func (w *WebTokenStorage) MapUser(user string) string {
for {
token := w.computeToken()
w.mutex.Lock()
if _, ok := w.storage[token]; !ok {
w.storage[token] = NewWebToken(user)
w.mutex.Unlock()
return token
}
w.mutex.Unlock()
}
}
func (w *WebTokenStorage) VerifyToken(token string) string {
w.mutex.Lock()
defer w.mutex.Unlock()
t, ok := w.storage[token]
if ok {
w.storage[token] = t.Refresh()
return t.User
}
return ""
}
func (w *WebTokenStorage) Expire() uint {
var count uint
w.mutex.Lock()
defer w.mutex.Unlock()
for k, v := range w.storage {
count++
if time.Since(v.Timestamp) > 24*time.Hour {
delete(w.storage, k)
count--
}
}
return count
}