-
Notifications
You must be signed in to change notification settings - Fork 402
/
apikeys.go
81 lines (66 loc) · 1.97 KB
/
apikeys.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
// Copyright (C) 2019 Storj Labs, Inc.
// See LICENSE for copying information.
package console
import (
"context"
"crypto/rand"
"encoding/base32"
"io"
"time"
"github.com/skyrings/skyring-common/tools/uuid"
"github.com/zeebo/errs"
)
// APIKeys is interface for working with api keys store
type APIKeys interface {
// GetByProjectID retrieves list of APIKeys for given projectID
GetByProjectID(ctx context.Context, projectID uuid.UUID) ([]APIKeyInfo, error)
// Get retrieves APIKeyInfo with given ID
Get(ctx context.Context, id uuid.UUID) (*APIKeyInfo, error)
//GetByKey retrieves APIKeyInfo for given key
GetByKey(ctx context.Context, key APIKey) (*APIKeyInfo, error)
// Create creates and stores new APIKeyInfo
Create(ctx context.Context, key APIKey, info APIKeyInfo) (*APIKeyInfo, error)
// Update updates APIKeyInfo in store
Update(ctx context.Context, key APIKeyInfo) error
// Delete deletes APIKeyInfo from store
Delete(ctx context.Context, id uuid.UUID) error
}
// APIKeyInfo describing api key model in the database
type APIKeyInfo struct {
ID uuid.UUID `json:"id"`
// Fk on project
ProjectID uuid.UUID `json:"projectId"`
Name string `json:"name"`
CreatedAt time.Time `json:"createdAt"`
}
// APIKey is an api key type
type APIKey [24]byte
// String implements Stringer
func (key APIKey) String() string {
return base32.HexEncoding.EncodeToString(key[:])
}
// APIKeyFromBytes creates new key from byte slice
func APIKeyFromBytes(b []byte) *APIKey {
key := new(APIKey)
copy(key[:], b)
return key
}
// APIKeyFromBase32 creates new key from base32 string
func APIKeyFromBase32(s string) (*APIKey, error) {
b, err := base32.HexEncoding.DecodeString(s)
if err != nil {
return nil, err
}
key := new(APIKey)
copy(key[:], b)
return key, nil
}
// CreateAPIKey creates new api key
func CreateAPIKey() (*APIKey, error) {
key := new(APIKey)
n, err := io.ReadFull(rand.Reader, key[:])
if err != nil || n != 24 {
return nil, errs.New(internalErrMsg)
}
return key, nil
}