User view (#94)

* fix: some funcitons

* feat(eventstore): implemented push events

* fix: move project eventstore to project package

* fix: change project eventstore funcs

* feat(eventstore): overwrite context data

* fix: change project eventstore

* fix: add project repo to mgmt server

* feat(types): SQL-config

* fix: commented code

* feat(eventstore): options to overwrite editor

* feat: auth interceptor and cockroach migrations

* fix: migrations

* fix: fix filter

* fix: not found on getbyid

* fix: use global sql config

* fix: add sequence

* fix: add some tests

* fix(eventstore): nullable sequence

* fix: add some tests

* merge

* fix: add some tests

* fix(migrations): correct statements for sequence

* fix: add some tests

* fix: add some tests

* fix: changes from mr

* fix: changes from mr

* fix: add some tests

* Update internal/eventstore/models/field.go

Co-Authored-By: livio-a <livio.a@gmail.com>

* fix(eventstore): code quality

* fix: add types to aggregate/Event-types

* fix: try tests

* fix(eventstore): rename modifier* to editor*

* fix(eventstore): delete editor_org

* fix(migrations): remove editor_org field,
rename modifier_* to editor_*

* fix: query tests

* fix: use prepare funcs

* fix: go mod

* fix: generate files

* fix(eventstore): tests

* fix(eventstore): rename modifier to editor

* fix(migrations): add cluster migration,
fix(migrations): fix typo of host in clean clsuter

* fix(eventstore): move health

* fix(eventstore): AggregateTypeFilter aggregateType as param

* code quality

* fix: go tests

* feat: add member funcs

* feat: add member model

* feat: add member events

* feat: add member repo model

* fix: better error func testing

* fix: project member funcs

* fix: add tests

* fix: add tests

* feat: implement member requests

* fix: merge master

* fix: merge master

* fix: read existing in project repo

* fix: fix tests

* feat: add internal cache

* feat: add cache mock

* fix: return values of cache mock

* feat: add project role

* fix: add cache config

* fix: add role to eventstore

* fix: use eventstore sdk

* fix: use eventstore sdk

* fix: add project role grpc requests

* fix: fix getby id

* fix: changes for mr

* fix: change value to interface

* feat: add app event creations

* fix: searchmethods

* Update internal/project/model/project_member.go

Co-Authored-By: Silvan <silvan.reusser@gmail.com>

* fix: use get project func

* fix: append events

* fix: check if value is string on equal ignore case

* fix: add changes test

* fix: add go mod

* fix: add some tests

* fix: return err not nil

* fix: return err not nil

* fix: add aggregate funcs and tests

* fix: add oidc aggregate funcs and tests

* fix: add oidc

* fix: add some tests

* fix: tests

* fix: oidc validation

* fix: generate client secret

* fix: generate client id

* fix: test change app

* fix: deactivate/reactivate application

* fix: change oidc config

* fix: change oidc config secret

* fix: implement grpc app funcs

* fix: add application requests

* fix: converter

* fix: converter

* fix: converter and generate clientid

* fix: tests

* feat: project grant aggregate

* feat: project grant

* fix: project grant check if role existing

* fix: project grant requests

* fix: project grant fixes

* fix: project grant member model

* fix: project grant member aggregate

* fix: project grant member eventstore

* fix: project grant member requests

* feat: user model

* feat: user command side

* user command side

* profile requests

* local config with gopass and more

* init for views (spooler, handler)

* init for views (spooler, handler)

* start view in management

* granted project

* Update internal/user/model/user.go

Co-Authored-By: Livio Amstutz <livio.a@gmail.com>

* Update internal/user/repository/eventsourcing/model/address.go

Co-Authored-By: Livio Amstutz <livio.a@gmail.com>

* Update internal/user/repository/eventsourcing/model/address.go

Co-Authored-By: Livio Amstutz <livio.a@gmail.com>

* Update internal/user/repository/eventsourcing/model/email.go

Co-Authored-By: Livio Amstutz <livio.a@gmail.com>

* Update internal/user/repository/eventsourcing/model/email.go

Co-Authored-By: Livio Amstutz <livio.a@gmail.com>

* Update internal/user/repository/eventsourcing/model/email.go

Co-Authored-By: Livio Amstutz <livio.a@gmail.com>

* Update internal/user/repository/eventsourcing/model/mfa.go

Co-Authored-By: Livio Amstutz <livio.a@gmail.com>

* Update internal/user/repository/eventsourcing/model/mfa.go

Co-Authored-By: Livio Amstutz <livio.a@gmail.com>

* Update internal/user/repository/eventsourcing/model/password.go

Co-Authored-By: Livio Amstutz <livio.a@gmail.com>

* Update internal/user/repository/eventsourcing/model/password.go

Co-Authored-By: Livio Amstutz <livio.a@gmail.com>

* Update internal/user/repository/eventsourcing/model/password.go

Co-Authored-By: Livio Amstutz <livio.a@gmail.com>

* Update internal/user/repository/eventsourcing/model/phone.go

Co-Authored-By: Livio Amstutz <livio.a@gmail.com>

* Update internal/user/repository/eventsourcing/model/phone.go

Co-Authored-By: Livio Amstutz <livio.a@gmail.com>

* Update internal/user/repository/eventsourcing/model/phone.go

Co-Authored-By: Livio Amstutz <livio.a@gmail.com>

* Update internal/user/repository/eventsourcing/model/user.go

Co-Authored-By: Livio Amstutz <livio.a@gmail.com>

* Update internal/user/repository/eventsourcing/model/user.go

Co-Authored-By: Livio Amstutz <livio.a@gmail.com>

* Update internal/user/repository/eventsourcing/model/user.go

Co-Authored-By: Livio Amstutz <livio.a@gmail.com>

* Update internal/usergrant/repository/eventsourcing/model/user_grant.go

Co-Authored-By: Livio Amstutz <livio.a@gmail.com>

* Update internal/usergrant/repository/eventsourcing/model/user_grant.go

Co-Authored-By: Livio Amstutz <livio.a@gmail.com>

* Update internal/usergrant/repository/eventsourcing/user_grant.go

Co-Authored-By: Livio Amstutz <livio.a@gmail.com>

* Update internal/user/repository/eventsourcing/user_test.go

Co-Authored-By: Livio Amstutz <livio.a@gmail.com>

* Update internal/user/repository/eventsourcing/eventstore_mock_test.go

Co-Authored-By: Livio Amstutz <livio.a@gmail.com>

* changes from mr review

* save files into basedir

* changes from mr review

* changes from mr review

* implement granted project view

* Update internal/usergrant/repository/eventsourcing/cache.go

Co-authored-by: Silvan <silvan.reusser@gmail.com>

* Update internal/usergrant/repository/eventsourcing/cache.go

Co-authored-by: Silvan <silvan.reusser@gmail.com>

* changes requested on mr

* fix generate codes

* fix return if no events

* password code

* search granted projects

* fix search column

* update all projects on project change

* search roles

* filter org

* project members

* project grant members

* fix tests

* application view

* project grant search

* mock

* Update internal/user/repository/eventsourcing/model/password.go

Co-authored-by: Silvan <silvan.reusser@gmail.com>

* Update internal/user/repository/eventsourcing/model/user.go

Co-authored-by: Silvan <silvan.reusser@gmail.com>

* requests of mr

* check email

* test appendevents

* test appendevents

* Update internal/view/query.go

Co-authored-by: Livio Amstutz <livio.a@gmail.com>

* Update internal/eventstore/spooler/spooler.go

Co-authored-by: Livio Amstutz <livio.a@gmail.com>

* Update internal/view/query.go

Co-authored-by: Livio Amstutz <livio.a@gmail.com>

* merge request changes

* Update internal/project/repository/view/model/application.go

Co-authored-by: Livio Amstutz <livio.a@gmail.com>

* merge request changes

* Project view sql (#92)

* sql and configs

* error handling

* sql start in eventstore

* on error handling, config

* merge branches

* user view

* user grant view

* fix test

* user grant search

* fill data on user grant

* update data on user grant

* return caos errors

* converter list len

* merge master

* Update internal/management/repository/eventsourcing/handler/user_grant.go

Co-authored-by: Livio Amstutz <livio.a@gmail.com>

* Update internal/usergrant/repository/view/model/user_grant_query.go

Co-authored-by: Livio Amstutz <livio.a@gmail.com>

* typo

* Update internal/user/repository/view/model/user_query.go

Co-authored-by: Silvan <silvan.reusser@gmail.com>

* Update internal/user/repository/view/user_view.go

Co-authored-by: Silvan <silvan.reusser@gmail.com>

* Update pkg/management/api/grpc/user_converter.go

Co-authored-by: Silvan <silvan.reusser@gmail.com>

* Update pkg/management/api/grpc/user_grant_converter.go

Co-authored-by: Silvan <silvan.reusser@gmail.com>

* set my org query

Co-authored-by: adlerhurst <silvan.reusser@gmail.com>
Co-authored-by: livio-a <livio.a@gmail.com>
This commit is contained in:
Fabi
2020-05-12 06:30:53 +02:00
committed by GitHub
parent 6e105f662e
commit 5cbf537a91
40 changed files with 6135 additions and 3743 deletions

View File

@@ -103,7 +103,7 @@ func (s *spooledHandler) process(ctx context.Context, events []*models.Event) er
return nil
}
func HandleError(event *models.Event,
func HandleError(event *models.Event, failedErr error,
latestFailedEvent func(sequence uint64) (*global_view.FailedEvent, error),
processFailedEvent func(*global_view.FailedEvent) error,
processSequence func(uint64) error, errorCountUntilSkip uint64) error {
@@ -112,7 +112,7 @@ func HandleError(event *models.Event,
return err
}
failedEvent.FailureCount++
failedEvent.ErrMsg = err.Error()
failedEvent.ErrMsg = failedErr.Error()
err = processFailedEvent(failedEvent)
if err != nil {
return err

View File

@@ -2,12 +2,16 @@ package eventstore
import (
"context"
"github.com/caos/zitadel/internal/management/repository/eventsourcing/view"
usr_model "github.com/caos/zitadel/internal/user/model"
usr_event "github.com/caos/zitadel/internal/user/repository/eventsourcing"
"github.com/caos/zitadel/internal/user/repository/view/model"
)
type UserRepo struct {
UserEvents *usr_event.UserEventstore
SearchLimit uint64
UserEvents *usr_event.UserEventstore
View *view.View
}
func (repo *UserRepo) UserByID(ctx context.Context, id string) (project *usr_model.User, err error) {
@@ -38,6 +42,36 @@ func (repo *UserRepo) UnlockUser(ctx context.Context, id string) (*usr_model.Use
return repo.UserEvents.UnlockUser(ctx, id)
}
func (repo *UserRepo) SearchUsers(ctx context.Context, request *usr_model.UserSearchRequest) (*usr_model.UserSearchResponse, error) {
request.EnsureLimit(repo.SearchLimit)
projects, count, err := repo.View.SearchUsers(request)
if err != nil {
return nil, err
}
return &usr_model.UserSearchResponse{
Offset: request.Offset,
Limit: request.Limit,
TotalResult: uint64(count),
Result: model.UsersToModel(projects),
}, nil
}
func (repo *UserRepo) GetGlobalUserByEmail(ctx context.Context, email string) (*usr_model.UserView, error) {
user, err := repo.View.GetGlobalUserByEmail(email)
if err != nil {
return nil, err
}
return model.UserToModel(user), nil
}
func (repo *UserRepo) IsUserUnique(ctx context.Context, userName, email string) (bool, error) {
return repo.View.IsUserUnique(userName, email)
}
func (repo *UserRepo) UserMfas(ctx context.Context, userID string) ([]*usr_model.MultiFactor, error) {
return repo.View.UserMfas(userID)
}
func (repo *UserRepo) SetOneTimePassword(ctx context.Context, password *usr_model.Password) (*usr_model.Password, error) {
return repo.UserEvents.SetOneTimePassword(ctx, password)
}

View File

@@ -2,12 +2,16 @@ package eventstore
import (
"context"
"github.com/caos/zitadel/internal/management/repository/eventsourcing/view"
grant_model "github.com/caos/zitadel/internal/usergrant/model"
grant_event "github.com/caos/zitadel/internal/usergrant/repository/eventsourcing"
"github.com/caos/zitadel/internal/usergrant/repository/view/model"
)
type UserGrantRepo struct {
SearchLimit uint64
UserGrantEvents *grant_event.UserGrantEventStore
View *view.View
}
func (repo *UserGrantRepo) UserGrantByID(ctx context.Context, grantID string) (*grant_model.UserGrant, error) {
@@ -33,3 +37,17 @@ func (repo *UserGrantRepo) ReactivateUserGrant(ctx context.Context, grantID stri
func (repo *UserGrantRepo) RemoveUserGrant(ctx context.Context, grantID string) error {
return repo.UserGrantEvents.RemoveUserGrant(ctx, grantID)
}
func (repo *UserGrantRepo) SearchUserGrants(ctx context.Context, request *grant_model.UserGrantSearchRequest) (*grant_model.UserGrantSearchResponse, error) {
request.EnsureLimit(repo.SearchLimit)
grants, count, err := repo.View.SearchUserGrants(request)
if err != nil {
return nil, err
}
return &grant_model.UserGrantSearchResponse{
Offset: request.Offset,
Limit: request.Limit,
TotalResult: uint64(count),
Result: model.UserGrantsToModel(grants),
}, nil
}

View File

@@ -68,7 +68,7 @@ func (p *Application) Process(event *models.Event) (err error) {
return p.view.PutApplication(app)
}
func (p *Application) OnError(event *models.Event, soolerError error) error {
logging.LogWithFields("SPOOL-ls9ew", "id", event.AggregateID).WithError(soolerError).Warn("something went wrong in project app handler")
return spooler.HandleError(event, p.view.GetLatestApplicationFailedEvent, p.view.ProcessedApplicationFailedEvent, p.view.ProcessedApplicationSequence, p.errorCountUntilSkip)
func (p *Application) OnError(event *models.Event, spoolerError error) error {
logging.LogWithFields("SPOOL-ls9ew", "id", event.AggregateID).WithError(spoolerError).Warn("something went wrong in project app handler")
return spooler.HandleError(event, spoolerError, p.view.GetLatestApplicationFailedEvent, p.view.ProcessedApplicationFailedEvent, p.view.ProcessedApplicationSequence, p.errorCountUntilSkip)
}

View File

@@ -121,5 +121,5 @@ func (p *GrantedProject) updateExistingProjects(project *view_model.GrantedProje
func (p *GrantedProject) OnError(event *models.Event, err error) error {
logging.LogWithFields("SPOOL-is8wa", "id", event.AggregateID).WithError(err).Warn("something went wrong in granted projecthandler")
return spooler.HandleError(event, p.view.GetLatestGrantedProjectFailedEvent, p.view.ProcessedGrantedProjectFailedEvent, p.view.ProcessedGrantedProjectSequence, p.errorCountUntilSkip)
return spooler.HandleError(event, err, p.view.GetLatestGrantedProjectFailedEvent, p.view.ProcessedGrantedProjectFailedEvent, p.view.ProcessedGrantedProjectSequence, p.errorCountUntilSkip)
}

View File

@@ -5,6 +5,7 @@ import (
"github.com/caos/zitadel/internal/eventstore/spooler"
"github.com/caos/zitadel/internal/management/repository/eventsourcing/view"
proj_event "github.com/caos/zitadel/internal/project/repository/eventsourcing"
usr_event "github.com/caos/zitadel/internal/user/repository/eventsourcing"
"time"
)
@@ -23,6 +24,7 @@ type handler struct {
type EventstoreRepos struct {
ProjectEvents *proj_event.ProjectEventstore
UserEvents *usr_event.UserEventstore
}
func Register(configs Configs, bulkLimit, errorCount uint64, view *view.View, eventstore eventstore.Eventstore, repos EventstoreRepos) []spooler.Handler {
@@ -32,6 +34,8 @@ func Register(configs Configs, bulkLimit, errorCount uint64, view *view.View, ev
&ProjectMember{handler: handler{view, bulkLimit, configs.cycleDuration("ProjectMember"), errorCount}},
&ProjectGrantMember{handler: handler{view, bulkLimit, configs.cycleDuration("ProjectGrantMember"), errorCount}},
&Application{handler: handler{view, bulkLimit, configs.cycleDuration("Application"), errorCount}},
&User{handler: handler{view, bulkLimit, configs.cycleDuration("User"), errorCount}},
&UserGrant{handler: handler{view, bulkLimit, configs.cycleDuration("UserGrant"), errorCount}, projectEvents: repos.ProjectEvents, userEvents: repos.UserEvents},
}
}

View File

@@ -123,5 +123,5 @@ func (p *ProjectGrantMember) fillUserData(member *view_model.ProjectGrantMemberV
func (p *ProjectGrantMember) OnError(event *models.Event, err error) error {
logging.LogWithFields("SPOOL-kls93", "id", event.AggregateID).WithError(err).Warn("something went wrong in projectmember handler")
return spooler.HandleError(event, p.view.GetLatestProjectGrantMemberFailedEvent, p.view.ProcessedProjectGrantMemberFailedEvent, p.view.ProcessedProjectGrantMemberSequence, p.errorCountUntilSkip)
return spooler.HandleError(event, err, p.view.GetLatestProjectGrantMemberFailedEvent, p.view.ProcessedProjectGrantMemberFailedEvent, p.view.ProcessedProjectGrantMemberSequence, p.errorCountUntilSkip)
}

View File

@@ -122,5 +122,5 @@ func (p *ProjectMember) fillUserData(member *view_model.ProjectMemberView, user
}
func (p *ProjectMember) OnError(event *models.Event, err error) error {
logging.LogWithFields("SPOOL-u73es", "id", event.AggregateID).WithError(err).Warn("something went wrong in projectmember handler")
return spooler.HandleError(event, p.view.GetLatestProjectMemberFailedEvent, p.view.ProcessedProjectMemberFailedEvent, p.view.ProcessedProjectMemberSequence, p.errorCountUntilSkip)
return spooler.HandleError(event, err, p.view.GetLatestProjectMemberFailedEvent, p.view.ProcessedProjectMemberFailedEvent, p.view.ProcessedProjectMemberSequence, p.errorCountUntilSkip)
}

View File

@@ -148,5 +148,5 @@ func getRoleFromProject(roleKey string, project *proj_model.Project) *proj_model
func (p *ProjectRole) OnError(event *models.Event, err error) error {
logging.LogWithFields("SPOOL-lso9w", "id", event.AggregateID).WithError(err).Warn("something went wrong in project role handler")
return spooler.HandleError(event, p.view.GetLatestProjectRoleFailedEvent, p.view.ProcessedProjectRoleFailedEvent, p.view.ProcessedProjectRoleSequence, p.errorCountUntilSkip)
return spooler.HandleError(event, err, p.view.GetLatestProjectRoleFailedEvent, p.view.ProcessedProjectRoleFailedEvent, p.view.ProcessedProjectRoleSequence, p.errorCountUntilSkip)
}

View File

@@ -0,0 +1,77 @@
package handler
import (
es_model "github.com/caos/zitadel/internal/user/repository/eventsourcing/model"
"time"
"github.com/caos/logging"
"github.com/caos/zitadel/internal/eventstore"
"github.com/caos/zitadel/internal/eventstore/models"
"github.com/caos/zitadel/internal/eventstore/spooler"
"github.com/caos/zitadel/internal/user/repository/eventsourcing"
view_model "github.com/caos/zitadel/internal/user/repository/view/model"
)
type User struct {
handler
eventstore eventstore.Eventstore
}
const (
userTable = "management.users"
)
func (p *User) MinimumCycleDuration() time.Duration { return p.cycleDuration }
func (p *User) ViewModel() string {
return userTable
}
func (p *User) EventQuery() (*models.SearchQuery, error) {
sequence, err := p.view.GetLatestUserSequence()
if err != nil {
return nil, err
}
return eventsourcing.UserQuery(sequence), nil
}
func (p *User) Process(event *models.Event) (err error) {
user := new(view_model.UserView)
switch event.Type {
case es_model.UserAdded,
es_model.UserRegistered:
user.AppendEvent(event)
case es_model.UserProfileChanged,
es_model.UserEmailChanged,
es_model.UserEmailVerified,
es_model.UserPhoneChanged,
es_model.UserPhoneVerified,
es_model.UserAddressChanged,
es_model.UserDeactivated,
es_model.UserReactivated,
es_model.UserLocked,
es_model.UserUnlocked,
es_model.MfaOtpAdded,
es_model.MfaOtpVerified,
es_model.MfaOtpRemoved:
user, err = p.view.UserByID(event.AggregateID)
if err != nil {
return err
}
err = user.AppendEvent(event)
case es_model.UserDeleted:
err = p.view.DeleteUser(event.AggregateID, event.Sequence)
default:
return p.view.ProcessedUserSequence(event.Sequence)
}
if err != nil {
return err
}
return p.view.PutUser(user)
}
func (p *User) OnError(event *models.Event, err error) error {
logging.LogWithFields("SPOOL-is8wa", "id", event.AggregateID).WithError(err).Warn("something went wrong in user handler")
return spooler.HandleError(event, err, p.view.GetLatestUserFailedEvent, p.view.ProcessedUserFailedEvent, p.view.ProcessedUserSequence, p.errorCountUntilSkip)
}

View File

@@ -0,0 +1,169 @@
package handler
import (
"context"
es_models "github.com/caos/zitadel/internal/eventstore/models"
proj_model "github.com/caos/zitadel/internal/project/model"
proj_event "github.com/caos/zitadel/internal/project/repository/eventsourcing"
proj_es_model "github.com/caos/zitadel/internal/project/repository/eventsourcing/model"
usr_model "github.com/caos/zitadel/internal/user/model"
usr_events "github.com/caos/zitadel/internal/user/repository/eventsourcing"
usr_es_model "github.com/caos/zitadel/internal/user/repository/eventsourcing/model"
grant_es_model "github.com/caos/zitadel/internal/usergrant/repository/eventsourcing/model"
"time"
"github.com/caos/logging"
"github.com/caos/zitadel/internal/eventstore"
"github.com/caos/zitadel/internal/eventstore/models"
"github.com/caos/zitadel/internal/eventstore/spooler"
view_model "github.com/caos/zitadel/internal/usergrant/repository/view/model"
)
type UserGrant struct {
handler
eventstore eventstore.Eventstore
projectEvents *proj_event.ProjectEventstore
userEvents *usr_events.UserEventstore
}
const (
userGrantTable = "management.user_grants"
)
func (u *UserGrant) MinimumCycleDuration() time.Duration { return u.cycleDuration }
func (u *UserGrant) ViewModel() string {
return userGrantTable
}
func (u *UserGrant) EventQuery() (*models.SearchQuery, error) {
sequence, err := u.view.GetLatestUserGrantSequence()
if err != nil {
return nil, err
}
return es_models.NewSearchQuery().
AggregateTypeFilter(grant_es_model.UserGrantAggregate, usr_es_model.UserAggregate, proj_es_model.ProjectAggregate).
LatestSequenceFilter(sequence), nil
}
func (u *UserGrant) Process(event *models.Event) (err error) {
switch event.AggregateType {
case grant_es_model.UserGrantAggregate:
err = u.processUserGrant(event)
case usr_es_model.UserAggregate:
err = u.processUser(event)
case proj_es_model.ProjectAggregate:
err = u.processProject(event)
}
return err
}
func (u *UserGrant) processUserGrant(event *models.Event) (err error) {
grant := new(view_model.UserGrantView)
switch event.Type {
case grant_es_model.UserGrantAdded:
err = grant.AppendEvent(event)
if err != nil {
return err
}
err = u.fillData(grant)
case grant_es_model.UserGrantChanged,
grant_es_model.UserGrantDeactivated,
grant_es_model.UserGrantReactivated:
grant, err = u.view.UserGrantByID(event.AggregateID)
if err != nil {
return err
}
err = grant.AppendEvent(event)
case grant_es_model.UserGrantRemoved:
err = u.view.DeleteUserGrant(event.AggregateID, event.Sequence)
default:
return u.view.ProcessedUserGrantSequence(event.Sequence)
}
if err != nil {
return err
}
return u.view.PutUserGrant(grant, grant.Sequence)
}
func (u *UserGrant) processUser(event *models.Event) (err error) {
switch event.Type {
case usr_es_model.UserProfileChanged,
usr_es_model.UserEmailChanged:
grants, err := u.view.UserGrantsByUserID(event.AggregateID)
if err != nil {
return err
}
user, err := u.userEvents.UserByID(context.Background(), event.AggregateID)
if err != nil {
return err
}
for _, grant := range grants {
u.fillUserData(grant, user)
err = u.view.PutUserGrant(grant, event.Sequence)
if err != nil {
return err
}
}
default:
return u.view.ProcessedUserGrantSequence(event.Sequence)
}
return nil
}
func (u *UserGrant) processProject(event *models.Event) (err error) {
switch event.Type {
case proj_es_model.ProjectChanged:
grants, err := u.view.UserGrantsByProjectID(event.AggregateID)
if err != nil {
return err
}
project, err := u.projectEvents.ProjectByID(context.Background(), event.AggregateID)
if err != nil {
return err
}
for _, grant := range grants {
u.fillProjectData(grant, project)
return u.view.PutUserGrant(grant, event.Sequence)
}
default:
return u.view.ProcessedUserGrantSequence(event.Sequence)
}
return nil
}
func (u *UserGrant) fillData(grant *view_model.UserGrantView) (err error) {
user, err := u.userEvents.UserByID(context.Background(), grant.UserID)
if err != nil {
return err
}
u.fillUserData(grant, user)
project, err := u.projectEvents.ProjectByID(context.Background(), grant.ProjectID)
if err != nil {
return err
}
u.fillProjectData(grant, project)
u.fillOrgData(grant)
return nil
}
func (u *UserGrant) fillUserData(grant *view_model.UserGrantView, user *usr_model.User) {
grant.UserName = user.UserName
grant.FirstName = user.FirstName
grant.LastName = user.LastName
grant.Email = user.EmailAddress
}
func (u *UserGrant) fillProjectData(grant *view_model.UserGrantView, project *proj_model.Project) {
grant.ProjectName = project.Name
}
func (u *UserGrant) fillOrgData(grant *view_model.UserGrantView) {
//TODO: get ORG
}
func (u *UserGrant) OnError(event *models.Event, err error) error {
logging.LogWithFields("SPOOL-8is4s", "id", event.AggregateID).WithError(err).Warn("something went wrong in user handler")
return spooler.HandleError(event, err, u.view.GetLatestUserGrantFailedEvent, u.view.ProcessedUserGrantFailedEvent, u.view.ProcessedUserGrantSequence, u.errorCountUntilSkip)
}

View File

@@ -71,8 +71,8 @@ func Start(conf Config, systemDefaults sd.SystemDefaults) (*EsRepository, error)
return &EsRepository{
spool,
eventstore.ProjectRepo{conf.SearchLimit, project, view},
eventstore.UserRepo{user},
eventstore.UserGrantRepo{usergrant},
eventstore.UserRepo{conf.SearchLimit, user, view},
eventstore.UserGrantRepo{conf.SearchLimit, usergrant, view},
}, nil
}

View File

@@ -0,0 +1,64 @@
package view
import (
usr_model "github.com/caos/zitadel/internal/user/model"
"github.com/caos/zitadel/internal/user/repository/view"
"github.com/caos/zitadel/internal/user/repository/view/model"
global_view "github.com/caos/zitadel/internal/view"
)
const (
userTable = "management.users"
)
func (v *View) UserByID(userID string) (*model.UserView, error) {
return view.UserByID(v.Db, userTable, userID)
}
func (v *View) SearchUsers(request *usr_model.UserSearchRequest) ([]*model.UserView, int, error) {
return view.SearchUsers(v.Db, userTable, request)
}
func (v *View) GetGlobalUserByEmail(email string) (*model.UserView, error) {
return view.GetGlobalUserByEmail(v.Db, userTable, email)
}
func (v *View) IsUserUnique(userName, email string) (bool, error) {
return view.IsUserUnique(v.Db, userTable, userName, email)
}
func (v *View) UserMfas(userID string) ([]*usr_model.MultiFactor, error) {
return view.UserMfas(v.Db, userTable, userID)
}
func (v *View) PutUser(user *model.UserView) error {
err := view.PutUser(v.Db, userTable, user)
if err != nil {
return err
}
return v.ProcessedUserSequence(user.Sequence)
}
func (v *View) DeleteUser(userID string, eventSequence uint64) error {
err := view.DeleteUser(v.Db, userTable, userID)
if err != nil {
return nil
}
return v.ProcessedUserSequence(eventSequence)
}
func (v *View) GetLatestUserSequence() (uint64, error) {
return v.latestSequence(userTable)
}
func (v *View) ProcessedUserSequence(eventSequence uint64) error {
return v.saveCurrentSequence(userTable, eventSequence)
}
func (v *View) GetLatestUserFailedEvent(sequence uint64) (*global_view.FailedEvent, error) {
return v.latestFailedEvent(userTable, sequence)
}
func (v *View) ProcessedUserFailedEvent(failedEvent *global_view.FailedEvent) error {
return v.saveFailedEvent(failedEvent)
}

View File

@@ -0,0 +1,64 @@
package view
import (
grant_model "github.com/caos/zitadel/internal/usergrant/model"
"github.com/caos/zitadel/internal/usergrant/repository/view"
"github.com/caos/zitadel/internal/usergrant/repository/view/model"
global_view "github.com/caos/zitadel/internal/view"
)
const (
userGrantTable = "management.user_grants"
)
func (v *View) UserGrantByID(grantID string) (*model.UserGrantView, error) {
return view.UserGrantByID(v.Db, userGrantTable, grantID)
}
func (v *View) SearchUserGrants(request *grant_model.UserGrantSearchRequest) ([]*model.UserGrantView, int, error) {
return view.SearchUserGrants(v.Db, userGrantTable, request)
}
func (v *View) UserGrantsByUserID(userID string) ([]*model.UserGrantView, error) {
return view.UserGrantsByUserID(v.Db, userGrantTable, userID)
}
func (v *View) UserGrantsByProjectID(projectID string) ([]*model.UserGrantView, error) {
return view.UserGrantsByProjectID(v.Db, userGrantTable, projectID)
}
func (v *View) UserGrantsByOrgID(orgID string) ([]*model.UserGrantView, error) {
return view.UserGrantsByOrgID(v.Db, userGrantTable, orgID)
}
func (v *View) PutUserGrant(grant *model.UserGrantView, sequence uint64) error {
err := view.PutUserGrant(v.Db, userGrantTable, grant)
if err != nil {
return err
}
return v.ProcessedUserGrantSequence(sequence)
}
func (v *View) DeleteUserGrant(grantID string, eventSequence uint64) error {
err := view.DeleteUserGrant(v.Db, userGrantTable, grantID)
if err != nil {
return nil
}
return v.ProcessedUserGrantSequence(eventSequence)
}
func (v *View) GetLatestUserGrantSequence() (uint64, error) {
return v.latestSequence(userGrantTable)
}
func (v *View) ProcessedUserGrantSequence(eventSequence uint64) error {
return v.saveCurrentSequence(userGrantTable, eventSequence)
}
func (v *View) GetLatestUserGrantFailedEvent(sequence uint64) (*global_view.FailedEvent, error) {
return v.latestFailedEvent(userGrantTable, sequence)
}
func (v *View) ProcessedUserGrantFailedEvent(failedEvent *global_view.FailedEvent) error {
return v.saveFailedEvent(failedEvent)
}

View File

@@ -13,6 +13,10 @@ type UserRepository interface {
ReactivateUser(ctx context.Context, id string) (*model.User, error)
LockUser(ctx context.Context, id string) (*model.User, error)
UnlockUser(ctx context.Context, id string) (*model.User, error)
SearchUsers(ctx context.Context, request *model.UserSearchRequest) (*model.UserSearchResponse, error)
GetGlobalUserByEmail(ctx context.Context, email string) (*model.UserView, error)
IsUserUnique(ctx context.Context, userName, email string) (bool, error)
UserMfas(ctx context.Context, userID string) ([]*model.MultiFactor, error)
SetOneTimePassword(ctx context.Context, password *model.Password) (*model.Password, error)
RequestSetPassword(ctx context.Context, id string, notifyType model.NotificationType) error

View File

@@ -12,4 +12,5 @@ type UserGrantRepository interface {
DeactivateUserGrant(ctx context.Context, grantID string) (*model.UserGrant, error)
ReactivateUserGrant(ctx context.Context, grantID string) (*model.UserGrant, error)
RemoveUserGrant(ctx context.Context, grantID string) error
SearchUserGrants(ctx context.Context, request *model.UserGrantSearchRequest) (*model.UserGrantSearchResponse, error)
}

View File

@@ -1,9 +1,6 @@
package model
import (
"context"
"github.com/caos/zitadel/internal/api"
grpc_util "github.com/caos/zitadel/internal/api/grpc"
"github.com/caos/zitadel/internal/model"
"time"
)
@@ -63,18 +60,15 @@ type GrantedProjectSearchResponse struct {
Result []*GrantedProjectView
}
func (r *GrantedProjectSearchRequest) AppendMyOrgQuery(ctx context.Context) {
orgID := grpc_util.GetHeader(ctx, api.ZitadelOrgID)
func (r *GrantedProjectSearchRequest) AppendMyOrgQuery(orgID string) {
r.Queries = append(r.Queries, &GrantedProjectSearchQuery{Key: GRANTEDPROJECTSEARCHKEY_ORGID, Method: model.SEARCHMETHOD_EQUALS, Value: orgID})
}
func (r *GrantedProjectSearchRequest) AppendNotMyOrgQuery(ctx context.Context) {
orgID := grpc_util.GetHeader(ctx, api.ZitadelOrgID)
func (r *GrantedProjectSearchRequest) AppendNotMyOrgQuery(orgID string) {
r.Queries = append(r.Queries, &GrantedProjectSearchQuery{Key: GRANTEDPROJECTSEARCHKEY_ORGID, Method: model.SEARCHMETHOD_NOT_EQUALS, Value: orgID})
}
func (r *GrantedProjectSearchRequest) AppendMyResourceOwnerQuery(ctx context.Context) {
orgID := grpc_util.GetHeader(ctx, api.ZitadelOrgID)
func (r *GrantedProjectSearchRequest) AppendMyResourceOwnerQuery(orgID string) {
r.Queries = append(r.Queries, &GrantedProjectSearchQuery{Key: GRANTEDPROJECTSEARCHKEY_RESOURCE_OWNER, Method: model.SEARCHMETHOD_EQUALS, Value: orgID})
}

View File

@@ -1,9 +1,6 @@
package model
import (
"context"
"github.com/caos/zitadel/internal/api"
grpc_util "github.com/caos/zitadel/internal/api/grpc"
"github.com/caos/zitadel/internal/model"
"time"
)
@@ -51,8 +48,7 @@ type ProjectRoleSearchResponse struct {
Result []*ProjectRoleView
}
func (r *ProjectRoleSearchRequest) AppendMyOrgQuery(ctx context.Context) {
orgID := grpc_util.GetHeader(ctx, api.ZitadelOrgID)
func (r *ProjectRoleSearchRequest) AppendMyOrgQuery(orgID string) {
r.Queries = append(r.Queries, &ProjectRoleSearchQuery{Key: PROJECTROLESEARCHKEY_ORGID, Method: model.SEARCHMETHOD_EQUALS, Value: orgID})
}

View File

@@ -21,3 +21,16 @@ const (
MFASTATE_NOTREADY
MFASTATE_READY
)
type MultiFactor struct {
Type MFAType
State MfaState
}
type MFAType int32
const (
MFATYPE_UNSPECIFIED MFAType = iota
MFATYPE_OTP
MFATYPE_SMS
)

View File

@@ -0,0 +1,80 @@
package model
import (
"github.com/caos/zitadel/internal/model"
"time"
)
type UserView struct {
ID string
CreationDate time.Time
ChangeDate time.Time
State UserState
ResourceOwner string
PasswordChanged time.Time
LastLogin time.Time
UserName string
FirstName string
LastName string
NickName string
DisplayName string
PreferredLanguage string
Gender Gender
Email string
IsEmailVerified bool
Phone string
IsPhoneVerified bool
Country string
Locality string
PostalCode string
Region string
StreetAddress string
OTPState MfaState
Sequence uint64
}
type UserSearchRequest struct {
Offset uint64
Limit uint64
SortingColumn UserSearchKey
Asc bool
Queries []*UserSearchQuery
}
type UserSearchKey int32
const (
USERSEARCHKEY_UNSPECIFIED UserSearchKey = iota
USERSEARCHKEY_USER_ID
USERSEARCHKEY_USER_NAME
USERSEARCHKEY_FIRST_NAME
USERSEARCHKEY_LAST_NAME
USERSEARCHKEY_NICK_NAME
USERSEARCHKEY_DISPLAY_NAME
USERSEARCHKEY_EMAIL
USERSEARCHKEY_STATE
USERSEARCHKEY_RESOURCEOWNER
)
type UserSearchQuery struct {
Key UserSearchKey
Method model.SearchMethod
Value string
}
type UserSearchResponse struct {
Offset uint64
Limit uint64
TotalResult uint64
Result []*UserView
}
func (r *UserSearchRequest) EnsureLimit(limit uint64) {
if r.Limit == 0 || r.Limit > limit {
r.Limit = limit
}
}
func (r *UserSearchRequest) AppendMyOrgQuery(orgID string) {
r.Queries = append(r.Queries, &UserSearchQuery{Key: USERSEARCHKEY_RESOURCEOWNER, Method: model.SEARCHMETHOD_EQUALS, Value: orgID})
}

View File

@@ -0,0 +1,182 @@
package model
import (
"encoding/json"
"github.com/caos/logging"
caos_errs "github.com/caos/zitadel/internal/errors"
"github.com/caos/zitadel/internal/eventstore/models"
"github.com/caos/zitadel/internal/user/model"
es_model "github.com/caos/zitadel/internal/user/repository/eventsourcing/model"
"time"
)
const (
UserKeyUserID = "id"
UserKeyUserName = "user_name"
UserKeyFirstName = "first_name"
UserKeyLastName = "last_name"
UserKeyNickName = "nick_name"
UserKeyDisplayName = "display_name"
UserKeyEmail = "email"
UserKeyState = "user_state"
UserKeyResourceOwner = "resource_owner"
)
type UserView struct {
ID string `json:"-" gorm:"column:id;primary_key"`
CreationDate time.Time `json:"-" gorm:"column:creation_date"`
ChangeDate time.Time `json:"-" gorm:"column:change_date"`
ResourceOwner string `json:"-" gorm:"column:resource_owner"`
State int32 `json:"-" gorm:"column:user_state"`
PasswordChanged time.Time `json:"-" gorm:"column:password_change"`
LastLogin time.Time `json:"-" gorm:"column:last_login"`
UserName string `json:"userName" gorm:"column:user_name"`
FirstName string `json:"firstName" gorm:"column:first_name"`
LastName string `json:"lastName" gorm:"column:last_name"`
NickName string `json:"nickName" gorm:"column:nick_name"`
DisplayName string `json:"displayName" gorm:"column:display_name"`
PreferredLanguage string `json:"preferredLanguage" gorm:"column:preferred_language"`
Gender int32 `json:"gender" gorm:"column:gender"`
Email string `json:"email" gorm:"column:email"`
IsEmailVerified bool `json:"-" gorm:"column:is_email_verified"`
Phone string `json:"phone" gorm:"column:phone"`
IsPhoneVerified bool `json:"-" gorm:"column:is_phone_verified"`
Country string `json:"country" gorm:"column:country"`
Locality string `json:"locality" gorm:"column:locality"`
PostalCode string `json:"postalCode" gorm:"column:postal_code"`
Region string `json:"region" gorm:"column:region"`
StreetAddress string `json:"streetAddress" gorm:"column:street_address"`
OTPState int32 `json:"-" gorm:"column:otp_state"`
Sequence uint64 `json:"-" gorm:"column:sequence"`
}
func UserFromModel(user *model.UserView) *UserView {
return &UserView{
ID: user.ID,
ChangeDate: user.ChangeDate,
CreationDate: user.CreationDate,
ResourceOwner: user.ResourceOwner,
State: int32(user.State),
PasswordChanged: user.PasswordChanged,
LastLogin: user.LastLogin,
UserName: user.UserName,
FirstName: user.FirstName,
LastName: user.LastName,
NickName: user.NickName,
DisplayName: user.DisplayName,
PreferredLanguage: user.PreferredLanguage,
Gender: int32(user.Gender),
Email: user.Email,
IsEmailVerified: user.IsEmailVerified,
Phone: user.Phone,
IsPhoneVerified: user.IsPhoneVerified,
Country: user.Country,
Locality: user.Locality,
PostalCode: user.PostalCode,
Region: user.Region,
StreetAddress: user.StreetAddress,
OTPState: int32(user.OTPState),
Sequence: user.Sequence,
}
}
func UserToModel(user *UserView) *model.UserView {
return &model.UserView{
ID: user.ID,
ChangeDate: user.ChangeDate,
CreationDate: user.CreationDate,
ResourceOwner: user.ResourceOwner,
State: model.UserState(user.State),
PasswordChanged: user.PasswordChanged,
LastLogin: user.LastLogin,
UserName: user.UserName,
FirstName: user.FirstName,
LastName: user.LastName,
NickName: user.NickName,
DisplayName: user.DisplayName,
PreferredLanguage: user.PreferredLanguage,
Gender: model.Gender(user.Gender),
Email: user.Email,
IsEmailVerified: user.IsEmailVerified,
Phone: user.Phone,
IsPhoneVerified: user.IsPhoneVerified,
Country: user.Country,
Locality: user.Locality,
PostalCode: user.PostalCode,
Region: user.Region,
StreetAddress: user.StreetAddress,
OTPState: model.MfaState(user.OTPState),
Sequence: user.Sequence,
}
}
func UsersToModel(users []*UserView) []*model.UserView {
result := make([]*model.UserView, len(users))
for i, p := range users {
result[i] = UserToModel(p)
}
return result
}
func (p *UserView) AppendEvent(event *models.Event) (err error) {
p.ChangeDate = event.CreationDate
p.Sequence = event.Sequence
switch event.Type {
case es_model.UserAdded,
es_model.UserRegistered:
p.CreationDate = event.CreationDate
p.setRootData(event)
err = p.setData(event)
case es_model.UserProfileChanged,
es_model.UserAddressChanged:
err = p.setData(event)
case es_model.UserEmailChanged:
p.IsEmailVerified = false
err = p.setData(event)
case es_model.UserEmailVerified:
p.IsEmailVerified = true
case es_model.UserPhoneChanged:
p.IsPhoneVerified = false
err = p.setData(event)
case es_model.UserPhoneVerified:
p.IsPhoneVerified = true
case es_model.UserDeactivated:
p.State = int32(model.USERSTATE_INACTIVE)
case es_model.UserReactivated,
es_model.UserUnlocked:
p.State = int32(model.USERSTATE_ACTIVE)
case es_model.UserLocked:
p.State = int32(model.USERSTATE_LOCKED)
case es_model.MfaOtpAdded:
p.OTPState = int32(model.MFASTATE_NOTREADY)
case es_model.MfaOtpVerified:
p.OTPState = int32(model.MFASTATE_READY)
case es_model.MfaOtpRemoved:
p.OTPState = int32(model.MFASTATE_UNSPECIFIED)
}
p.ComputeObject()
return err
}
func (u *UserView) setRootData(event *models.Event) {
u.ID = event.AggregateID
u.ResourceOwner = event.ResourceOwner
}
func (u *UserView) setData(event *models.Event) error {
if err := json.Unmarshal(event.Data, u); err != nil {
logging.Log("EVEN-lso9e").WithError(err).Error("could not unmarshal event data")
return caos_errs.ThrowInternal(nil, "MODEL-8iows", "could not unmarshal data")
}
return nil
}
func (u *UserView) ComputeObject() {
if u.State == int32(model.USERSTATE_UNSPECIFIED) || u.State == int32(model.USERSTATE_INITIAL) {
if u.IsEmailVerified {
u.State = int32(model.USERSTATE_ACTIVE)
} else {
u.State = int32(model.USERSTATE_INITIAL)
}
}
}

View File

@@ -0,0 +1,75 @@
package model
import (
global_model "github.com/caos/zitadel/internal/model"
usr_model "github.com/caos/zitadel/internal/user/model"
"github.com/caos/zitadel/internal/view"
)
type UserSearchRequest usr_model.UserSearchRequest
type UserSearchQuery usr_model.UserSearchQuery
type UserSearchKey usr_model.UserSearchKey
func (req UserSearchRequest) GetLimit() uint64 {
return req.Limit
}
func (req UserSearchRequest) GetOffset() uint64 {
return req.Offset
}
func (req UserSearchRequest) GetSortingColumn() view.ColumnKey {
if req.SortingColumn == usr_model.USERSEARCHKEY_UNSPECIFIED {
return nil
}
return UserSearchKey(req.SortingColumn)
}
func (req UserSearchRequest) GetAsc() bool {
return req.Asc
}
func (req UserSearchRequest) GetQueries() []view.SearchQuery {
result := make([]view.SearchQuery, len(req.Queries))
for i, q := range req.Queries {
result[i] = UserSearchQuery{Key: q.Key, Value: q.Value, Method: q.Method}
}
return result
}
func (req UserSearchQuery) GetKey() view.ColumnKey {
return UserSearchKey(req.Key)
}
func (req UserSearchQuery) GetMethod() global_model.SearchMethod {
return req.Method
}
func (req UserSearchQuery) GetValue() interface{} {
return req.Value
}
func (key UserSearchKey) ToColumnName() string {
switch usr_model.UserSearchKey(key) {
case usr_model.USERSEARCHKEY_USER_ID:
return UserKeyUserID
case usr_model.USERSEARCHKEY_USER_NAME:
return UserKeyUserName
case usr_model.USERSEARCHKEY_FIRST_NAME:
return UserKeyFirstName
case usr_model.USERSEARCHKEY_LAST_NAME:
return UserKeyLastName
case usr_model.USERSEARCHKEY_DISPLAY_NAME:
return UserKeyDisplayName
case usr_model.USERSEARCHKEY_NICK_NAME:
return UserKeyNickName
case usr_model.USERSEARCHKEY_EMAIL:
return UserKeyEmail
case usr_model.USERSEARCHKEY_STATE:
return UserKeyState
case usr_model.USERSEARCHKEY_RESOURCEOWNER:
return UserKeyResourceOwner
default:
return ""
}
}

View File

@@ -0,0 +1,216 @@
package model
import (
"encoding/json"
es_models "github.com/caos/zitadel/internal/eventstore/models"
"github.com/caos/zitadel/internal/user/model"
es_model "github.com/caos/zitadel/internal/user/repository/eventsourcing/model"
"testing"
)
func mockUserData(user *es_model.User) []byte {
data, _ := json.Marshal(user)
return data
}
func mockProfileData(profile *es_model.Profile) []byte {
data, _ := json.Marshal(profile)
return data
}
func mockEmailData(email *es_model.Email) []byte {
data, _ := json.Marshal(email)
return data
}
func mockPhoneData(phone *es_model.Phone) []byte {
data, _ := json.Marshal(phone)
return data
}
func mockAddressData(address *es_model.Address) []byte {
data, _ := json.Marshal(address)
return data
}
func getFullUser() *es_model.User {
return &es_model.User{
Profile: &es_model.Profile{
UserName: "UserName",
FirstName: "FirstName",
LastName: "LastName",
},
Email: &es_model.Email{
EmailAddress: "Email",
},
Phone: &es_model.Phone{
PhoneNumber: "Phone",
},
Address: &es_model.Address{
Country: "Country",
},
}
}
func TestUserAppendEvent(t *testing.T) {
type args struct {
event *es_models.Event
user *UserView
}
tests := []struct {
name string
args args
result *UserView
}{
{
name: "append added user event",
args: args{
event: &es_models.Event{AggregateID: "AggregateID", Sequence: 1, Type: es_model.UserAdded, ResourceOwner: "OrgID", Data: mockUserData(getFullUser())},
user: &UserView{},
},
result: &UserView{ID: "AggregateID", ResourceOwner: "OrgID", UserName: "UserName", FirstName: "FirstName", LastName: "LastName", Email: "Email", Phone: "Phone", Country: "Country", State: int32(model.USERSTATE_INITIAL)},
},
{
name: "append change user profile event",
args: args{
event: &es_models.Event{AggregateID: "AggregateID", Sequence: 1, Type: es_model.UserProfileChanged, ResourceOwner: "OrgID", Data: mockProfileData(&es_model.Profile{FirstName: "FirstNameChanged"})},
user: &UserView{ID: "AggregateID", ResourceOwner: "OrgID", UserName: "UserName", FirstName: "FirstName", LastName: "LastName", Email: "Email", Phone: "Phone", Country: "Country", State: int32(model.USERSTATE_INITIAL)},
},
result: &UserView{ID: "AggregateID", ResourceOwner: "OrgID", UserName: "UserName", FirstName: "FirstNameChanged", LastName: "LastName", Email: "Email", Phone: "Phone", Country: "Country", State: int32(model.USERSTATE_INITIAL)},
},
{
name: "append change user email event",
args: args{
event: &es_models.Event{AggregateID: "AggregateID", Sequence: 1, Type: es_model.UserEmailChanged, ResourceOwner: "OrgID", Data: mockEmailData(&es_model.Email{EmailAddress: "EmailChanged"})},
user: &UserView{ID: "AggregateID", ResourceOwner: "OrgID", UserName: "UserName", FirstName: "FirstName", LastName: "LastName", Email: "Email", IsEmailVerified: true, Phone: "Phone", Country: "Country", State: int32(model.USERSTATE_ACTIVE)},
},
result: &UserView{ID: "AggregateID", ResourceOwner: "OrgID", UserName: "UserName", FirstName: "FirstName", LastName: "LastName", Email: "EmailChanged", Phone: "Phone", Country: "Country", State: int32(model.USERSTATE_ACTIVE)},
},
{
name: "append verify user email event",
args: args{
event: &es_models.Event{AggregateID: "AggregateID", Sequence: 1, Type: es_model.UserEmailVerified, ResourceOwner: "OrgID"},
user: &UserView{ID: "AggregateID", ResourceOwner: "OrgID", UserName: "UserName", FirstName: "FirstName", LastName: "LastName", Email: "Email", Phone: "Phone", Country: "Country", State: int32(model.USERSTATE_INITIAL)},
},
result: &UserView{ID: "AggregateID", ResourceOwner: "OrgID", UserName: "UserName", FirstName: "FirstName", LastName: "LastName", Email: "Email", IsEmailVerified: true, Phone: "Phone", Country: "Country", State: int32(model.USERSTATE_ACTIVE)},
},
{
name: "append change user phone event",
args: args{
event: &es_models.Event{AggregateID: "AggregateID", Sequence: 1, Type: es_model.UserPhoneChanged, ResourceOwner: "OrgID", Data: mockPhoneData(&es_model.Phone{PhoneNumber: "PhoneChanged"})},
user: &UserView{ID: "AggregateID", ResourceOwner: "OrgID", UserName: "UserName", FirstName: "FirstName", LastName: "LastName", Email: "Email", IsEmailVerified: true, Phone: "Phone", Country: "Country", State: int32(model.USERSTATE_ACTIVE)},
},
result: &UserView{ID: "AggregateID", ResourceOwner: "OrgID", UserName: "UserName", FirstName: "FirstName", LastName: "LastName", Email: "Email", IsEmailVerified: true, Phone: "PhoneChanged", Country: "Country", State: int32(model.USERSTATE_ACTIVE)},
},
{
name: "append verify user phone event",
args: args{
event: &es_models.Event{AggregateID: "AggregateID", Sequence: 1, Type: es_model.UserPhoneVerified, ResourceOwner: "OrgID"},
user: &UserView{ID: "AggregateID", ResourceOwner: "OrgID", UserName: "UserName", FirstName: "FirstName", LastName: "LastName", Email: "Email", Phone: "Phone", Country: "Country", State: int32(model.USERSTATE_ACTIVE)},
},
result: &UserView{ID: "AggregateID", ResourceOwner: "OrgID", UserName: "UserName", FirstName: "FirstName", LastName: "LastName", Email: "Email", Phone: "Phone", IsPhoneVerified: true, Country: "Country", State: int32(model.USERSTATE_ACTIVE)},
},
{
name: "append change user address event",
args: args{
event: &es_models.Event{AggregateID: "AggregateID", Sequence: 1, Type: es_model.UserAddressChanged, ResourceOwner: "OrgID", Data: mockAddressData(&es_model.Address{Country: "CountryChanged"})},
user: &UserView{ID: "AggregateID", ResourceOwner: "OrgID", UserName: "UserName", FirstName: "FirstName", LastName: "LastName", Email: "Email", IsEmailVerified: true, Phone: "Phone", Country: "Country", State: int32(model.USERSTATE_ACTIVE)},
},
result: &UserView{ID: "AggregateID", ResourceOwner: "OrgID", UserName: "UserName", FirstName: "FirstName", LastName: "LastName", Email: "Email", IsEmailVerified: true, Phone: "Phone", Country: "CountryChanged", State: int32(model.USERSTATE_ACTIVE)},
},
{
name: "append user deactivate event",
args: args{
event: &es_models.Event{AggregateID: "AggregateID", Sequence: 1, Type: es_model.UserDeactivated, ResourceOwner: "OrgID"},
user: &UserView{ID: "AggregateID", ResourceOwner: "OrgID", UserName: "UserName", FirstName: "FirstName", LastName: "LastName", Email: "Email", Phone: "Phone", Country: "Country", State: int32(model.USERSTATE_ACTIVE)},
},
result: &UserView{ID: "AggregateID", ResourceOwner: "OrgID", UserName: "UserName", FirstName: "FirstName", LastName: "LastName", Email: "Email", Phone: "Phone", Country: "Country", State: int32(model.USERSTATE_INACTIVE)},
},
{
name: "append user reactivate event",
args: args{
event: &es_models.Event{AggregateID: "AggregateID", Sequence: 1, Type: es_model.UserReactivated, ResourceOwner: "OrgID"},
user: &UserView{ID: "AggregateID", ResourceOwner: "OrgID", UserName: "UserName", FirstName: "FirstName", LastName: "LastName", Email: "Email", Phone: "Phone", Country: "Country", State: int32(model.USERSTATE_INACTIVE)},
},
result: &UserView{ID: "AggregateID", ResourceOwner: "OrgID", UserName: "UserName", FirstName: "FirstName", LastName: "LastName", Email: "Email", Phone: "Phone", Country: "Country", State: int32(model.USERSTATE_ACTIVE)},
},
{
name: "append user lock event",
args: args{
event: &es_models.Event{AggregateID: "AggregateID", Sequence: 1, Type: es_model.UserLocked, ResourceOwner: "OrgID"},
user: &UserView{ID: "AggregateID", ResourceOwner: "OrgID", UserName: "UserName", FirstName: "FirstName", LastName: "LastName", Email: "Email", Phone: "Phone", Country: "Country", State: int32(model.USERSTATE_ACTIVE)},
},
result: &UserView{ID: "AggregateID", ResourceOwner: "OrgID", UserName: "UserName", FirstName: "FirstName", LastName: "LastName", Email: "Email", Phone: "Phone", Country: "Country", State: int32(model.USERSTATE_LOCKED)},
},
{
name: "append user unlock event",
args: args{
event: &es_models.Event{AggregateID: "AggregateID", Sequence: 1, Type: es_model.UserUnlocked, ResourceOwner: "OrgID"},
user: &UserView{ID: "AggregateID", ResourceOwner: "OrgID", UserName: "UserName", FirstName: "FirstName", LastName: "LastName", Email: "Email", Phone: "Phone", Country: "Country", State: int32(model.USERSTATE_LOCKED)},
},
result: &UserView{ID: "AggregateID", ResourceOwner: "OrgID", UserName: "UserName", FirstName: "FirstName", LastName: "LastName", Email: "Email", Phone: "Phone", Country: "Country", State: int32(model.USERSTATE_ACTIVE)},
},
{
name: "append user add otp event",
args: args{
event: &es_models.Event{AggregateID: "AggregateID", Sequence: 1, Type: es_model.MfaOtpAdded, ResourceOwner: "OrgID"},
user: &UserView{ID: "AggregateID", ResourceOwner: "OrgID", UserName: "UserName", FirstName: "FirstName", LastName: "LastName", Email: "Email", Phone: "Phone", Country: "Country", State: int32(model.USERSTATE_ACTIVE)},
},
result: &UserView{ID: "AggregateID", ResourceOwner: "OrgID", UserName: "UserName", FirstName: "FirstName", LastName: "LastName", Email: "Email", Phone: "Phone", Country: "Country", State: int32(model.USERSTATE_ACTIVE), OTPState: int32(model.MFASTATE_NOTREADY)},
},
{
name: "append user verify otp event",
args: args{
event: &es_models.Event{AggregateID: "AggregateID", Sequence: 1, Type: es_model.MfaOtpVerified, ResourceOwner: "OrgID"},
user: &UserView{ID: "AggregateID", ResourceOwner: "OrgID", UserName: "UserName", FirstName: "FirstName", LastName: "LastName", Email: "Email", Phone: "Phone", Country: "Country", State: int32(model.USERSTATE_ACTIVE), OTPState: int32(model.MFASTATE_NOTREADY)},
},
result: &UserView{ID: "AggregateID", ResourceOwner: "OrgID", UserName: "UserName", FirstName: "FirstName", LastName: "LastName", Email: "Email", Phone: "Phone", Country: "Country", State: int32(model.USERSTATE_ACTIVE), OTPState: int32(model.MFASTATE_READY)},
},
{
name: "append user remove otp event",
args: args{
event: &es_models.Event{AggregateID: "AggregateID", Sequence: 1, Type: es_model.MfaOtpRemoved, ResourceOwner: "OrgID"},
user: &UserView{ID: "AggregateID", ResourceOwner: "OrgID", UserName: "UserName", FirstName: "FirstName", LastName: "LastName", Email: "Email", Phone: "Phone", Country: "Country", State: int32(model.USERSTATE_ACTIVE), OTPState: int32(model.MFASTATE_READY)},
},
result: &UserView{ID: "AggregateID", ResourceOwner: "OrgID", UserName: "UserName", FirstName: "FirstName", LastName: "LastName", Email: "Email", Phone: "Phone", Country: "Country", State: int32(model.USERSTATE_ACTIVE), OTPState: int32(model.MFASTATE_UNSPECIFIED)},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
tt.args.user.AppendEvent(tt.args.event)
if tt.args.user.ID != tt.result.ID {
t.Errorf("got wrong result ID: expected: %v, actual: %v ", tt.result.ID, tt.args.user.ID)
}
if tt.args.user.FirstName != tt.result.FirstName {
t.Errorf("got wrong result FirstName: expected: %v, actual: %v ", tt.result.FirstName, tt.args.user.FirstName)
}
if tt.args.user.LastName != tt.result.LastName {
t.Errorf("got wrong result FirstName: expected: %v, actual: %v ", tt.result.FirstName, tt.args.user.FirstName)
}
if tt.args.user.ResourceOwner != tt.result.ResourceOwner {
t.Errorf("got wrong result ResourceOwner: expected: %v, actual: %v ", tt.result.ResourceOwner, tt.args.user.ResourceOwner)
}
if tt.args.user.Email != tt.result.Email {
t.Errorf("got wrong result email: expected: %v, actual: %v ", tt.result.Email, tt.args.user.Email)
}
if tt.args.user.IsEmailVerified != tt.result.IsEmailVerified {
t.Errorf("got wrong result IsEmailVerified: expected: %v, actual: %v ", tt.result.IsEmailVerified, tt.args.user.IsEmailVerified)
}
if tt.args.user.Phone != tt.result.Phone {
t.Errorf("got wrong result Phone: expected: %v, actual: %v ", tt.result.Phone, tt.args.user.Phone)
}
if tt.args.user.IsPhoneVerified != tt.result.IsPhoneVerified {
t.Errorf("got wrong result IsPhoneVerified: expected: %v, actual: %v ", tt.result.IsPhoneVerified, tt.args.user.IsPhoneVerified)
}
if tt.args.user.Country != tt.result.Country {
t.Errorf("got wrong result Country: expected: %v, actual: %v ", tt.result.Country, tt.args.user.Country)
}
if tt.args.user.State != tt.result.State {
t.Errorf("got wrong result state: expected: %v, actual: %v ", tt.result.State, tt.args.user.State)
}
if tt.args.user.OTPState != tt.result.OTPState {
t.Errorf("got wrong result OTPState: expected: %v, actual: %v ", tt.result.OTPState, tt.args.user.OTPState)
}
})
}
}

View File

@@ -0,0 +1,79 @@
package view
import (
caos_errs "github.com/caos/zitadel/internal/errors"
usr_model "github.com/caos/zitadel/internal/user/model"
"github.com/caos/zitadel/internal/user/repository/view/model"
"github.com/caos/zitadel/internal/view"
"github.com/jinzhu/gorm"
)
func UserByID(db *gorm.DB, table, userID string) (*model.UserView, error) {
user := new(model.UserView)
query := view.PrepareGetByKey(table, model.UserSearchKey(usr_model.USERSEARCHKEY_USER_ID), userID)
err := query(db, user)
return user, err
}
func UserByUserName(db *gorm.DB, table, userName string) (*model.UserView, error) {
user := new(model.UserView)
query := view.PrepareGetByKey(table, model.UserSearchKey(usr_model.USERSEARCHKEY_USER_NAME), userName)
err := query(db, user)
return user, err
}
func SearchUsers(db *gorm.DB, table string, req *usr_model.UserSearchRequest) ([]*model.UserView, int, error) {
users := make([]*model.UserView, 0)
query := view.PrepareSearchQuery(table, model.UserSearchRequest{Limit: req.Limit, Offset: req.Offset, Queries: req.Queries})
count, err := query(db, &users)
if err != nil {
return nil, 0, err
}
return users, count, nil
}
func GetGlobalUserByEmail(db *gorm.DB, table, email string) (*model.UserView, error) {
user := new(model.UserView)
query := view.PrepareGetByKey(table, model.UserSearchKey(usr_model.USERSEARCHKEY_EMAIL), email)
err := query(db, user)
return user, err
}
func IsUserUnique(db *gorm.DB, table, userName, email string) (bool, error) {
user := new(model.UserView)
query := view.PrepareGetByKey(table, model.UserSearchKey(usr_model.USERSEARCHKEY_EMAIL), email)
err := query(db, user)
if err != nil && !caos_errs.IsNotFound(err) {
return false, err
}
if user != nil {
return false, nil
}
query = view.PrepareGetByKey(table, model.UserSearchKey(usr_model.USERSEARCHKEY_USER_NAME), email)
err = query(db, user)
if err != nil && !caos_errs.IsNotFound(err) {
return false, err
}
return user == nil, nil
}
func UserMfas(db *gorm.DB, table, userID string) ([]*usr_model.MultiFactor, error) {
user, err := UserByID(db, table, userID)
if err != nil {
return nil, err
}
if user.OTPState == int32(usr_model.MFASTATE_UNSPECIFIED) {
return []*usr_model.MultiFactor{}, nil
}
return []*usr_model.MultiFactor{&usr_model.MultiFactor{Type: usr_model.MFATYPE_OTP, State: usr_model.MfaState(user.OTPState)}}, nil
}
func PutUser(db *gorm.DB, table string, project *model.UserView) error {
save := view.PrepareSave(table)
return save(db, project)
}
func DeleteUser(db *gorm.DB, table, userID string) error {
delete := view.PrepareDeleteByKey(table, model.UserSearchKey(usr_model.USERSEARCHKEY_USER_ID), userID)
return delete(db)
}

View File

@@ -0,0 +1,69 @@
package model
import (
"github.com/caos/zitadel/internal/model"
"time"
)
type UserGrantView struct {
ID string
ResourceOwner string
UserID string
ProjectID string
UserName string
FirstName string
LastName string
Email string
ProjectName string
OrgName string
OrgDomain string
RoleKeys []string
CreationDate time.Time
ChangeDate time.Time
State UserGrantState
Sequence uint64
}
type UserGrantSearchRequest struct {
Offset uint64
Limit uint64
SortingColumn UserGrantSearchKey
Asc bool
Queries []*UserGrantSearchQuery
}
type UserGrantSearchKey int32
const (
USERGRANTSEARCHKEY_UNSPECIFIED UserGrantSearchKey = iota
USERGRANTSEARCHKEY_USER_ID
USERGRANTSEARCHKEY_PROJECT_ID
USERGRANTSEARCHKEY_RESOURCEOWNER
USERGRANTSEARCHKEY_STATE
USERGRANTSEARCHKEY_GRANT_ID
)
type UserGrantSearchQuery struct {
Key UserGrantSearchKey
Method model.SearchMethod
Value string
}
type UserGrantSearchResponse struct {
Offset uint64
Limit uint64
TotalResult uint64
Result []*UserGrantView
}
func (r *UserGrantSearchRequest) EnsureLimit(limit uint64) {
if r.Limit == 0 || r.Limit > limit {
r.Limit = limit
}
}
func (r *UserGrantSearchRequest) AppendMyOrgQuery(orgID string) {
r.Queries = append(r.Queries, &UserGrantSearchQuery{Key: USERGRANTSEARCHKEY_RESOURCEOWNER, Method: model.SEARCHMETHOD_EQUALS, Value: orgID})
}

View File

@@ -0,0 +1,123 @@
package model
import (
"encoding/json"
"github.com/caos/logging"
caos_errs "github.com/caos/zitadel/internal/errors"
"github.com/caos/zitadel/internal/eventstore/models"
"github.com/caos/zitadel/internal/usergrant/model"
es_model "github.com/caos/zitadel/internal/usergrant/repository/eventsourcing/model"
"github.com/lib/pq"
"time"
)
const (
UserGrantKeyID = "id"
UserGrantKeyUserID = "user_id"
UserGrantKeyProjectID = "project_id"
UserGrantKeyResourceOwner = "resource_owner"
UserGrantKeyState = "state"
)
type UserGrantView struct {
ID string `json:"-" gorm:"column:id;primary_key"`
ResourceOwner string `json:"-" gorm:"resource_owner"`
UserID string `json:"userId" gorm:"user_id"`
ProjectID string `json:"projectId" gorm:"column:project_id"`
UserName string `json:"-" gorm:"column:user_name"`
FirstName string `json:"-" gorm:"column:first_name"`
LastName string `json:"-" gorm:"column:last_name"`
Email string `json:"-" gorm:"column:email"`
ProjectName string `json:"-" gorm:"column:project_name"`
OrgName string `json:"-" gorm:"column:org_name"`
OrgDomain string `json:"-" gorm:"column:org_domain"`
RoleKeys pq.StringArray `json:"roleKeys" gorm:"column:role_keys"`
CreationDate time.Time `json:"-" gorm:"column:creation_date"`
ChangeDate time.Time `json:"-" gorm:"column:change_date"`
State int32 `json:"-" gorm:"column:grant_state"`
Sequence uint64 `json:"-" gorm:"column:sequence"`
}
func UserGrantFromModel(grant *model.UserGrantView) *UserGrantView {
return &UserGrantView{
ID: grant.ID,
ResourceOwner: grant.ResourceOwner,
UserID: grant.UserID,
ProjectID: grant.ProjectID,
ChangeDate: grant.ChangeDate,
CreationDate: grant.CreationDate,
State: int32(grant.State),
UserName: grant.UserName,
FirstName: grant.FirstName,
LastName: grant.LastName,
Email: grant.Email,
ProjectName: grant.ProjectName,
OrgName: grant.OrgName,
OrgDomain: grant.OrgDomain,
RoleKeys: grant.RoleKeys,
Sequence: grant.Sequence,
}
}
func UserGrantToModel(grant *UserGrantView) *model.UserGrantView {
return &model.UserGrantView{
ID: grant.ID,
ResourceOwner: grant.ResourceOwner,
UserID: grant.UserID,
ProjectID: grant.ProjectID,
ChangeDate: grant.ChangeDate,
CreationDate: grant.CreationDate,
State: model.UserGrantState(grant.State),
UserName: grant.UserName,
FirstName: grant.FirstName,
LastName: grant.LastName,
Email: grant.Email,
ProjectName: grant.ProjectName,
OrgName: grant.OrgName,
OrgDomain: grant.OrgDomain,
RoleKeys: grant.RoleKeys,
Sequence: grant.Sequence,
}
}
func UserGrantsToModel(grants []*UserGrantView) []*model.UserGrantView {
result := make([]*model.UserGrantView, len(grants))
for i, g := range grants {
result[i] = UserGrantToModel(g)
}
return result
}
func (g *UserGrantView) AppendEvent(event *models.Event) (err error) {
g.ChangeDate = event.CreationDate
g.Sequence = event.Sequence
switch event.Type {
case es_model.UserGrantAdded:
g.State = int32(model.USERGRANTSTATE_ACTIVE)
g.CreationDate = event.CreationDate
g.setRootData(event)
err = g.setData(event)
case es_model.UserGrantChanged:
err = g.setData(event)
case es_model.UserGrantDeactivated:
g.State = int32(model.USERGRANTSTATE_INACTIVE)
case es_model.UserGrantReactivated:
g.State = int32(model.USERGRANTSTATE_ACTIVE)
}
return err
}
func (u *UserGrantView) setRootData(event *models.Event) {
u.ID = event.AggregateID
u.ResourceOwner = event.ResourceOwner
}
func (u *UserGrantView) setData(event *models.Event) error {
if err := json.Unmarshal(event.Data, u); err != nil {
logging.Log("EVEN-l9sw4").WithError(err).Error("could not unmarshal event data")
return caos_errs.ThrowInternal(nil, "MODEL-7xhke", "could not unmarshal data")
}
return nil
}

View File

@@ -0,0 +1,67 @@
package model
import (
global_model "github.com/caos/zitadel/internal/model"
grant_model "github.com/caos/zitadel/internal/usergrant/model"
"github.com/caos/zitadel/internal/view"
)
type UserGrantSearchRequest grant_model.UserGrantSearchRequest
type UserGrantSearchQuery grant_model.UserGrantSearchQuery
type UserGrantSearchKey grant_model.UserGrantSearchKey
func (req UserGrantSearchRequest) GetLimit() uint64 {
return req.Limit
}
func (req UserGrantSearchRequest) GetOffset() uint64 {
return req.Offset
}
func (req UserGrantSearchRequest) GetSortingColumn() view.ColumnKey {
if req.SortingColumn == grant_model.USERGRANTSEARCHKEY_UNSPECIFIED {
return nil
}
return UserGrantSearchKey(req.SortingColumn)
}
func (req UserGrantSearchRequest) GetAsc() bool {
return req.Asc
}
func (req UserGrantSearchRequest) GetQueries() []view.SearchQuery {
result := make([]view.SearchQuery, len(req.Queries))
for i, q := range req.Queries {
result[i] = UserGrantSearchQuery{Key: q.Key, Value: q.Value, Method: q.Method}
}
return result
}
func (req UserGrantSearchQuery) GetKey() view.ColumnKey {
return UserGrantSearchKey(req.Key)
}
func (req UserGrantSearchQuery) GetMethod() global_model.SearchMethod {
return req.Method
}
func (req UserGrantSearchQuery) GetValue() interface{} {
return req.Value
}
func (key UserGrantSearchKey) ToColumnName() string {
switch grant_model.UserGrantSearchKey(key) {
case grant_model.USERGRANTSEARCHKEY_USER_ID:
return UserGrantKeyUserID
case grant_model.USERGRANTSEARCHKEY_PROJECT_ID:
return UserGrantKeyProjectID
case grant_model.USERGRANTSEARCHKEY_STATE:
return UserGrantKeyState
case grant_model.USERGRANTSEARCHKEY_RESOURCEOWNER:
return UserGrantKeyResourceOwner
case grant_model.USERGRANTSEARCHKEY_GRANT_ID:
return UserGrantKeyID
default:
return ""
}
}

View File

@@ -0,0 +1,81 @@
package model
import (
"encoding/json"
es_models "github.com/caos/zitadel/internal/eventstore/models"
"github.com/caos/zitadel/internal/usergrant/model"
es_model "github.com/caos/zitadel/internal/usergrant/repository/eventsourcing/model"
"github.com/lib/pq"
"reflect"
"testing"
)
func mockUserGrantData(grant *es_model.UserGrant) []byte {
data, _ := json.Marshal(grant)
return data
}
func TestUserAppendEvent(t *testing.T) {
type args struct {
event *es_models.Event
grant *UserGrantView
}
tests := []struct {
name string
args args
result *UserGrantView
}{
{
name: "append added grant event",
args: args{
event: &es_models.Event{AggregateID: "AggregateID", Sequence: 1, Type: es_model.UserGrantAdded, ResourceOwner: "OrgID", Data: mockUserGrantData(&es_model.UserGrant{UserID: "UserID", ProjectID: "ProjectID", RoleKeys: pq.StringArray{"Keys"}})},
grant: &UserGrantView{},
},
result: &UserGrantView{ID: "AggregateID", ResourceOwner: "OrgID", UserID: "UserID", ProjectID: "ProjectID", RoleKeys: pq.StringArray{"Keys"}, State: int32(model.USERGRANTSTATE_ACTIVE)},
},
{
name: "append change grant profile event",
args: args{
event: &es_models.Event{AggregateID: "AggregateID", Sequence: 1, Type: es_model.UserGrantChanged, ResourceOwner: "OrgID", Data: mockUserGrantData(&es_model.UserGrant{RoleKeys: pq.StringArray{"KeysChanged"}})},
grant: &UserGrantView{ID: "AggregateID", ResourceOwner: "OrgID", UserID: "UserID", ProjectID: "ProjectID", RoleKeys: pq.StringArray{"Keys"}, State: int32(model.USERGRANTSTATE_ACTIVE)},
},
result: &UserGrantView{ID: "AggregateID", ResourceOwner: "OrgID", UserID: "UserID", ProjectID: "ProjectID", RoleKeys: pq.StringArray{"KeysChanged"}, State: int32(model.USERGRANTSTATE_ACTIVE)},
},
{
name: "append grant deactivate event",
args: args{
event: &es_models.Event{AggregateID: "AggregateID", Sequence: 1, Type: es_model.UserGrantDeactivated, ResourceOwner: "OrgID"},
grant: &UserGrantView{ID: "AggregateID", ResourceOwner: "OrgID", UserID: "UserID", ProjectID: "ProjectID", RoleKeys: pq.StringArray{"Keys"}, State: int32(model.USERGRANTSTATE_ACTIVE)},
},
result: &UserGrantView{ID: "AggregateID", ResourceOwner: "OrgID", UserID: "UserID", ProjectID: "ProjectID", RoleKeys: pq.StringArray{"Keys"}, State: int32(model.USERGRANTSTATE_INACTIVE)},
},
{
name: "append grant reactivate event",
args: args{
event: &es_models.Event{AggregateID: "AggregateID", Sequence: 1, Type: es_model.UserGrantReactivated, ResourceOwner: "OrgID"},
grant: &UserGrantView{ID: "AggregateID", ResourceOwner: "OrgID", UserID: "UserID", ProjectID: "ProjectID", RoleKeys: pq.StringArray{"Keys"}, State: int32(model.USERGRANTSTATE_INACTIVE)},
},
result: &UserGrantView{ID: "AggregateID", ResourceOwner: "OrgID", UserID: "UserID", ProjectID: "ProjectID", RoleKeys: pq.StringArray{"Keys"}, State: int32(model.USERGRANTSTATE_ACTIVE)},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
tt.args.grant.AppendEvent(tt.args.event)
if tt.args.grant.ID != tt.result.ID {
t.Errorf("got wrong result ID: expected: %v, actual: %v ", tt.result.ID, tt.args.grant.ID)
}
if tt.args.grant.ResourceOwner != tt.result.ResourceOwner {
t.Errorf("got wrong result ResourceOwner: expected: %v, actual: %v ", tt.result.ResourceOwner, tt.args.grant.ResourceOwner)
}
if tt.args.grant.UserID != tt.result.UserID {
t.Errorf("got wrong result UserID: expected: %v, actual: %v ", tt.result.UserID, tt.args.grant.UserID)
}
if tt.args.grant.ProjectID != tt.result.ProjectID {
t.Errorf("got wrong result ProjectID: expected: %v, actual: %v ", tt.result.ProjectID, tt.args.grant.ProjectID)
}
if !reflect.DeepEqual(tt.args.grant.RoleKeys, tt.result.RoleKeys) {
t.Errorf("got wrong result RoleKeys: expected: %v, actual: %v ", tt.result.RoleKeys, tt.args.grant.RoleKeys)
}
})
}
}

View File

@@ -0,0 +1,75 @@
package view
import (
global_model "github.com/caos/zitadel/internal/model"
grant_model "github.com/caos/zitadel/internal/usergrant/model"
"github.com/caos/zitadel/internal/usergrant/repository/view/model"
"github.com/caos/zitadel/internal/view"
"github.com/jinzhu/gorm"
)
func UserGrantByID(db *gorm.DB, table, grantID string) (*model.UserGrantView, error) {
user := new(model.UserGrantView)
query := view.PrepareGetByKey(table, model.UserGrantSearchKey(grant_model.USERGRANTSEARCHKEY_GRANT_ID), grantID)
err := query(db, user)
return user, err
}
func SearchUserGrants(db *gorm.DB, table string, req *grant_model.UserGrantSearchRequest) ([]*model.UserGrantView, int, error) {
users := make([]*model.UserGrantView, 0)
query := view.PrepareSearchQuery(table, model.UserGrantSearchRequest{Limit: req.Limit, Offset: req.Offset, Queries: req.Queries})
count, err := query(db, &users)
if err != nil {
return nil, 0, err
}
return users, count, nil
}
func UserGrantsByUserID(db *gorm.DB, table, userID string) ([]*model.UserGrantView, error) {
users := make([]*model.UserGrantView, 0)
queries := []*grant_model.UserGrantSearchQuery{
&grant_model.UserGrantSearchQuery{Key: grant_model.USERGRANTSEARCHKEY_USER_ID, Value: userID, Method: global_model.SEARCHMETHOD_EQUALS},
}
query := view.PrepareSearchQuery(table, model.UserGrantSearchRequest{Queries: queries})
_, err := query(db, &users)
if err != nil {
return nil, err
}
return users, nil
}
func UserGrantsByProjectID(db *gorm.DB, table, projectID string) ([]*model.UserGrantView, error) {
users := make([]*model.UserGrantView, 0)
queries := []*grant_model.UserGrantSearchQuery{
&grant_model.UserGrantSearchQuery{Key: grant_model.USERGRANTSEARCHKEY_PROJECT_ID, Value: projectID, Method: global_model.SEARCHMETHOD_EQUALS},
}
query := view.PrepareSearchQuery(table, model.UserGrantSearchRequest{Queries: queries})
_, err := query(db, &users)
if err != nil {
return nil, err
}
return users, nil
}
func UserGrantsByOrgID(db *gorm.DB, table, orgID string) ([]*model.UserGrantView, error) {
users := make([]*model.UserGrantView, 0)
queries := []*grant_model.UserGrantSearchQuery{
&grant_model.UserGrantSearchQuery{Key: grant_model.USERGRANTSEARCHKEY_RESOURCEOWNER, Value: orgID, Method: global_model.SEARCHMETHOD_EQUALS},
}
query := view.PrepareSearchQuery(table, model.UserGrantSearchRequest{Queries: queries})
_, err := query(db, &users)
if err != nil {
return nil, err
}
return users, nil
}
func PutUserGrant(db *gorm.DB, table string, grant *model.UserGrantView) error {
save := view.PrepareSave(table)
return save(db, grant)
}
func DeleteUserGrant(db *gorm.DB, table, grantID string) error {
delete := view.PrepareDeleteByKey(table, model.UserGrantSearchKey(grant_model.USERGRANTSEARCHKEY_GRANT_ID), grantID)
return delete(db)
}