-
Notifications
You must be signed in to change notification settings - Fork 0
/
otp.go
75 lines (60 loc) · 1.48 KB
/
otp.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
// Package main - the OTP file is used for having a OTP manager
package main
import (
"context"
"time"
"github.com/google/uuid"
)
type OTP struct {
Key string
Created time.Time
}
type Verifier interface {
VerifyOTP(otp string) bool
}
type RetentionMap map[string]OTP
// NewRetentionMap will create a new retentionmap and start the retention given the set period
func NewRetentionMap(ctx context.Context, retentionPeriod time.Duration) RetentionMap {
rm := make(RetentionMap)
go rm.Retention(ctx, retentionPeriod)
return rm
}
// NewOTP creates and adds a new otp to the map
func (rm RetentionMap) NewOTP() OTP {
o := OTP{
Key: uuid.NewString(),
Created: time.Now(),
}
rm[o.Key] = o
return o
}
// VerifyOTP will make sure a OTP exists
// and return true if so
// It will also delete the key so it cant be reused
func (rm RetentionMap) VerifyOTP(otp string) bool {
// Verify OTP is existing
if _, ok := rm[otp]; !ok {
// otp does not exist
return false
}
delete(rm, otp)
return true
}
// Retention will make sure old OTPs are removed
// Is Blocking, so run as a Goroutine
func (rm RetentionMap) Retention(ctx context.Context, retentionPeriod time.Duration) {
ticker := time.NewTicker(400 * time.Millisecond)
for {
select {
case <-ticker.C:
for _, otp := range rm {
// Add Retention to Created and check if it is expired
if otp.Created.Add(retentionPeriod).Before(time.Now()) {
delete(rm, otp.Key)
}
}
case <-ctx.Done():
return
}
}
}