-
Notifications
You must be signed in to change notification settings - Fork 137
/
registration_logins.go
239 lines (211 loc) · 6.11 KB
/
registration_logins.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
package session
import (
"context"
"encoding/json"
"sync"
"time"
"github.com/cozy/cozy-stack/model/instance/lifecycle"
"github.com/cozy/cozy-stack/pkg/config/config"
"github.com/cozy/cozy-stack/pkg/consts"
"github.com/cozy/cozy-stack/pkg/couchdb"
"github.com/cozy/cozy-stack/pkg/logger"
"github.com/cozy/cozy-stack/pkg/prefixer"
"github.com/cozy/cozy-stack/pkg/utils"
)
var log = logger.WithNamespace("sessions")
const redisRegistationKey = "registration-logins"
type registrationEntry struct {
Domain string
ClientID string
LoginEntryID string
Expire time.Time
}
func (r *registrationEntry) Key() string {
return r.Domain + "|" + r.ClientID
}
var (
registrationExpirationDuration = 5 * time.Minute
registrationsMap map[string]registrationEntry
registrationsMapLock sync.Mutex
)
// SweepLoginRegistrations starts the login registration process.
//
// This process involving a queue of registration login entries is necessary to
// distinguish "normal" logins from logins to give right to an OAuth
// application.
//
// Since we cannot really distinguish between them other than trusting the
// user, we send a notification to the user by following this process:
// - if we identify a login for a device registration — by looking at the
// redirection address — we push an entry onto the queue
// - if we do not receive the activation of the device by the user in 5
// minutes, we send a notification for a "normal" login
// - otherwise we send a notification for the activation of a new device.
func SweepLoginRegistrations() utils.Shutdowner {
closed := make(chan struct{})
go func() {
waitDuration := registrationExpirationDuration / 2
for {
select {
case <-time.After(waitDuration):
var err error
waitDuration, err = sweepRegistrations()
if err != nil {
log.Errorf("Could not sweep registration queue: %s", err)
}
if waitDuration <= 0 {
waitDuration = registrationExpirationDuration
}
case <-closed:
return
}
}
}()
return &sweeper{closed}
}
type sweeper struct {
closed chan struct{}
}
func (s *sweeper) Shutdown(ctx context.Context) error {
select {
case s.closed <- struct{}{}:
case <-ctx.Done():
}
return nil
}
// PushLoginRegistration pushes a new login into the registration queue.
func PushLoginRegistration(db prefixer.Prefixer, login *LoginEntry, clientID string) error {
entry := registrationEntry{
Domain: db.DomainName(),
ClientID: clientID,
LoginEntryID: login.ID(),
Expire: time.Now(),
}
if cli := config.GetConfig().SessionStorage; cli != nil {
b, err := json.Marshal(entry)
if err != nil {
return err
}
ctx := context.Background()
return cli.HSet(ctx, redisRegistationKey, entry.Key(), b).Err()
}
registrationsMapLock.Lock()
if registrationsMap == nil {
registrationsMap = make(map[string]registrationEntry)
}
registrationsMap[entry.Key()] = entry
registrationsMapLock.Unlock()
return nil
}
// RemoveLoginRegistration removes a login from the registration map.
func RemoveLoginRegistration(domain, clientID string) error {
var entryPtr *registrationEntry
key := domain + "|" + clientID
if cli := config.GetConfig().SessionStorage; cli != nil {
ctx := context.Background()
b, err := cli.HGet(ctx, redisRegistationKey, key).Result()
if err != nil {
return err
}
var entry registrationEntry
if err = json.Unmarshal([]byte(b), &entry); err != nil {
return err
}
if err = cli.HDel(ctx, redisRegistationKey, key).Err(); err != nil {
return err
}
entryPtr = &entry
} else {
registrationsMapLock.Lock()
entry, ok := registrationsMap[key]
if ok {
delete(registrationsMap, key)
entryPtr = &entry
}
registrationsMapLock.Unlock()
}
if entryPtr != nil {
_ = sendRegistrationNotification(entryPtr, true)
}
return nil
}
func sweepRegistrations() (waitDuration time.Duration, err error) {
var expiredLogins []registrationEntry
now := time.Now()
if cli := config.GetConfig().SessionStorage; cli != nil {
ctx := context.Background()
var vals map[string]string
vals, err = cli.HGetAll(ctx, redisRegistationKey).Result()
if err != nil {
return
}
var deletedKeys []string
for key, data := range vals {
var entry registrationEntry
if err = json.Unmarshal([]byte(data), &entry); err != nil {
deletedKeys = append(deletedKeys, key)
continue
}
diff := entry.Expire.Sub(now)
if diff < -24*time.Hour {
// skip too old entries
deletedKeys = append(deletedKeys, entry.Key())
} else if diff <= 10*time.Second {
expiredLogins = append(expiredLogins, entry)
deletedKeys = append(deletedKeys, entry.Key())
} else if waitDuration == 0 || waitDuration > diff {
waitDuration = diff
}
}
if len(deletedKeys) > 0 {
err = cli.HDel(ctx, redisRegistationKey, deletedKeys...).Err()
}
} else {
registrationsMapLock.Lock()
var deletedKeys []string
for _, entry := range registrationsMap {
diff := entry.Expire.Sub(now)
if diff < -24*time.Hour {
// skip too old entries
deletedKeys = append(deletedKeys, entry.Key())
} else if diff <= 10*time.Second {
expiredLogins = append(expiredLogins, entry)
deletedKeys = append(deletedKeys, entry.Key())
} else if waitDuration == 0 || waitDuration > diff {
waitDuration = diff
}
}
for _, key := range deletedKeys {
delete(registrationsMap, key)
}
registrationsMapLock.Unlock()
}
if len(expiredLogins) > 0 {
sendExpiredRegistrationNotifications(expiredLogins)
}
return
}
func sendRegistrationNotification(entry *registrationEntry, registrationNotification bool) error {
i, err := lifecycle.GetInstance(entry.Domain)
if err != nil {
return err
}
var clientID string
if registrationNotification {
clientID = entry.ClientID
}
if clientID != "" {
return SendNewRegistrationNotification(i, clientID)
}
var login LoginEntry
err = couchdb.GetDoc(i, consts.SessionsLogins, entry.LoginEntryID, &login)
if err != nil {
return err
}
return sendLoginNotification(i, &login)
}
func sendExpiredRegistrationNotifications(entries []registrationEntry) {
for _, entry := range entries {
_ = sendRegistrationNotification(&entry, false)
}
}