-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathverify.go
92 lines (77 loc) · 2.13 KB
/
verify.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
package main
import (
"os"
"fmt"
"sync"
"encoding/base64"
"path/filepath"
"crypto/rand"
"errors"
"time"
"net/http"
)
type verificationSession struct {
Code string
Created time.Time
}
type verificationRegistry struct {
Lock sync.Mutex
Sessions map[string]verificationSession
Lifespan time.Duration
}
func newVerificationRegistry(lifespan time.Duration) *verificationRegistry {
return &verificationRegistry {
Sessions: map[string]verificationSession{},
Lifespan: lifespan,
}
}
func (vr *verificationRegistry) Provision(path string) (string, error) {
var candidate string
buff := make([]byte, 32) // 256 bits of entropy should be enough.
found := false
for i := 0; i < 10; i++ {
_, err := rand.Read(buff)
if err != nil {
return "", fmt.Errorf("random generation failed; %w", err)
}
candidate = ".sewer_" + base64.RawURLEncoding.EncodeToString(buff)
_, err = os.Stat(filepath.Join(path, candidate))
if err != nil {
if errors.Is(err, os.ErrNotExist) {
found = true
break
} else if errors.Is(err, os.ErrPermission) {
return "", newHttpError(http.StatusBadRequest, fmt.Errorf("path is not accessible; %w", err))
} else {
return "", fmt.Errorf("failed to inspect path; %w", err)
}
}
}
if !found {
return "", errors.New("exhausted attempts")
}
vr.Lock.Lock()
defer vr.Lock.Unlock()
vr.Sessions[path] = verificationSession{
Code: candidate,
Created: time.Now(),
}
// Automatically deleting it after some time has expired.
go func() {
time.Sleep(vr.Lifespan)
vr.Lock.Lock()
defer vr.Lock.Unlock()
delete(vr.Sessions, path)
}()
return candidate, nil
}
func (vr *verificationRegistry) Pop(path string) (string, bool) {
vr.Lock.Lock()
defer vr.Lock.Unlock()
found, ok := vr.Sessions[path]
if !ok {
return "", false
}
delete(vr.Sessions, path)
return found.Code, true
}