zitadel/internal/v2/repository/member/event_changed.go

80 lines
1.5 KiB
Go
Raw Normal View History

2020-11-06 21:09:19 +00:00
package member
import (
"encoding/json"
2020-11-18 20:22:15 +00:00
"reflect"
"sort"
"github.com/caos/zitadel/internal/errors"
2020-11-06 21:09:19 +00:00
"github.com/caos/zitadel/internal/eventstore/v2"
"github.com/caos/zitadel/internal/eventstore/v2/repository"
2020-11-06 21:09:19 +00:00
)
2020-11-11 16:51:44 +00:00
const (
ChangedEventType = "member.changed"
)
type ChangedEvent struct {
2020-11-06 21:09:19 +00:00
eventstore.BaseEvent `json:"-"`
2020-11-18 20:22:15 +00:00
Roles []string `json:"roles,omitempty"`
UserID string `json:"userId,omitempty"`
2020-11-06 21:09:19 +00:00
}
2020-11-11 16:51:44 +00:00
func (e *ChangedEvent) CheckPrevious() bool {
2020-11-06 21:09:19 +00:00
return true
}
2020-11-11 16:51:44 +00:00
func (e *ChangedEvent) Data() interface{} {
2020-11-06 21:09:19 +00:00
return e
}
2020-11-23 18:31:12 +00:00
func ChangeEventFromExisting(
2020-11-11 16:51:44 +00:00
base *eventstore.BaseEvent,
2020-11-23 18:31:12 +00:00
current *WriteModel,
roles ...string,
2020-11-18 20:22:15 +00:00
) (*ChangedEvent, error) {
2020-11-11 16:51:44 +00:00
change := NewChangedEvent(base, current.UserID)
2020-11-25 19:04:32 +00:00
hasChanged := false
2020-11-18 20:22:15 +00:00
sort.Strings(current.Roles)
2020-11-23 18:31:12 +00:00
sort.Strings(roles)
if !reflect.DeepEqual(current.Roles, roles) {
change.Roles = roles
2020-11-25 19:04:32 +00:00
hasChanged = true
2020-11-18 20:22:15 +00:00
}
2020-11-25 19:04:32 +00:00
if !hasChanged {
2020-11-18 20:22:15 +00:00
return nil, errors.ThrowPreconditionFailed(nil, "MEMBE-SeKlD", "Errors.NoChanges")
}
return change, nil
2020-11-23 18:31:12 +00:00
}
2020-11-18 20:22:15 +00:00
2020-11-23 18:31:12 +00:00
func NewChangedEvent(
base *eventstore.BaseEvent,
userID string,
roles ...string,
) *ChangedEvent {
return &ChangedEvent{
BaseEvent: *base,
UserID: userID,
Roles: roles,
}
2020-11-06 21:09:19 +00:00
}
func ChangedEventMapper(event *repository.Event) (eventstore.EventReader, error) {
e := &ChangedEvent{
BaseEvent: *eventstore.BaseEventFromRepo(event),
}
err := json.Unmarshal(event.Data, e)
if err != nil {
return nil, errors.ThrowInternal(err, "POLIC-puqv4", "unable to unmarshal label policy")
}
return e, nil
}