-
Notifications
You must be signed in to change notification settings - Fork 0
/
cache.go
98 lines (74 loc) · 2.68 KB
/
cache.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
90
91
92
93
94
95
96
97
98
package jwt
import (
"fmt"
"sync"
"time"
"github.com/alrusov/misc"
"github.com/alrusov/panic"
)
//----------------------------------------------------------------------------------------------------------------------------//
type (
// Элемент кэша для ранее созданных HTTP заголовков для метода JWT
clientCacheElement struct {
header string // Собственно заголовок
exp int64 // Время истечения (unixtime)
}
)
var (
cacheMutex = new(sync.Mutex)
clientsTokenCache = map[string]clientCacheElement{} // Кэш заголовков, ключ - см. сacheKey()
)
//----------------------------------------------------------------------------------------------------------------------------//
func init() {
go func() {
panicID := panic.ID()
defer panic.SaveStackToLogEx(panicID)
for {
if !misc.Sleep(30 * time.Minute) {
return
}
func() {
cacheMutex.Lock()
defer cacheMutex.Unlock()
now := misc.NowUnix()
for key, elm := range clientsTokenCache {
if now > elm.exp {
delete(clientsTokenCache, key)
}
}
}()
}
}()
}
//----------------------------------------------------------------------------------------------------------------------------//
// Создание ключа для кэша из имени пользователя и секрета
func cacheKey(user string, secret string) string {
return fmt.Sprintf("[%s].[%s]", user, secret)
}
//----------------------------------------------------------------------------------------------------------------------------//
// Создание HTTP заголовка для метода JWT для клиента из имени пользователя и секрета
func ClientHeader(user string, secret string, lifetime time.Duration) (headerString string, err error) {
key := cacheKey(user, secret)
cacheMutex.Lock()
cached, exists := clientsTokenCache[key]
cacheMutex.Unlock()
if exists && (cached.exp > misc.NowUnix()+60) { // если токен будет еще валиден больше 60 секунд, то используем кэшированный заголовок
headerString = cached.header
return
}
// Создаем заголовок
access, _, exp, err := MakeTokens(user, secret, lifetime, lifetime)
if err != nil {
return
}
headerString = "Bearer " + access
// И кэшируем его
cacheMutex.Lock()
clientsTokenCache[key] = clientCacheElement{
header: headerString,
exp: exp,
}
cacheMutex.Unlock()
return
}
//----------------------------------------------------------------------------------------------------------------------------//