forked from raystack/frontier
-
Notifications
You must be signed in to change notification settings - Fork 0
/
service.go
103 lines (84 loc) · 2.45 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
package role
import (
"context"
"fmt"
"github.com/goto/salt/log"
"github.com/goto/shield/core/activity"
"github.com/goto/shield/core/user"
)
const (
auditKeyRoleUpsert = "role.upsert"
auditKeyRoleUpdate = "role.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) Upsert(ctx context.Context, toCreate Role) (Role, error) {
currentUser, err := s.userService.FetchCurrentUser(ctx)
if err != nil {
return Role{}, err
}
roleID, err := s.repository.Upsert(ctx, toCreate)
if err != nil {
return Role{}, err
}
newRole, err := s.repository.Get(ctx, roleID)
if err != nil {
return Role{}, err
}
go func() {
ctx := context.WithoutCancel(ctx)
roleLogData := newRole.ToLogData()
actor := activity.Actor{ID: currentUser.ID, Email: currentUser.Email}
if err := s.activityService.Log(ctx, auditKeyRoleUpsert, actor, roleLogData); err != nil {
s.logger.Error(fmt.Sprintf("%s: %s", ErrLogActivity.Error(), err.Error()))
}
}()
return newRole, nil
}
func (s Service) Get(ctx context.Context, id string) (Role, error) {
return s.repository.Get(ctx, id)
}
func (s Service) List(ctx context.Context) ([]Role, error) {
return s.repository.List(ctx)
}
func (s Service) Update(ctx context.Context, toUpdate Role) (Role, error) {
currentUser, err := s.userService.FetchCurrentUser(ctx)
if err != nil {
return Role{}, err
}
roleID, err := s.repository.Update(ctx, toUpdate)
if err != nil {
return Role{}, err
}
updatedRole, err := s.repository.Get(ctx, roleID)
if err != nil {
return Role{}, err
}
go func() {
ctx := context.WithoutCancel(ctx)
roleLogData := updatedRole.ToLogData()
actor := activity.Actor{ID: currentUser.ID, Email: currentUser.Email}
if err := s.activityService.Log(ctx, auditKeyRoleUpdate, actor, roleLogData); err != nil {
s.logger.Error(fmt.Sprintf("%s: %s", ErrLogActivity.Error(), err.Error()))
}
}()
return updatedRole, nil
}