-
Notifications
You must be signed in to change notification settings - Fork 397
/
service.go
76 lines (62 loc) · 1.74 KB
/
service.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
// Copyright (C) 2019 Storj Labs, Inc.
// See LICENSE for copying information.
package authorization
import (
"context"
"fmt"
"github.com/zeebo/errs"
"go.uber.org/zap"
)
// ErrService is the default error class for the authorization service.
var ErrService = errs.Class("authorization service error")
// Service is the authorization service.
type Service struct {
log *zap.Logger
db *DB
}
// NewService creates a new authorization service.
func NewService(log *zap.Logger, db *DB) *Service {
return &Service{
log: log,
db: db,
}
}
// GetOrCreate will return an authorization for the given user ID.
func (service *Service) GetOrCreate(ctx context.Context, userID string) (_ *Token, err error) {
defer mon.Task()(&ctx)(&err)
if userID == "" {
msg := "missing user ID"
err = ErrService.New(msg)
return nil, err
}
existingGroup, err := service.db.Get(ctx, userID)
if err != nil && !ErrNotFound.Has(err) {
msg := "error getting authorizations"
err = ErrService.Wrap(err)
service.log.Error(msg, zap.Error(err))
return nil, err
}
if existingGroup != nil && len(existingGroup) > 0 {
for _, authorization := range existingGroup {
if authorization.Claim == nil {
return &authorization.Token, nil
}
}
}
createdGroup, err := service.db.Create(ctx, userID, 1)
if err != nil {
msg := "error creating authorization"
err = ErrService.Wrap(err)
service.log.Error(msg, zap.Error(err))
return nil, err
}
groupLen := len(createdGroup)
if groupLen != 1 {
clientMsg := "error creating authorization"
internalMsg := clientMsg + fmt.Sprintf("; expected 1, got %d", groupLen)
service.log.Error(internalMsg)
return nil, ErrEndpoint.New("%s", clientMsg)
}
authorization := createdGroup[0]
return &authorization.Token, nil
}