-
-
Notifications
You must be signed in to change notification settings - Fork 692
/
token.go
95 lines (81 loc) · 2.53 KB
/
token.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
// Copyright (C) 2019 Nicola Murino
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, version 3.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
package httpd
import (
"crypto/sha256"
"encoding/hex"
"sync"
"time"
"github.com/drakkan/sftpgo/v2/internal/dataprovider"
"github.com/drakkan/sftpgo/v2/internal/logger"
"github.com/drakkan/sftpgo/v2/internal/util"
)
func newTokenManager(isShared int) tokenManager {
if isShared == 1 {
logger.Info(logSender, "", "using provider token manager")
return &dbTokenManager{}
}
logger.Info(logSender, "", "using memory token manager")
return &memoryTokenManager{}
}
type tokenManager interface {
Add(token string, expiresAt time.Time)
Get(token string) bool
Cleanup()
}
type memoryTokenManager struct {
invalidatedJWTTokens sync.Map
}
func (m *memoryTokenManager) Add(token string, expiresAt time.Time) {
m.invalidatedJWTTokens.Store(token, expiresAt)
}
func (m *memoryTokenManager) Get(token string) bool {
_, ok := m.invalidatedJWTTokens.Load(token)
return ok
}
func (m *memoryTokenManager) Cleanup() {
m.invalidatedJWTTokens.Range(func(key, value any) bool {
exp, ok := value.(time.Time)
if !ok || exp.Before(time.Now().UTC()) {
m.invalidatedJWTTokens.Delete(key)
}
return true
})
}
type dbTokenManager struct{}
func (m *dbTokenManager) getKey(token string) string {
digest := sha256.Sum256([]byte(token))
return hex.EncodeToString(digest[:])
}
func (m *dbTokenManager) Add(token string, expiresAt time.Time) {
key := m.getKey(token)
data := map[string]string{
"jwt": token,
}
session := dataprovider.Session{
Key: key,
Data: data,
Type: dataprovider.SessionTypeInvalidToken,
Timestamp: util.GetTimeAsMsSinceEpoch(expiresAt),
}
dataprovider.AddSharedSession(session) //nolint:errcheck
}
func (m *dbTokenManager) Get(token string) bool {
key := m.getKey(token)
_, err := dataprovider.GetSharedSession(key)
return err == nil
}
func (m *dbTokenManager) Cleanup() {
dataprovider.CleanupSharedSessions(dataprovider.SessionTypeInvalidToken, time.Now()) //nolint:errcheck
}