/
database.go
258 lines (218 loc) Β· 5.6 KB
/
database.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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
package access
import (
"errors"
"fmt"
"net/http"
"sync"
"time"
"github.com/safing/portbase/database"
"github.com/safing/portbase/database/record"
"github.com/safing/portmaster/spn/access/account"
)
const (
userRecordKey = "core:spn/account/user"
authTokenRecordKey = "core:spn/account/authtoken" //nolint:gosec // Not a credential.
tokenStorageKeyTemplate = "core:spn/account/tokens/%s" //nolint:gosec // Not a credential.
)
var db = database.NewInterface(&database.Options{
Local: true,
Internal: true,
})
// UserRecord holds a SPN user account.
type UserRecord struct {
record.Base
sync.Mutex
*account.User
LastNotifiedOfEnd *time.Time
LoggedInAt *time.Time
}
// MayUseSPN returns whether the user may currently use the SPN.
func (user *UserRecord) MayUseSPN() bool {
// Shadow this function in order to allow calls on a nil user.
if user == nil || user.User == nil {
return false
}
return user.User.MayUseSPN()
}
// MayUsePrioritySupport returns whether the user may currently use the priority support.
func (user *UserRecord) MayUsePrioritySupport() bool {
// Shadow this function in order to allow calls on a nil user.
if user == nil || user.User == nil {
return false
}
return user.User.MayUsePrioritySupport()
}
// MayUse returns whether the user may currently use the feature identified by
// the given feature ID.
// Leave feature ID empty to check without feature.
func (user *UserRecord) MayUse(featureID account.FeatureID) bool {
// Shadow this function in order to allow calls on a nil user.
if user == nil || user.User == nil {
return false
}
return user.User.MayUse(featureID)
}
// AuthTokenRecord holds an authentication token.
type AuthTokenRecord struct {
record.Base
sync.Mutex
Token *account.AuthToken
}
// GetToken returns the token from the record.
func (authToken *AuthTokenRecord) GetToken() *account.AuthToken {
authToken.Lock()
defer authToken.Unlock()
return authToken.Token
}
// SaveNewAuthToken saves a new auth token to the database.
func SaveNewAuthToken(deviceID string, resp *http.Response) error {
token, ok := account.GetNextTokenFromResponse(resp)
if !ok {
return account.ErrMissingToken
}
newAuthToken := &AuthTokenRecord{
Token: &account.AuthToken{
Device: deviceID,
Token: token,
},
}
return newAuthToken.Save()
}
// Update updates an existing auth token with the next token from a response.
func (authToken *AuthTokenRecord) Update(resp *http.Response) error {
token, ok := account.GetNextTokenFromResponse(resp)
if !ok {
return account.ErrMissingToken
}
// Update token with new account.AuthToken.
func() {
authToken.Lock()
defer authToken.Unlock()
authToken.Token = &account.AuthToken{
Device: authToken.Token.Device,
Token: token,
}
}()
return authToken.Save()
}
var (
accountCacheLock sync.Mutex
cachedUser *UserRecord
cachedUserSet bool
cachedAuthToken *AuthTokenRecord
)
func clearUserCaches() {
accountCacheLock.Lock()
defer accountCacheLock.Unlock()
cachedUser = nil
cachedUserSet = false
cachedAuthToken = nil
}
// GetUser returns the current user account.
// Returns nil when no user is logged in.
func GetUser() (*UserRecord, error) {
// Check cache.
accountCacheLock.Lock()
defer accountCacheLock.Unlock()
if cachedUserSet {
if cachedUser == nil {
return nil, ErrNotLoggedIn
}
return cachedUser, nil
}
// Load from disk.
r, err := db.Get(userRecordKey)
if err != nil {
if errors.Is(err, database.ErrNotFound) {
cachedUser = nil
cachedUserSet = true
return nil, ErrNotLoggedIn
}
return nil, err
}
// Unwrap record.
if r.IsWrapped() {
// only allocate a new struct, if we need it
newUser := &UserRecord{}
err = record.Unwrap(r, newUser)
if err != nil {
return nil, err
}
cachedUser = newUser
cachedUserSet = true
return cachedUser, nil
}
// Or adjust type.
newUser, ok := r.(*UserRecord)
if !ok {
return nil, fmt.Errorf("record not of type *UserRecord, but %T", r)
}
cachedUser = newUser
cachedUserSet = true
return cachedUser, nil
}
// Save saves the User.
func (user *UserRecord) Save() error {
// Update cache.
accountCacheLock.Lock()
defer accountCacheLock.Unlock()
cachedUser = user
cachedUserSet = true
// Update view if unset.
if user.View == nil {
user.UpdateView(0)
}
// Set, check and update metadata.
if !user.KeyIsSet() {
user.SetKey(userRecordKey)
}
user.UpdateMeta()
return db.Put(user)
}
// GetAuthToken returns the current auth token.
func GetAuthToken() (*AuthTokenRecord, error) {
// Check cache.
accountCacheLock.Lock()
defer accountCacheLock.Unlock()
if cachedAuthToken != nil {
return cachedAuthToken, nil
}
// Load from disk.
r, err := db.Get(authTokenRecordKey)
if err != nil {
return nil, err
}
// Unwrap record.
if r.IsWrapped() {
// only allocate a new struct, if we need it
newAuthRecord := &AuthTokenRecord{}
err = record.Unwrap(r, newAuthRecord)
if err != nil {
return nil, err
}
cachedAuthToken = newAuthRecord
return newAuthRecord, nil
}
// Or adjust type.
newAuthRecord, ok := r.(*AuthTokenRecord)
if !ok {
return nil, fmt.Errorf("record not of type *AuthTokenRecord, but %T", r)
}
cachedAuthToken = newAuthRecord
return newAuthRecord, nil
}
// Save saves the auth token to the database.
func (authToken *AuthTokenRecord) Save() error {
// Update cache.
accountCacheLock.Lock()
defer accountCacheLock.Unlock()
cachedAuthToken = authToken
// Set, check and update metadata.
if !authToken.KeyIsSet() {
authToken.SetKey(authTokenRecordKey)
}
authToken.UpdateMeta()
authToken.Meta().MakeSecret()
authToken.Meta().MakeCrownJewel()
return db.Put(authToken)
}