forked from raystack/frontier
-
Notifications
You must be signed in to change notification settings - Fork 0
/
service.go
105 lines (86 loc) · 2.5 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
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
package policy
import (
"context"
"fmt"
"github.com/goto/salt/log"
"github.com/goto/shield/core/activity"
"github.com/goto/shield/core/user"
)
const (
auditKeyPolicyUpsert = "policy.upsert"
auditKeyPolicyUpdate = "policy.update"
)
type UserService interface {
FetchCurrentUser(ctx context.Context) (user.User, error)
}
type ActivityService interface {
Log(ctx context.Context, action string, actor activity.Actor, data any) error
}
type Service struct {
logger log.Logger
repository Repository
userService UserService
activityService ActivityService
}
func NewService(logger log.Logger, repository Repository, userService UserService, activityService ActivityService) *Service {
return &Service{
logger: logger,
repository: repository,
userService: userService,
activityService: activityService,
}
}
func (s Service) Get(ctx context.Context, id string) (Policy, error) {
return s.repository.Get(ctx, id)
}
func (s Service) List(ctx context.Context) ([]Policy, error) {
return s.repository.List(ctx)
}
func (s Service) Upsert(ctx context.Context, pol *Policy) ([]Policy, error) {
currentUser, err := s.userService.FetchCurrentUser(ctx)
if err != nil {
return []Policy{}, err
}
policyID, err := s.repository.Upsert(ctx, pol)
if err != nil {
return []Policy{}, err
}
pol.ID = policyID
policies, err := s.repository.List(ctx)
if err != nil {
return []Policy{}, err
}
go func() {
ctx := context.WithoutCancel(ctx)
policyLogData := pol.ToLogData()
actor := activity.Actor{ID: currentUser.ID, Email: currentUser.Email}
if err := s.activityService.Log(ctx, auditKeyPolicyUpsert, actor, policyLogData); err != nil {
s.logger.Error(fmt.Sprintf("%s: %s", ErrLogActivity.Error(), err.Error()))
}
}()
return policies, err
}
func (s Service) Update(ctx context.Context, pol *Policy) ([]Policy, error) {
currentUser, err := s.userService.FetchCurrentUser(ctx)
if err != nil {
return []Policy{}, err
}
policyID, err := s.repository.Update(ctx, pol)
if err != nil {
return []Policy{}, err
}
pol.ID = policyID
policies, err := s.repository.List(ctx)
if err != nil {
return []Policy{}, err
}
go func() {
ctx := context.WithoutCancel(ctx)
policyLogData := pol.ToLogData()
actor := activity.Actor{ID: currentUser.ID, Email: currentUser.Email}
if err := s.activityService.Log(ctx, auditKeyPolicyUpdate, actor, policyLogData); err != nil {
s.logger.Error(fmt.Sprintf("%s: %s", ErrLogActivity.Error(), err.Error()))
}
}()
return policies, err
}