forked from raystack/frontier
-
Notifications
You must be signed in to change notification settings - Fork 0
/
service.go
100 lines (82 loc) · 2.49 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
package policy
import (
"context"
"fmt"
"github.com/goto/salt/log"
"github.com/goto/shield/core/user"
pkgctx "github.com/goto/shield/pkg/context"
)
const (
auditKeyPolicyCreate = "policy.create"
auditKeyPolicyUpdate = "policy.update"
)
type UserService interface {
FetchCurrentUser(ctx context.Context) (user.User, error)
}
type ActivityService interface {
Log(ctx context.Context, action string, actor string, 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) Create(ctx context.Context, policy Policy) ([]Policy, error) {
currentUser, err := s.userService.FetchCurrentUser(ctx)
if err != nil {
s.logger.Error(fmt.Sprintf("%s: %s", user.ErrInvalidEmail.Error(), err.Error()))
}
policyId, err := s.repository.Create(ctx, policy)
if err != nil {
return []Policy{}, err
}
policies, err := s.repository.List(ctx)
if err != nil {
return []Policy{}, err
}
go func() {
ctx := pkgctx.WithoutCancel(ctx)
policyLogData := policy.ToPolicyLogData(policyId)
if err := s.activityService.Log(ctx, auditKeyPolicyCreate, currentUser.ID, 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 {
s.logger.Error(fmt.Sprintf("%s: %s", user.ErrInvalidEmail.Error(), err.Error()))
}
policyId, err := s.repository.Update(ctx, pol)
if err != nil {
return []Policy{}, err
}
policies, err := s.repository.List(ctx)
if err != nil {
return []Policy{}, err
}
go func() {
ctx := pkgctx.WithoutCancel(ctx)
policyLogData := pol.ToPolicyLogData(policyId)
if err := s.activityService.Log(ctx, auditKeyPolicyUpdate, currentUser.ID, policyLogData); err != nil {
s.logger.Error(fmt.Sprintf("%s: %s", ErrLogActivity.Error(), err.Error()))
}
}()
return policies, err
}