-
Notifications
You must be signed in to change notification settings - Fork 3
/
repository_invitations.go
110 lines (88 loc) · 2.49 KB
/
repository_invitations.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
package auth
import (
"encoding/json"
"time"
"github.com/boreq/eggplant/application/auth"
"github.com/boreq/eggplant/logging"
"github.com/boreq/errors"
bolt "go.etcd.io/bbolt"
)
const maxInvitationAge = 48 * time.Hour
type InvitationRepository struct {
tx *bolt.Tx
bucket []byte
log logging.Logger
}
func NewInvitationRepository(tx *bolt.Tx) (*InvitationRepository, error) {
bucket := []byte("invitations")
if tx.Writable() {
if _, err := tx.CreateBucketIfNotExists(bucket); err != nil {
return nil, errors.Wrap(err, "could not create a bucket")
}
}
return &InvitationRepository{
tx: tx,
bucket: bucket,
log: logging.New("InvitationRepository"),
}, nil
}
func (r *InvitationRepository) Put(invitation auth.Invitation) error {
j, err := json.Marshal(invitation)
if err != nil {
return errors.Wrap(err, "marshaling to json failed")
}
b := r.tx.Bucket(r.bucket)
if b == nil {
return errors.New("bucket does not exist")
}
if err := r.removeOldInvitations(b); err != nil {
return errors.Wrap(err, "could not remove old invitations")
}
return b.Put([]byte(invitation.Token), j)
}
func (r *InvitationRepository) Get(token auth.InvitationToken) (*auth.Invitation, error) {
b := r.tx.Bucket(r.bucket)
if b == nil {
return nil, errors.Wrap(auth.ErrNotFound, "bucket does not exist")
}
j := b.Get([]byte(token))
if j == nil {
return nil, auth.ErrNotFound
}
invitation := &auth.Invitation{}
if err := json.Unmarshal(j, invitation); err != nil {
return nil, errors.Wrap(err, "json unmarshal failed")
}
if time.Now().After(invitation.Created.Add(maxInvitationAge)) {
return nil, auth.ErrNotFound
}
return invitation, nil
}
func (r *InvitationRepository) Remove(token auth.InvitationToken) error {
b := r.tx.Bucket(r.bucket)
if b == nil {
return errors.New("bucket does not exist")
}
return b.Delete([]byte(token))
}
func (r *InvitationRepository) removeOldInvitations(b *bolt.Bucket) error {
var keysToRemove [][]byte
if err := b.ForEach(func(key, value []byte) error {
invitation := &auth.Invitation{}
if err := json.Unmarshal(value, invitation); err != nil {
return errors.Wrap(err, "json unmarshal failed")
}
if time.Now().After(invitation.Created.Add(maxInvitationAge)) {
keysToRemove = append(keysToRemove, nil)
}
return nil
}); err != nil {
return errors.Wrap(err, "for each failed")
}
for _, key := range keysToRemove {
if err := b.Delete(key); err != nil {
return errors.Wrap(err, "delete failed")
}
}
return nil
}