fix(queries): privacy policy (#2431)

* job queue

* wg improvements

* start handler

* statement

* statements

* imporve handler

* improve statement

* statement in seperate file

* move handlers

* move query/old to query

* handler

* read models

* bulk works

* cleanup

* contrib

* rename readmodel to projection

* rename read_models schema to projections

* rename read_models schema to projections

* search query as func,
bulk iterates as long as new events

* add event sequence less query

* update checks for events between current sequence and sequence of first statement if it has previous sequence 0

* cleanup crdb projection

* refactor projection handler

* start with testing

* tests for handler

* remove todo

* refactor statement: remove table name,
add tests

* improve projection handler shutdown,
no savepoint if noop stmt,
tests for stmt handler

* tests

* start failed events

* seperate branch for contrib

* move statement constructors to crdb pkg

* correct import

* Subscribe for eventtypes (#1800)

* fix: is default (#1737)

* fix: use email as username on global org (#1738)

* fix: use email as username on global org

* Update user_human.go

* Update register_handler.go

* chore(deps): update docusaurus (#1739)

* chore: remove PAT and use GH Token (#1716)

* chore: remove PAT and use GH Token

* fix env

* fix env

* fix env

* md lint

* trigger ci

* change user

* fix GH bug

* replace login part

* chore: add GH Token to sem rel (#1746)

* chore: add GH Token to sem rel

* try branch

* add GH Token

* remove test branch again

* docs: changes acme to acme-caos (#1744)

* changes acme to acme-caos

* Apply suggestions from code review

Co-authored-by: Florian Forster <florian@caos.ch>

Co-authored-by: Maximilian Panne <maximilian.panne@gmail.com>
Co-authored-by: Florian Forster <florian@caos.ch>

* feat: add additional origins on applications (#1691)

* feat: add additional origins on applications

* app additional redirects

* chore(deps-dev): bump @angular/cli from 11.2.8 to 11.2.11 in /console (#1706)

* fix: show org with regex (#1688)

* fix: flag mapping (#1699)

* chore(deps-dev): bump @angular/cli from 11.2.8 to 11.2.11 in /console

Bumps [@angular/cli](https://github.com/angular/angular-cli) from 11.2.8 to 11.2.11.
- [Release notes](https://github.com/angular/angular-cli/releases)
- [Commits](https://github.com/angular/angular-cli/compare/v11.2.8...v11.2.11)

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: Max Peintner <max@caos.ch>
Co-authored-by: Silvan <silvan.reusser@gmail.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

* chore(deps-dev): bump stylelint from 13.10.0 to 13.13.1 in /console (#1703)

* fix: show org with regex (#1688)

* fix: flag mapping (#1699)

* chore(deps-dev): bump stylelint from 13.10.0 to 13.13.1 in /console

Bumps [stylelint](https://github.com/stylelint/stylelint) from 13.10.0 to 13.13.1.
- [Release notes](https://github.com/stylelint/stylelint/releases)
- [Changelog](https://github.com/stylelint/stylelint/blob/master/CHANGELOG.md)
- [Commits](https://github.com/stylelint/stylelint/compare/13.10.0...13.13.1)

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: Max Peintner <max@caos.ch>
Co-authored-by: Silvan <silvan.reusser@gmail.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

* chore(deps-dev): bump @types/node from 14.14.37 to 15.0.1 in /console (#1702)

* fix: show org with regex (#1688)

* fix: flag mapping (#1699)

* chore(deps-dev): bump @types/node from 14.14.37 to 15.0.1 in /console

Bumps [@types/node](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/node) from 14.14.37 to 15.0.1.
- [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases)
- [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/node)

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: Max Peintner <max@caos.ch>
Co-authored-by: Silvan <silvan.reusser@gmail.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

* chore(deps): bump ts-protoc-gen from 0.14.0 to 0.15.0 in /console (#1701)

* fix: show org with regex (#1688)

* fix: flag mapping (#1699)

* chore(deps): bump ts-protoc-gen from 0.14.0 to 0.15.0 in /console

Bumps [ts-protoc-gen](https://github.com/improbable-eng/ts-protoc-gen) from 0.14.0 to 0.15.0.
- [Release notes](https://github.com/improbable-eng/ts-protoc-gen/releases)
- [Changelog](https://github.com/improbable-eng/ts-protoc-gen/blob/master/CHANGELOG.md)
- [Commits](https://github.com/improbable-eng/ts-protoc-gen/compare/0.14.0...0.15.0)

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: Max Peintner <max@caos.ch>
Co-authored-by: Silvan <silvan.reusser@gmail.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

* chore(deps-dev): bump @types/jasmine from 3.6.9 to 3.6.10 in /console (#1682)

Bumps [@types/jasmine](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/jasmine) from 3.6.9 to 3.6.10.
- [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases)
- [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/jasmine)

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

* chore(deps): bump @types/google-protobuf in /console (#1681)

Bumps [@types/google-protobuf](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/google-protobuf) from 3.7.4 to 3.15.2.
- [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases)
- [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/google-protobuf)

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

* chore(deps): bump grpc from 1.24.5 to 1.24.7 in /console (#1666)

Bumps [grpc](https://github.com/grpc/grpc-node) from 1.24.5 to 1.24.7.
- [Release notes](https://github.com/grpc/grpc-node/releases)
- [Commits](https://github.com/grpc/grpc-node/compare/grpc@1.24.5...grpc@1.24.7)

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

* lock

* chore(deps-dev): bump @angular/language-service from 11.2.9 to 11.2.12 in /console (#1704)

* fix: show org with regex (#1688)

* fix: flag mapping (#1699)

* chore(deps-dev): bump @angular/language-service in /console

Bumps [@angular/language-service](https://github.com/angular/angular/tree/HEAD/packages/language-service) from 11.2.9 to 11.2.12.
- [Release notes](https://github.com/angular/angular/releases)
- [Changelog](https://github.com/angular/angular/blob/master/CHANGELOG.md)
- [Commits](https://github.com/angular/angular/commits/11.2.12/packages/language-service)

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: Max Peintner <max@caos.ch>
Co-authored-by: Silvan <silvan.reusser@gmail.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

* package lock

* downgrade grpc

* downgrade protobuf types

* revert npm packs 🥸

Co-authored-by: Max Peintner <max@caos.ch>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Silvan <silvan.reusser@gmail.com>

* docs: update run and start section texts (#1745)

* update run and start section texts

* adds showcase

Co-authored-by: Maximilian Panne <maximilian.panne@gmail.com>

* fix: additional origin list (#1753)

* fix: handle api configs in authz handler (#1755)

* fix(console): add model for api keys, fix toast, binding (#1757)

* fix: add model for api keys, fix toast, binding

* show api clientid

* fix: missing patchvalue (#1758)

* feat: refresh token (#1728)

* begin refresh tokens

* refresh tokens

* list and revoke refresh tokens

* handle remove

* tests for refresh tokens

* uniqueness and default expiration

* rename oidc token methods

* cleanup

* migration version

* Update internal/static/i18n/en.yaml

Co-authored-by: Fabi <38692350+fgerschwiler@users.noreply.github.com>

* fixes

* feat: update oidc pkg for refresh tokens

Co-authored-by: Fabi <38692350+fgerschwiler@users.noreply.github.com>

* fix: correct json name of clientId in key.json (#1760)

* fix: migration version (#1767)

* start subscription

* eventtypes

* fix(login): links (#1778)

* fix(login): href for help

* fix(login): correct link to tos

* fix: access tokens for service users and refresh token infos (#1779)

* fix: access token for service user

* handle info from refresh request

* uniqueness

* postpone access token uniqueness change

* chore(coc): recommend code of conduct (#1782)

* subscribe for events

* feat(console): refresh toggle out of granttype context (#1785)

* refresh toggle

* disable if not code flow, lint

* lint

* fix: change oidc config order

* accept refresh option within flow

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

* fix: refresh token activation (#1795)

* fix: oidc grant type check

* docs: add offline_access scope

* docs: update refresh token status in supported grant types

* fix: update oidc pkg

* fix: check refresh token grant type (#1796)

* configuration structs

* org admins

* failed events

* fixes

Co-authored-by: Max Peintner <max@caos.ch>
Co-authored-by: Livio Amstutz <livio.a@gmail.com>
Co-authored-by: Florian Forster <florian@caos.ch>
Co-authored-by: mffap <mpa@caos.ch>
Co-authored-by: Maximilian Panne <maximilian.panne@gmail.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Fabi <38692350+fgerschwiler@users.noreply.github.com>

* remove comment

* aggregate reducer

* remove eventtypes

* add protoc-get-validate to mod

* fix transaltion

* upsert

* add gender on org admins,
allow to retry failed stmts after configurable time

* remove if

* sub queries

* fix: tests

* add builder to tests

* new search query

* rename searchquerybuilder to builder

* remove comment from code

* test with multiple queries

* add filters test

* current sequences

* make org and org_admins work again

* add aggregate type to current sequence

* fix(contibute): listing

* add validate module

* fix: search queries

* feat(eventstore): previous aggregate root sequence (#1810)

* feat(eventstore): previous aggregate root sequence

* fix tests

* fix: eventstore v1 test

* add col to all mocked rows

* next try

* fix mig

* rename aggregate root to aggregate type

* update comment

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

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

* small refactorings

* allow update multiple current sequences

* unique log id

* fix migrations

* rename org admin to org owner

* improve error handling and logging

* fix(migration): optimize prev agg root seq

* fix: projection handler test

* fix: sub queries

* small fixes

* additional event types

* correct org owner projection

* fix primary key

* feat(eventstore): jobs for projections (#2026)

* fix: template names in login (#1974)

* fix: template names in login

* fix: error.html

* fix: check for features on mgmt only (#1976)

* fix: add sentry in ui, http and projection handlers (#1977)

* fix: add sentry in ui, http and projection handlers

* fix test

* fix(eventstore): sub queries (#1805)

* sub queries

* fix: tests

* add builder to tests

* new search query

* rename searchquerybuilder to builder

* remove comment from code

* test with multiple queries

* add filters test

* fix(contibute): listing

* add validate module

* fix: search queries

* remove unused event type in query

* ignore query if error in marshal

* go mod tidy

* update privacy policy query

* update queries

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

* feat: Extend oidc idp with oauth endpoints (#1980)

* feat: add oauth attributes to oidc idp configuration

* feat: return idpconfig id on create idp

* feat: tests

* feat: descriptions

* feat: docs

* feat: tests

* docs: update to beta 3 (#1984)

* fix: role assertion (#1986)

* fix: enum to display access token role assertion

* improve assertion descriptions

* fix nil pointer

* docs: eventstore (#1982)

* docs: eventstore

* Apply suggestions from code review

Co-authored-by: Florian Forster <florian@caos.ch>

Co-authored-by: Florian Forster <florian@caos.ch>

* fix(sentry): trigger sentry release (#1989)

* feat(send sentry release): send sentry release

* fix(moved step and added releasetag): moved step and added releasetag

* fix: set version for sentry release (#1990)

* feat(send sentry release): send sentry release

* fix(moved step and added releasetag): moved step and added releasetag

* fix(corrected var name): corrected var name

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

* fix: log error reason on terminate session (#1973)

* fix: return default language file, if requested lang does not exist for default login texts (#1988)

* fix: return default language file, if requested lang doesnt exists

* feat: read default translation file

* feat: docs

* fix: race condition in auth request unmarshalling (#1993)

* feat: handle ui_locales in login (#1994)

* fix: handle ui_locales in login

* move supportedlanguage func into i18n package

* update oidc pkg

* fix: handle closed channels on unsubscribe (#1995)

* fix: give restore more time (#1997)

* fix: translation file read (#2009)

* feat: translation file read

* feat: readme

* fix: enable idp add button for iam users (#2010)

* fix: filter event_data (#2011)

* feat: Custom message files (#1992)

* feat: add get custom message text to admin api

* feat: read custom message texts from files

* feat: get languages in apis

* feat: get languages in apis

* feat: get languages in apis

* feat: pr feedback

* feat: docs

* feat: merge main

* fix: sms notification (#2013)

* fix: phone verifications

* feat: fix password reset as sms

* fix: phone verification

* fix: grpc status in sentry and validation interceptors (#2012)

* fix: remove oauth endpoints from oidc config proto (#2014)

* try with view

* fix(console): disable sw (#2021)

* fix: disable sw

* angular.json disable sw

* project projections

* fix typos

* customize projections

* customizable projections,
add change date to projects

Co-authored-by: Livio Amstutz <livio.a@gmail.com>
Co-authored-by: Max Peintner <max@caos.ch>
Co-authored-by: Fabi <38692350+fgerschwiler@users.noreply.github.com>
Co-authored-by: Florian Forster <florian@caos.ch>
Co-authored-by: mffap <mpa@caos.ch>
Co-authored-by: Christian Jakob <47860090+thesephirot@users.noreply.github.com>
Co-authored-by: Elio Bischof <eliobischof@gmail.com>

* env file

* typo

* correct users

* correct migration

* fix: merge fail

* fix test

* fix(tests): unordered matcher

* improve currentSequenceMatcher

* correct certs

* correct certs

* add zitadel database on database list

* refctor switch in match

* enable all handlers

* Delete io.env

* cleanup

* add handlers

* rename view to projection

* rename view to projection

* fix type typo

* remove unnecessary logs

* refactor stmts

* simplify interval calculation

* fix tests

* fix unlock test

* fix migration

* migs

* fix(operator): update cockroach and flyway versions (#2138)

* chore(deps): bump k8s.io/apiextensions-apiserver from 0.19.2 to 0.21.3

Bumps [k8s.io/apiextensions-apiserver](https://github.com/kubernetes/apiextensions-apiserver) from 0.19.2 to 0.21.3.
- [Release notes](https://github.com/kubernetes/apiextensions-apiserver/releases)
- [Commits](https://github.com/kubernetes/apiextensions-apiserver/compare/v0.19.2...v0.21.3)

---
updated-dependencies:
- dependency-name: k8s.io/apiextensions-apiserver
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>

* chore(deps): bump google.golang.org/api from 0.34.0 to 0.52.0

Bumps [google.golang.org/api](https://github.com/googleapis/google-api-go-client) from 0.34.0 to 0.52.0.
- [Release notes](https://github.com/googleapis/google-api-go-client/releases)
- [Changelog](https://github.com/googleapis/google-api-go-client/blob/master/CHANGES.md)
- [Commits](https://github.com/googleapis/google-api-go-client/compare/v0.34.0...v0.52.0)

---
updated-dependencies:
- dependency-name: google.golang.org/api
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>

* start update dependencies

* update mods and otlp

* fix(build): update to go 1.16

* old version for k8s mods

* update k8s versions

* update orbos

* fix(operator): update cockroach and flyway version

* Update images.go

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Stefan Benz <stefan@caos.ch>

* fix import

* fix typo

* fix(migration): add org projection

* fix(projection): correct table for org events in org owners

* better insert stmt

* fix typo

* fix typo

* set max connection lifetime

* set max conns and conn lifetime in eventstore v1

* configure sql connection settings

* add mig for agg type index

* fix replace tab in yaml

* handler interfaces

* subscription

* first try

* handler

* move sql client initialization

* first part implemented

* removed all occurencies of org by id and search orgs

* fix merge issues

* cleanup code

* fix: queries implements orgviewprovider

* cleanup

* refactor text comparison

* remove unused file

* remove unused code

* log

* remove unused code

* remove unused field

* remove unused file

* refactor

* tests for search query

* remove try

* simplify state change mappers

* projection tests

* query functions

* move reusable objects to separate files

* rename domain column to primar_domain

* fix tests

* add current sequence

* remove log prints

* fix tests

* fix: verifier

* fix test

* rename domain col migrations

* simplify search response

* add custom column constructors

* fix: org projection table const

* fix: full column name

* feat: text query extension

* fix: tests for query

* number query

* add deprection message

* projection

* correct migration

* projection

* projection

* column in a single place (#2416)

* column in a single place

* use projection for columns

* query column with aliases

* rename methods

* remove unused code

* column for current sequences

* correct file name

* global counter column

* fix is org unique

* query

* fix wrong code

* remove unused code

* query

* remove unused code

* remove unused code

* query

* api

* remove unused cod

* remove unused code

* remove unused code

* remove unused code

* tests

* tests

* tests

* tests

* fix: tests

* migrations

* fixes

* errors

* fix test

* add converter option

* fix(auth-repo): add queries to struct

* error messages

* rename method,
correct log message

* small fixes

* correct version

* correct version

* fix(migration): set pk

* correct version

* fix test

* cleanup code

* fix interface

* cleanup code

* method name

* rename method

Co-authored-by: Max Peintner <max@caos.ch>
Co-authored-by: Livio Amstutz <livio.a@gmail.com>
Co-authored-by: Florian Forster <florian@caos.ch>
Co-authored-by: mffap <mpa@caos.ch>
Co-authored-by: Maximilian Panne <maximilian.panne@gmail.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Fabi <38692350+fgerschwiler@users.noreply.github.com>
Co-authored-by: Christian Jakob <47860090+thesephirot@users.noreply.github.com>
Co-authored-by: Elio Bischof <eliobischof@gmail.com>
Co-authored-by: Stefan Benz <stefan@caos.ch>
Co-authored-by: fabi <fabienne.gerschwiler@gmail.com>
This commit is contained in:
Silvan 2021-10-20 17:12:34 +02:00 committed by GitHub
parent 40b7b5a804
commit dbec8e164d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
32 changed files with 556 additions and 810 deletions

View File

@ -272,33 +272,6 @@ func (repo *IAMRepository) GetCustomMessageText(ctx context.Context, textType, l
return result, err
}
func (repo *IAMRepository) GetDefaultPrivacyPolicy(ctx context.Context) (*iam_model.PrivacyPolicyView, error) {
policy, viewErr := repo.View.PrivacyPolicyByAggregateID(repo.SystemDefaults.IamID)
if viewErr != nil && !caos_errs.IsNotFound(viewErr) {
return nil, viewErr
}
if caos_errs.IsNotFound(viewErr) {
policy = new(iam_es_model.PrivacyPolicyView)
}
events, esErr := repo.getIAMEvents(ctx, policy.Sequence)
if caos_errs.IsNotFound(viewErr) && len(events) == 0 {
return nil, caos_errs.ThrowNotFound(nil, "EVENT-84Nfs", "Errors.IAM.PrivacyPolicy.NotFound")
}
if esErr != nil {
logging.Log("EVENT-0p3Fs").WithError(esErr).Debug("error retrieving new events")
return iam_es_model.PrivacyViewToModel(policy), nil
}
policyCopy := *policy
for _, event := range events {
if err := policyCopy.AppendEvent(event); err != nil {
return iam_es_model.PrivacyViewToModel(policy), nil
}
}
result := iam_es_model.PrivacyViewToModel(policy)
result.Default = true
return result, nil
}
func (repo *IAMRepository) GetDefaultLoginTexts(ctx context.Context, lang string) (*domain.CustomLoginText, error) {
repo.mutex.Lock()
defer repo.mutex.Unlock()

View File

@ -56,8 +56,6 @@ func Register(configs Configs, bulkLimit, errorCount uint64, view *view.View, es
handler{view, bulkLimit, configs.cycleDuration("MessageText"), errorCount, es}),
newFeatures(
handler{view, bulkLimit, configs.cycleDuration("Features"), errorCount, es}),
newPrivacyPolicy(
handler{view, bulkLimit, configs.cycleDuration("PrivacyPolicy"), errorCount, es}),
newCustomText(
handler{view, bulkLimit, configs.cycleDuration("CustomTexts"), errorCount, es}),
}

View File

@ -1,110 +0,0 @@
package handler
import (
"github.com/caos/logging"
"github.com/caos/zitadel/internal/eventstore/v1"
iam_es_model "github.com/caos/zitadel/internal/iam/repository/eventsourcing/model"
es_models "github.com/caos/zitadel/internal/eventstore/v1/models"
"github.com/caos/zitadel/internal/eventstore/v1/query"
"github.com/caos/zitadel/internal/eventstore/v1/spooler"
iam_model "github.com/caos/zitadel/internal/iam/repository/view/model"
"github.com/caos/zitadel/internal/org/repository/eventsourcing/model"
)
const (
privacyPolicyTable = "adminapi.privacy_policies"
)
type PrivacyPolicy struct {
handler
subscription *v1.Subscription
}
func newPrivacyPolicy(handler handler) *PrivacyPolicy {
h := &PrivacyPolicy{
handler: handler,
}
h.subscribe()
return h
}
func (p *PrivacyPolicy) subscribe() {
p.subscription = p.es.Subscribe(p.AggregateTypes()...)
go func() {
for event := range p.subscription.Events {
query.ReduceEvent(p, event)
}
}()
}
func (p *PrivacyPolicy) ViewModel() string {
return privacyPolicyTable
}
func (p *PrivacyPolicy) Subscription() *v1.Subscription {
return p.subscription
}
func (p *PrivacyPolicy) AggregateTypes() []es_models.AggregateType {
return []es_models.AggregateType{model.OrgAggregate, iam_es_model.IAMAggregate}
}
func (p *PrivacyPolicy) CurrentSequence() (uint64, error) {
sequence, err := p.view.GetLatestPrivacyPolicySequence()
if err != nil {
return 0, err
}
return sequence.CurrentSequence, nil
}
func (p *PrivacyPolicy) EventQuery() (*es_models.SearchQuery, error) {
sequence, err := p.view.GetLatestPrivacyPolicySequence()
if err != nil {
return nil, err
}
return es_models.NewSearchQuery().
AggregateTypeFilter(p.AggregateTypes()...).
LatestSequenceFilter(sequence.CurrentSequence), nil
}
func (p *PrivacyPolicy) Reduce(event *es_models.Event) (err error) {
switch event.AggregateType {
case model.OrgAggregate, iam_es_model.IAMAggregate:
err = p.processPrivacyPolicy(event)
}
return err
}
func (p *PrivacyPolicy) processPrivacyPolicy(event *es_models.Event) (err error) {
policy := new(iam_model.PrivacyPolicyView)
switch event.Type {
case iam_es_model.PrivacyPolicyAdded, model.PrivacyPolicyAdded:
err = policy.AppendEvent(event)
case iam_es_model.PrivacyPolicyChanged, model.PrivacyPolicyChanged:
policy, err = p.view.PrivacyPolicyByAggregateID(event.AggregateID)
if err != nil {
return err
}
err = policy.AppendEvent(event)
case model.PrivacyPolicyRemoved:
return p.view.DeletePrivacyPolicy(event.AggregateID, event)
default:
return p.view.ProcessedPrivacyPolicySequence(event)
}
if err != nil {
return err
}
return p.view.PutPrivacyPolicy(policy, event)
}
func (p *PrivacyPolicy) OnError(event *es_models.Event, err error) error {
logging.LogWithFields("SPOOL-4N8sw", "id", event.AggregateID).WithError(err).Warn("something went wrong in privacy policy handler")
return spooler.HandleError(event, err, p.view.GetLatestPrivacyPolicyFailedEvent, p.view.ProcessedPrivacyPolicyFailedEvent, p.view.ProcessedPrivacyPolicySequence, p.errorCountUntilSkip)
}
func (p *PrivacyPolicy) OnSuccess() error {
return spooler.HandleSuccess(p.view.UpdatePrivacyPolicySpoolerRunTimestamp)
}

View File

@ -1,53 +0,0 @@
package view
import (
"github.com/caos/zitadel/internal/errors"
"github.com/caos/zitadel/internal/eventstore/v1/models"
"github.com/caos/zitadel/internal/iam/repository/view"
"github.com/caos/zitadel/internal/iam/repository/view/model"
global_view "github.com/caos/zitadel/internal/view/repository"
)
const (
privacyPolicyTable = "adminapi.privacy_policies"
)
func (v *View) PrivacyPolicyByAggregateID(aggregateID string) (*model.PrivacyPolicyView, error) {
return view.GetPrivacyPolicyByAggregateID(v.Db, privacyPolicyTable, aggregateID)
}
func (v *View) PutPrivacyPolicy(policy *model.PrivacyPolicyView, event *models.Event) error {
err := view.PutPrivacyPolicy(v.Db, privacyPolicyTable, policy)
if err != nil {
return err
}
return v.ProcessedPrivacyPolicySequence(event)
}
func (v *View) DeletePrivacyPolicy(aggregateID string, event *models.Event) error {
err := view.DeletePrivacyPolicy(v.Db, privacyPolicyTable, aggregateID)
if err != nil && !errors.IsNotFound(err) {
return err
}
return v.ProcessedPrivacyPolicySequence(event)
}
func (v *View) GetLatestPrivacyPolicySequence() (*global_view.CurrentSequence, error) {
return v.latestSequence(privacyPolicyTable)
}
func (v *View) ProcessedPrivacyPolicySequence(event *models.Event) error {
return v.saveCurrentSequence(privacyPolicyTable, event)
}
func (v *View) UpdatePrivacyPolicySpoolerRunTimestamp() error {
return v.updateSpoolerRunSequence(privacyPolicyTable)
}
func (v *View) GetLatestPrivacyPolicyFailedEvent(sequence uint64) (*global_view.FailedEvent, error) {
return v.latestFailedEvent(privacyPolicyTable, sequence)
}
func (v *View) ProcessedPrivacyPolicyFailedEvent(failedEvent *global_view.FailedEvent) error {
return v.saveFailedEvent(failedEvent)
}

View File

@ -35,7 +35,5 @@ type IAMRepository interface {
GetDefaultLoginTexts(ctx context.Context, lang string) (*domain.CustomLoginText, error)
GetCustomLoginTexts(ctx context.Context, lang string) (*domain.CustomLoginText, error)
GetDefaultPrivacyPolicy(ctx context.Context) (*iam_model.PrivacyPolicyView, error)
GetDefaultOrgIAMPolicy(ctx context.Context) (*iam_model.OrgIAMPolicyView, error)
}

View File

@ -9,7 +9,7 @@ import (
)
func (s *Server) GetPrivacyPolicy(ctx context.Context, _ *admin_pb.GetPrivacyPolicyRequest) (*admin_pb.GetPrivacyPolicyResponse, error) {
policy, err := s.iam.GetDefaultPrivacyPolicy(ctx)
policy, err := s.query.DefaultPrivacyPolicy(ctx)
if err != nil {
return nil, err
}

View File

@ -10,7 +10,7 @@ import (
)
func (s *Server) GetPrivacyPolicy(ctx context.Context, _ *mgmt_pb.GetPrivacyPolicyRequest) (*mgmt_pb.GetPrivacyPolicyResponse, error) {
policy, err := s.org.GetPrivacyPolicy(ctx)
policy, err := s.query.PrivacyPolicyByOrg(ctx, authz.GetCtxData(ctx).OrgID)
if err != nil {
return nil, err
}
@ -18,7 +18,7 @@ func (s *Server) GetPrivacyPolicy(ctx context.Context, _ *mgmt_pb.GetPrivacyPoli
}
func (s *Server) GetDefaultPrivacyPolicy(ctx context.Context, _ *mgmt_pb.GetDefaultPrivacyPolicyRequest) (*mgmt_pb.GetDefaultPrivacyPolicyResponse, error) {
policy, err := s.org.GetDefaultPrivacyPolicy(ctx)
policy, err := s.query.DefaultPrivacyPolicy(ctx)
if err != nil {
return nil, err
}

View File

@ -2,20 +2,20 @@ package policy
import (
"github.com/caos/zitadel/internal/api/grpc/object"
"github.com/caos/zitadel/internal/iam/model"
"github.com/caos/zitadel/internal/query"
policy_pb "github.com/caos/zitadel/pkg/grpc/policy"
)
func ModelPrivacyPolicyToPb(policy *model.PrivacyPolicyView) *policy_pb.PrivacyPolicy {
func ModelPrivacyPolicyToPb(policy *query.PrivacyPolicy) *policy_pb.PrivacyPolicy {
return &policy_pb.PrivacyPolicy{
IsDefault: policy.Default,
IsDefault: policy.IsDefault,
TosLink: policy.TOSLink,
PrivacyLink: policy.PrivacyLink,
Details: object.ToViewDetailsPb(
policy.Sequence,
policy.CreationDate,
policy.ChangeDate,
"", //TODO: resourceowner
policy.ResourceOwner,
),
}
}

View File

@ -20,7 +20,6 @@ import (
"github.com/caos/zitadel/internal/id"
project_view_model "github.com/caos/zitadel/internal/project/repository/view/model"
"github.com/caos/zitadel/internal/query"
"github.com/caos/zitadel/internal/repository/iam"
"github.com/caos/zitadel/internal/telemetry/tracing"
user_model "github.com/caos/zitadel/internal/user/model"
es_model "github.com/caos/zitadel/internal/user/repository/eventsourcing/model"
@ -41,6 +40,7 @@ type AuthRequestRepo struct {
OrgViewProvider orgViewProvider
LoginPolicyViewProvider loginPolicyViewProvider
LockoutPolicyViewProvider lockoutPolicyViewProvider
PrivacyPolicyProvider privacyPolicyProvider
IDPProviderViewProvider idpProviderViewProvider
UserGrantProvider userGrantProvider
ProjectProvider projectProvider
@ -56,6 +56,10 @@ type AuthRequestRepo struct {
IAMID string
}
type privacyPolicyProvider interface {
PrivacyPolicyByOrg(context.Context, string) (*query.PrivacyPolicy, error)
}
type userSessionViewProvider interface {
UserSessionByIDs(string, string) (*user_view_model.UserSessionView, error)
UserSessionsByAgentID(string) ([]*user_view_model.UserSessionView, error)
@ -875,33 +879,27 @@ func (repo *AuthRequestRepo) mfaSkippedOrSetUp(user *user_model.UserView) bool {
}
func (repo *AuthRequestRepo) getPrivacyPolicy(ctx context.Context, orgID string) (*domain.PrivacyPolicy, error) {
policy, err := repo.View.PrivacyPolicyByAggregateID(orgID)
if errors.IsNotFound(err) {
policy, err = repo.View.PrivacyPolicyByAggregateID(repo.IAMID)
if err != nil && !errors.IsNotFound(err) {
return nil, err
}
if err == nil {
return policy.ToDomain(), nil
}
policy = &iam_view_model.PrivacyPolicyView{}
events, err := repo.Eventstore.FilterEvents(ctx, es_models.NewSearchQuery().
AggregateIDFilter(repo.IAMID).
AggregateTypeFilter(iam.AggregateType).
EventTypesFilter(es_models.EventType(iam.PrivacyPolicyAddedEventType), es_models.EventType(iam.PrivacyPolicyChangedEventType)))
if err != nil || len(events) == 0 {
return nil, errors.ThrowNotFound(err, "EVENT-GSRqg", "IAM.PrivacyPolicy.NotExisting")
}
policy.Default = true
for _, event := range events {
policy.AppendEvent(event)
}
return policy.ToDomain(), nil
}
policy, err := repo.PrivacyPolicyProvider.PrivacyPolicyByOrg(ctx, orgID)
if err != nil {
return nil, err
}
return policy.ToDomain(), err
return privacyPolicyToDomain(policy), err
}
func privacyPolicyToDomain(p *query.PrivacyPolicy) *domain.PrivacyPolicy {
return &domain.PrivacyPolicy{
ObjectRoot: es_models.ObjectRoot{
AggregateID: p.ID,
Sequence: p.Sequence,
ResourceOwner: p.ResourceOwner,
CreationDate: p.CreationDate,
ChangeDate: p.ChangeDate,
},
State: p.State,
Default: p.IsDefault,
TOSLink: p.TOSLink,
PrivacyLink: p.PrivacyLink,
}
}
func (repo *AuthRequestRepo) getLockoutPolicy(ctx context.Context, orgID string) (*query.LockoutPolicy, error) {

View File

@ -3,8 +3,6 @@ package eventstore
import (
"context"
"github.com/caos/logging"
"github.com/caos/zitadel/internal/api/authz"
auth_view "github.com/caos/zitadel/internal/auth/repository/eventsourcing/view"
"github.com/caos/zitadel/internal/config/systemdefaults"
@ -91,33 +89,6 @@ func (repo *OrgRepository) GetLoginText(ctx context.Context, orgID string) ([]*d
return append(iam_view_model.CustomTextViewsToDomain(loginTexts), iam_view_model.CustomTextViewsToDomain(orgLoginTexts)...), nil
}
func (repo *OrgRepository) GetDefaultPrivacyPolicy(ctx context.Context) (*iam_model.PrivacyPolicyView, error) {
policy, viewErr := repo.View.PrivacyPolicyByAggregateID(repo.SystemDefaults.IamID)
if viewErr != nil && !errors.IsNotFound(viewErr) {
return nil, viewErr
}
if errors.IsNotFound(viewErr) {
policy = new(iam_view_model.PrivacyPolicyView)
}
events, esErr := repo.getIAMEvents(ctx, policy.Sequence)
if errors.IsNotFound(viewErr) && len(events) == 0 {
return nil, errors.ThrowNotFound(nil, "EVENT-LPJMp", "Errors.IAM.PrivacyPolicy.NotFound")
}
if esErr != nil {
logging.Log("EVENT-1l7bf").WithError(esErr).Debug("error retrieving new events")
return iam_view_model.PrivacyViewToModel(policy), nil
}
policyCopy := *policy
for _, event := range events {
if err := policyCopy.AppendEvent(event); err != nil {
return iam_view_model.PrivacyViewToModel(policy), nil
}
}
result := iam_view_model.PrivacyViewToModel(policy)
result.Default = true
return result, nil
}
func (p *OrgRepository) getIAMEvents(ctx context.Context, sequence uint64) ([]*models.Event, error) {
return p.Eventstore.FilterEvents(ctx, models.NewSearchQuery().AggregateIDFilter(p.SystemDefaults.IamID).AggregateTypeFilter(iam.AggregateType))
}

View File

@ -64,7 +64,6 @@ func Register(configs Configs, bulkLimit, errorCount uint64, view *view.View, es
newLabelPolicy(handler{view, bulkLimit, configs.cycleDuration("LabelPolicy"), errorCount, es}),
newFeatures(handler{view, bulkLimit, configs.cycleDuration("Features"), errorCount, es}),
newRefreshToken(handler{view, bulkLimit, configs.cycleDuration("RefreshToken"), errorCount, es}),
newPrivacyPolicy(handler{view, bulkLimit, configs.cycleDuration("PrivacyPolicy"), errorCount, es}),
newCustomText(handler{view, bulkLimit, configs.cycleDuration("CustomTexts"), errorCount, es}),
newMetadata(handler{view, bulkLimit, configs.cycleDuration("Metadata"), errorCount, es}),
newOrgProjectMapping(handler{view, bulkLimit, configs.cycleDuration("OrgProjectMapping"), errorCount, es}),

View File

@ -1,110 +0,0 @@
package handler
import (
"github.com/caos/logging"
"github.com/caos/zitadel/internal/eventstore/v1"
iam_es_model "github.com/caos/zitadel/internal/iam/repository/eventsourcing/model"
es_models "github.com/caos/zitadel/internal/eventstore/v1/models"
"github.com/caos/zitadel/internal/eventstore/v1/query"
"github.com/caos/zitadel/internal/eventstore/v1/spooler"
iam_model "github.com/caos/zitadel/internal/iam/repository/view/model"
"github.com/caos/zitadel/internal/org/repository/eventsourcing/model"
)
const (
privacyPolicyTable = "auth.privacy_policies"
)
type PrivacyPolicy struct {
handler
subscription *v1.Subscription
}
func newPrivacyPolicy(handler handler) *PrivacyPolicy {
h := &PrivacyPolicy{
handler: handler,
}
h.subscribe()
return h
}
func (p *PrivacyPolicy) subscribe() {
p.subscription = p.es.Subscribe(p.AggregateTypes()...)
go func() {
for event := range p.subscription.Events {
query.ReduceEvent(p, event)
}
}()
}
func (p *PrivacyPolicy) ViewModel() string {
return privacyPolicyTable
}
func (p *PrivacyPolicy) Subscription() *v1.Subscription {
return p.subscription
}
func (p *PrivacyPolicy) AggregateTypes() []es_models.AggregateType {
return []es_models.AggregateType{model.OrgAggregate, iam_es_model.IAMAggregate}
}
func (p *PrivacyPolicy) CurrentSequence() (uint64, error) {
sequence, err := p.view.GetLatestPrivacyPolicySequence()
if err != nil {
return 0, err
}
return sequence.CurrentSequence, nil
}
func (p *PrivacyPolicy) EventQuery() (*es_models.SearchQuery, error) {
sequence, err := p.view.GetLatestPrivacyPolicySequence()
if err != nil {
return nil, err
}
return es_models.NewSearchQuery().
AggregateTypeFilter(p.AggregateTypes()...).
LatestSequenceFilter(sequence.CurrentSequence), nil
}
func (p *PrivacyPolicy) Reduce(event *es_models.Event) (err error) {
switch event.AggregateType {
case model.OrgAggregate, iam_es_model.IAMAggregate:
err = p.processPrivacyPolicy(event)
}
return err
}
func (p *PrivacyPolicy) processPrivacyPolicy(event *es_models.Event) (err error) {
policy := new(iam_model.PrivacyPolicyView)
switch event.Type {
case iam_es_model.PrivacyPolicyAdded, model.PrivacyPolicyAdded:
err = policy.AppendEvent(event)
case iam_es_model.PrivacyPolicyChanged, model.PrivacyPolicyChanged:
policy, err = p.view.PrivacyPolicyByAggregateID(event.AggregateID)
if err != nil {
return err
}
err = policy.AppendEvent(event)
case model.PrivacyPolicyRemoved:
return p.view.DeletePrivacyPolicy(event.AggregateID, event)
default:
return p.view.ProcessedPrivacyPolicySequence(event)
}
if err != nil {
return err
}
return p.view.PutPrivacyPolicy(policy, event)
}
func (p *PrivacyPolicy) OnError(event *es_models.Event, err error) error {
logging.LogWithFields("SPOOL-4N8sw", "id", event.AggregateID).WithError(err).Warn("something went wrong in privacy policy handler")
return spooler.HandleError(event, err, p.view.GetLatestPrivacyPolicyFailedEvent, p.view.ProcessedPrivacyPolicyFailedEvent, p.view.ProcessedPrivacyPolicySequence, p.errorCountUntilSkip)
}
func (p *PrivacyPolicy) OnSuccess() error {
return spooler.HandleSuccess(p.view.UpdatePrivacyPolicySpoolerRunTimestamp)
}

View File

@ -1,53 +0,0 @@
package view
import (
"github.com/caos/zitadel/internal/errors"
"github.com/caos/zitadel/internal/eventstore/v1/models"
"github.com/caos/zitadel/internal/iam/repository/view"
"github.com/caos/zitadel/internal/iam/repository/view/model"
global_view "github.com/caos/zitadel/internal/view/repository"
)
const (
privacyPolicyTable = "auth.privacy_policies"
)
func (v *View) PrivacyPolicyByAggregateID(aggregateID string) (*model.PrivacyPolicyView, error) {
return view.GetPrivacyPolicyByAggregateID(v.Db, privacyPolicyTable, aggregateID)
}
func (v *View) PutPrivacyPolicy(policy *model.PrivacyPolicyView, event *models.Event) error {
err := view.PutPrivacyPolicy(v.Db, privacyPolicyTable, policy)
if err != nil {
return err
}
return v.ProcessedPrivacyPolicySequence(event)
}
func (v *View) DeletePrivacyPolicy(aggregateID string, event *models.Event) error {
err := view.DeletePrivacyPolicy(v.Db, privacyPolicyTable, aggregateID)
if err != nil && !errors.IsNotFound(err) {
return err
}
return v.ProcessedPrivacyPolicySequence(event)
}
func (v *View) GetLatestPrivacyPolicySequence() (*global_view.CurrentSequence, error) {
return v.latestSequence(privacyPolicyTable)
}
func (v *View) ProcessedPrivacyPolicySequence(event *models.Event) error {
return v.saveCurrentSequence(privacyPolicyTable, event)
}
func (v *View) UpdatePrivacyPolicySpoolerRunTimestamp() error {
return v.updateSpoolerRunSequence(privacyPolicyTable)
}
func (v *View) GetLatestPrivacyPolicyFailedEvent(sequence uint64) (*global_view.FailedEvent, error) {
return v.latestFailedEvent(privacyPolicyTable, sequence)
}
func (v *View) ProcessedPrivacyPolicyFailedEvent(failedEvent *global_view.FailedEvent) error {
return v.saveFailedEvent(failedEvent)
}

View File

@ -14,5 +14,4 @@ type OrgRepository interface {
GetMyPasswordComplexityPolicy(ctx context.Context) (*iam_model.PasswordComplexityPolicyView, error)
GetLabelPolicy(ctx context.Context, orgID string) (*domain.LabelPolicy, error)
GetLoginText(ctx context.Context, orgID string) ([]*domain.CustomText, error)
GetDefaultPrivacyPolicy(ctx context.Context) (*iam_model.PrivacyPolicyView, error)
}

View File

@ -1,98 +0,0 @@
package model
import (
"encoding/json"
"time"
"github.com/caos/zitadel/internal/domain"
org_es_model "github.com/caos/zitadel/internal/org/repository/eventsourcing/model"
es_model "github.com/caos/zitadel/internal/iam/repository/eventsourcing/model"
"github.com/caos/logging"
caos_errs "github.com/caos/zitadel/internal/errors"
"github.com/caos/zitadel/internal/eventstore/v1/models"
"github.com/caos/zitadel/internal/iam/model"
)
const (
PrivacyKeyAggregateID = "aggregate_id"
)
type PrivacyPolicyView struct {
AggregateID string `json:"-" gorm:"column:aggregate_id;primary_key"`
CreationDate time.Time `json:"-" gorm:"column:creation_date"`
ChangeDate time.Time `json:"-" gorm:"column:change_date"`
State int32 `json:"-" gorm:"column:state"`
TOSLink string `json:"tosLink" gorm:"column:tos_link"`
PrivacyLink string `json:"privacyLink" gorm:"column:privacy_link"`
Default bool `json:"-" gorm:"-"`
Sequence uint64 `json:"-" gorm:"column:sequence"`
}
func PrivacyViewFromModel(policy *model.PrivacyPolicyView) *PrivacyPolicyView {
return &PrivacyPolicyView{
AggregateID: policy.AggregateID,
Sequence: policy.Sequence,
CreationDate: policy.CreationDate,
ChangeDate: policy.ChangeDate,
TOSLink: policy.TOSLink,
PrivacyLink: policy.PrivacyLink,
Default: policy.Default,
}
}
func PrivacyViewToModel(policy *PrivacyPolicyView) *model.PrivacyPolicyView {
return &model.PrivacyPolicyView{
AggregateID: policy.AggregateID,
Sequence: policy.Sequence,
CreationDate: policy.CreationDate,
ChangeDate: policy.ChangeDate,
TOSLink: policy.TOSLink,
PrivacyLink: policy.PrivacyLink,
Default: policy.Default,
}
}
func (p *PrivacyPolicyView) ToDomain() *domain.PrivacyPolicy {
return &domain.PrivacyPolicy{
ObjectRoot: models.ObjectRoot{
AggregateID: p.AggregateID,
CreationDate: p.CreationDate,
ChangeDate: p.ChangeDate,
Sequence: p.Sequence,
},
Default: p.Default,
TOSLink: p.TOSLink,
PrivacyLink: p.PrivacyLink,
}
}
func (i *PrivacyPolicyView) AppendEvent(event *models.Event) (err error) {
i.Sequence = event.Sequence
i.ChangeDate = event.CreationDate
switch event.Type {
case es_model.PrivacyPolicyAdded, org_es_model.PrivacyPolicyAdded:
i.setRootData(event)
i.CreationDate = event.CreationDate
err = i.SetData(event)
case es_model.PrivacyPolicyChanged, org_es_model.PrivacyPolicyChanged:
err = i.SetData(event)
}
return err
}
func (r *PrivacyPolicyView) setRootData(event *models.Event) {
r.AggregateID = event.AggregateID
}
func (r *PrivacyPolicyView) SetData(event *models.Event) error {
if err := json.Unmarshal(event.Data, r); err != nil {
logging.Log("EVEN-gHls0").WithError(err).Error("could not unmarshal event data")
return caos_errs.ThrowInternal(err, "MODEL-Hs8uf", "Could not unmarshal data")
}
return nil
}

View File

@ -1,59 +0,0 @@
package model
import (
"github.com/caos/zitadel/internal/domain"
iam_model "github.com/caos/zitadel/internal/iam/model"
"github.com/caos/zitadel/internal/view/repository"
)
type PrivacyPolicySearchRequest iam_model.PrivacyPolicySearchRequest
type PrivacyPolicySearchQuery iam_model.PrivacyPolicySearchQuery
type PrivacyPolicySearchKey iam_model.PrivacyPolicySearchKey
func (req PrivacyPolicySearchRequest) GetLimit() uint64 {
return req.Limit
}
func (req PrivacyPolicySearchRequest) GetOffset() uint64 {
return req.Offset
}
func (req PrivacyPolicySearchRequest) GetSortingColumn() repository.ColumnKey {
if req.SortingColumn == iam_model.PrivacyPolicySearchKeyUnspecified {
return nil
}
return PrivacyPolicySearchKey(req.SortingColumn)
}
func (req PrivacyPolicySearchRequest) GetAsc() bool {
return req.Asc
}
func (req PrivacyPolicySearchRequest) GetQueries() []repository.SearchQuery {
result := make([]repository.SearchQuery, len(req.Queries))
for i, q := range req.Queries {
result[i] = PrivacyPolicySearchQuery{Key: q.Key, Value: q.Value, Method: q.Method}
}
return result
}
func (req PrivacyPolicySearchQuery) GetKey() repository.ColumnKey {
return PrivacyPolicySearchKey(req.Key)
}
func (req PrivacyPolicySearchQuery) GetMethod() domain.SearchMethod {
return req.Method
}
func (req PrivacyPolicySearchQuery) GetValue() interface{} {
return req.Value
}
func (key PrivacyPolicySearchKey) ToColumnName() string {
switch iam_model.PrivacyPolicySearchKey(key) {
case iam_model.PrivacyPolicySearchKeyAggregateID:
return PrivacyKeyAggregateID
default:
return ""
}
}

View File

@ -1,32 +0,0 @@
package view
import (
"github.com/caos/zitadel/internal/domain"
caos_errs "github.com/caos/zitadel/internal/errors"
iam_model "github.com/caos/zitadel/internal/iam/model"
"github.com/caos/zitadel/internal/iam/repository/view/model"
"github.com/caos/zitadel/internal/view/repository"
"github.com/jinzhu/gorm"
)
func GetPrivacyPolicyByAggregateID(db *gorm.DB, table, aggregateID string) (*model.PrivacyPolicyView, error) {
policy := new(model.PrivacyPolicyView)
aggregateIDQuery := &model.PrivacyPolicySearchQuery{Key: iam_model.PrivacyPolicySearchKeyAggregateID, Value: aggregateID, Method: domain.SearchMethodEquals}
query := repository.PrepareGetByQuery(table, aggregateIDQuery)
err := query(db, policy)
if caos_errs.IsNotFound(err) {
return nil, caos_errs.ThrowNotFound(nil, "VIEW-2N9fs", "Errors.IAM.PrivacyPolicy.NotExisting")
}
return policy, err
}
func PutPrivacyPolicy(db *gorm.DB, table string, policy *model.PrivacyPolicyView) error {
save := repository.PrepareSave(table)
return save(db, policy)
}
func DeletePrivacyPolicy(db *gorm.DB, table, aggregateID string) error {
delete := repository.PrepareDeleteByKey(table, model.PrivacyPolicySearchKey(iam_model.PrivacyPolicySearchKeyAggregateID), aggregateID)
return delete(db)
}

View File

@ -285,23 +285,6 @@ func (repo *OrgRepository) SearchIDPProviders(ctx context.Context, request *iam_
return result, nil
}
func (repo *OrgRepository) GetPrivacyPolicy(ctx context.Context) (*iam_model.PrivacyPolicyView, error) {
policy, err := repo.View.PrivacyPolicyByAggregateID(authz.GetCtxData(ctx).OrgID)
if errors.IsNotFound(err) {
return repo.GetDefaultPrivacyPolicy(ctx)
}
return iam_view_model.PrivacyViewToModel(policy), nil
}
func (repo *OrgRepository) GetDefaultPrivacyPolicy(ctx context.Context) (*iam_model.PrivacyPolicyView, error) {
policy, err := repo.View.PrivacyPolicyByAggregateID(repo.SystemDefaults.IamID)
if err != nil {
return nil, err
}
policy.Default = true
return iam_view_model.PrivacyViewToModel(policy), nil
}
func (repo *OrgRepository) GetDefaultMailTemplate(ctx context.Context) (*iam_model.MailTemplateView, error) {
template, err := repo.View.MailTemplateByAggregateID(repo.SystemDefaults.IamID)
if err != nil {

View File

@ -65,8 +65,6 @@ func Register(configs Configs, bulkLimit, errorCount uint64, view *view.View, es
handler{view, bulkLimit, configs.cycleDuration("MessageText"), errorCount, es}),
newFeatures(
handler{view, bulkLimit, configs.cycleDuration("Features"), errorCount, es}),
newPrivacyPolicy(
handler{view, bulkLimit, configs.cycleDuration("PrivacyPolicy"), errorCount, es}),
newCustomText(
handler{view, bulkLimit, configs.cycleDuration("CustomText"), errorCount, es}),
newMetadata(

View File

@ -1,110 +0,0 @@
package handler
import (
"github.com/caos/logging"
"github.com/caos/zitadel/internal/eventstore/v1"
iam_es_model "github.com/caos/zitadel/internal/iam/repository/eventsourcing/model"
es_models "github.com/caos/zitadel/internal/eventstore/v1/models"
"github.com/caos/zitadel/internal/eventstore/v1/query"
"github.com/caos/zitadel/internal/eventstore/v1/spooler"
iam_model "github.com/caos/zitadel/internal/iam/repository/view/model"
"github.com/caos/zitadel/internal/org/repository/eventsourcing/model"
)
const (
privacyPolicyTable = "management.privacy_policies"
)
type PrivacyPolicy struct {
handler
subscription *v1.Subscription
}
func newPrivacyPolicy(handler handler) *PrivacyPolicy {
h := &PrivacyPolicy{
handler: handler,
}
h.subscribe()
return h
}
func (p *PrivacyPolicy) subscribe() {
p.subscription = p.es.Subscribe(p.AggregateTypes()...)
go func() {
for event := range p.subscription.Events {
query.ReduceEvent(p, event)
}
}()
}
func (p *PrivacyPolicy) ViewModel() string {
return privacyPolicyTable
}
func (p *PrivacyPolicy) Subscription() *v1.Subscription {
return p.subscription
}
func (p *PrivacyPolicy) AggregateTypes() []es_models.AggregateType {
return []es_models.AggregateType{model.OrgAggregate, iam_es_model.IAMAggregate}
}
func (p *PrivacyPolicy) CurrentSequence() (uint64, error) {
sequence, err := p.view.GetLatestPrivacyPolicySequence()
if err != nil {
return 0, err
}
return sequence.CurrentSequence, nil
}
func (p *PrivacyPolicy) EventQuery() (*es_models.SearchQuery, error) {
sequence, err := p.view.GetLatestPrivacyPolicySequence()
if err != nil {
return nil, err
}
return es_models.NewSearchQuery().
AggregateTypeFilter(p.AggregateTypes()...).
LatestSequenceFilter(sequence.CurrentSequence), nil
}
func (p *PrivacyPolicy) Reduce(event *es_models.Event) (err error) {
switch event.AggregateType {
case model.OrgAggregate, iam_es_model.IAMAggregate:
err = p.processPrivacyPolicy(event)
}
return err
}
func (p *PrivacyPolicy) processPrivacyPolicy(event *es_models.Event) (err error) {
policy := new(iam_model.PrivacyPolicyView)
switch event.Type {
case iam_es_model.PrivacyPolicyAdded, model.PrivacyPolicyAdded:
err = policy.AppendEvent(event)
case iam_es_model.PrivacyPolicyChanged, model.PrivacyPolicyChanged:
policy, err = p.view.PrivacyPolicyByAggregateID(event.AggregateID)
if err != nil {
return err
}
err = policy.AppendEvent(event)
case model.PrivacyPolicyRemoved:
return p.view.DeletePrivacyPolicy(event.AggregateID, event)
default:
return p.view.ProcessedPrivacyPolicySequence(event)
}
if err != nil {
return err
}
return p.view.PutPrivacyPolicy(policy, event)
}
func (p *PrivacyPolicy) OnError(event *es_models.Event, err error) error {
logging.LogWithFields("SPOOL-4N8sw", "id", event.AggregateID).WithError(err).Warn("something went wrong in privacy policy handler")
return spooler.HandleError(event, err, p.view.GetLatestPrivacyPolicyFailedEvent, p.view.ProcessedPrivacyPolicyFailedEvent, p.view.ProcessedPrivacyPolicySequence, p.errorCountUntilSkip)
}
func (p *PrivacyPolicy) OnSuccess() error {
return spooler.HandleSuccess(p.view.UpdatePrivacyPolicySpoolerRunTimestamp)
}

View File

@ -1,53 +0,0 @@
package view
import (
"github.com/caos/zitadel/internal/errors"
"github.com/caos/zitadel/internal/eventstore/v1/models"
"github.com/caos/zitadel/internal/iam/repository/view"
"github.com/caos/zitadel/internal/iam/repository/view/model"
global_view "github.com/caos/zitadel/internal/view/repository"
)
const (
privacyPolicyTable = "management.privacy_policies"
)
func (v *View) PrivacyPolicyByAggregateID(aggregateID string) (*model.PrivacyPolicyView, error) {
return view.GetPrivacyPolicyByAggregateID(v.Db, privacyPolicyTable, aggregateID)
}
func (v *View) PutPrivacyPolicy(policy *model.PrivacyPolicyView, event *models.Event) error {
err := view.PutPrivacyPolicy(v.Db, privacyPolicyTable, policy)
if err != nil {
return err
}
return v.ProcessedPrivacyPolicySequence(event)
}
func (v *View) DeletePrivacyPolicy(aggregateID string, event *models.Event) error {
err := view.DeletePrivacyPolicy(v.Db, privacyPolicyTable, aggregateID)
if err != nil && !errors.IsNotFound(err) {
return err
}
return v.ProcessedPrivacyPolicySequence(event)
}
func (v *View) GetLatestPrivacyPolicySequence() (*global_view.CurrentSequence, error) {
return v.latestSequence(privacyPolicyTable)
}
func (v *View) ProcessedPrivacyPolicySequence(event *models.Event) error {
return v.saveCurrentSequence(privacyPolicyTable, event)
}
func (v *View) UpdatePrivacyPolicySpoolerRunTimestamp() error {
return v.updateSpoolerRunSequence(privacyPolicyTable)
}
func (v *View) GetLatestPrivacyPolicyFailedEvent(sequence uint64) (*global_view.FailedEvent, error) {
return v.latestFailedEvent(privacyPolicyTable, sequence)
}
func (v *View) ProcessedPrivacyPolicyFailedEvent(failedEvent *global_view.FailedEvent) error {
return v.saveFailedEvent(failedEvent)
}

View File

@ -28,9 +28,6 @@ type OrgRepository interface {
SearchIDPProviders(ctx context.Context, request *iam_model.IDPProviderSearchRequest) (*iam_model.IDPProviderSearchResponse, error)
GetIDPProvidersByIDPConfigID(ctx context.Context, aggregateID, idpConfigID string) ([]*iam_model.IDPProviderView, error)
GetPrivacyPolicy(ctx context.Context) (*iam_model.PrivacyPolicyView, error)
GetDefaultPrivacyPolicy(ctx context.Context) (*iam_model.PrivacyPolicyView, error)
GetDefaultMailTemplate(ctx context.Context) (*iam_model.MailTemplateView, error)
GetMailTemplate(ctx context.Context) (*iam_model.MailTemplateView, error)

View File

@ -7,6 +7,7 @@ import (
"time"
sq "github.com/Masterminds/squirrel"
"github.com/caos/zitadel/internal/domain"
"github.com/caos/zitadel/internal/errors"
"github.com/caos/zitadel/internal/query/projection"
)
@ -17,6 +18,7 @@ type LockoutPolicy struct {
CreationDate time.Time
ChangeDate time.Time
ResourceOwner string
State domain.PolicyState
MaxPasswordAttempts uint64
ShowFailures bool
@ -52,6 +54,9 @@ var (
LockoutColIsDefault = Column{
name: projection.LockoutPolicyIsDefaultCol,
}
LockoutColState = Column{
name: projection.LockoutPolicyStateCol,
}
)
func (q *Queries) LockoutPolicyByOrg(ctx context.Context, orgID string) (*LockoutPolicy, error) {
@ -100,6 +105,7 @@ func prepareLockoutPolicyQuery() (sq.SelectBuilder, func(*sql.Row) (*LockoutPoli
LockoutColShowFailures.identifier(),
LockoutColMaxPasswordAttempts.identifier(),
LockoutColIsDefault.identifier(),
LockoutColState.identifier(),
).
From(lockoutTable.identifier()).PlaceholderFormat(sq.Dollar),
func(row *sql.Row) (*LockoutPolicy, error) {
@ -113,6 +119,7 @@ func prepareLockoutPolicyQuery() (sq.SelectBuilder, func(*sql.Row) (*LockoutPoli
&policy.ShowFailures,
&policy.MaxPasswordAttempts,
&policy.IsDefault,
&policy.State,
)
if err != nil {
if errs.Is(err, sql.ErrNoRows) {

View File

@ -7,6 +7,7 @@ import (
"time"
sq "github.com/Masterminds/squirrel"
"github.com/caos/zitadel/internal/domain"
"github.com/caos/zitadel/internal/errors"
"github.com/caos/zitadel/internal/query/projection"
)
@ -17,6 +18,7 @@ type PasswordAgePolicy struct {
CreationDate time.Time
ChangeDate time.Time
ResourceOwner string
State domain.PolicyState
ExpireWarnDays uint64
MaxAgeDays uint64
@ -52,6 +54,9 @@ var (
PasswordAgeColIsDefault = Column{
name: projection.AgePolicyIsDefaultCol,
}
PasswordAgeColState = Column{
name: projection.AgePolicyStateCol,
}
)
func (q *Queries) PasswordAgePolicyByOrg(ctx context.Context, orgID string) (*PasswordAgePolicy, error) {
@ -100,6 +105,7 @@ func preparePasswordAgePolicyQuery() (sq.SelectBuilder, func(*sql.Row) (*Passwor
PasswordAgeColWarnDays.identifier(),
PasswordAgeColMaxAge.identifier(),
PasswordAgeColIsDefault.identifier(),
PasswordAgeColState.identifier(),
).
From(passwordAgeTable.identifier()).PlaceholderFormat(sq.Dollar),
func(row *sql.Row) (*PasswordAgePolicy, error) {
@ -113,6 +119,7 @@ func preparePasswordAgePolicyQuery() (sq.SelectBuilder, func(*sql.Row) (*Passwor
&policy.ExpireWarnDays,
&policy.MaxAgeDays,
&policy.IsDefault,
&policy.State,
)
if err != nil {
if errs.Is(err, sql.ErrNoRows) {

View File

@ -7,6 +7,7 @@ import (
"time"
sq "github.com/Masterminds/squirrel"
"github.com/caos/zitadel/internal/domain"
"github.com/caos/zitadel/internal/errors"
"github.com/caos/zitadel/internal/query/projection"
)
@ -17,6 +18,7 @@ type PasswordComplexityPolicy struct {
CreationDate time.Time
ChangeDate time.Time
ResourceOwner string
State domain.PolicyState
MinLength uint64
HasLowercase bool
@ -100,6 +102,9 @@ var (
PasswordComplexityColIsDefault = Column{
name: projection.ComplexityPolicyIsDefaultCol,
}
PasswordComplexityColState = Column{
name: projection.ComplexityPolicyStateCol,
}
)
func preparePasswordComplexityPolicyQuery() (sq.SelectBuilder, func(*sql.Row) (*PasswordComplexityPolicy, error)) {
@ -115,6 +120,7 @@ func preparePasswordComplexityPolicyQuery() (sq.SelectBuilder, func(*sql.Row) (*
PasswordComplexityColHasNumber.identifier(),
PasswordComplexityColHasSymbol.identifier(),
PasswordComplexityColIsDefault.identifier(),
PasswordComplexityColState.identifier(),
).
From(passwordComplexityTable.identifier()).PlaceholderFormat(sq.Dollar),
func(row *sql.Row) (*PasswordComplexityPolicy, error) {
@ -131,6 +137,7 @@ func preparePasswordComplexityPolicyQuery() (sq.SelectBuilder, func(*sql.Row) (*
&policy.HasNumber,
&policy.HasSymbol,
&policy.IsDefault,
&policy.State,
)
if err != nil {
if errs.Is(err, sql.ErrNoRows) {

View File

@ -0,0 +1,132 @@
package query
import (
"context"
"database/sql"
errs "errors"
"time"
sq "github.com/Masterminds/squirrel"
"github.com/caos/zitadel/internal/domain"
"github.com/caos/zitadel/internal/errors"
"github.com/caos/zitadel/internal/query/projection"
)
type PrivacyPolicy struct {
ID string
Sequence uint64
CreationDate time.Time
ChangeDate time.Time
ResourceOwner string
State domain.PolicyState
TOSLink string
PrivacyLink string
IsDefault bool
}
var (
privacyTable = table{
name: projection.PrivacyPolicyTable,
}
PrivacyColID = Column{
name: projection.PrivacyPolicyIDCol,
}
PrivacyColSequence = Column{
name: projection.PrivacyPolicySequenceCol,
}
PrivacyColCreationDate = Column{
name: projection.PrivacyPolicyCreationDateCol,
}
PrivacyColChangeDate = Column{
name: projection.PrivacyPolicyChangeDateCol,
}
PrivacyColResourceOwner = Column{
name: projection.PrivacyPolicyResourceOwnerCol,
}
PrivacyColPrivacyLink = Column{
name: projection.PrivacyPolicyPrivacyLinkCol,
}
PrivacyColTOSLink = Column{
name: projection.PrivacyPolicyTOSLinkCol,
}
PrivacyColIsDefault = Column{
name: projection.PrivacyPolicyIsDefaultCol,
}
PrivacyColState = Column{
name: projection.PrivacyPolicyStateCol,
}
)
func (q *Queries) PrivacyPolicyByOrg(ctx context.Context, orgID string) (*PrivacyPolicy, error) {
stmt, scan := preparePrivacyPolicyQuery()
query, args, err := stmt.Where(
sq.Or{
sq.Eq{
PrivacyColID.identifier(): orgID,
},
sq.Eq{
PrivacyColID.identifier(): q.iamID,
},
}).
OrderBy(PrivacyColIsDefault.identifier()).
Limit(1).ToSql()
if err != nil {
return nil, errors.ThrowInternal(err, "QUERY-UXuPI", "Errors.Query.SQLStatement")
}
row := q.client.QueryRowContext(ctx, query, args...)
return scan(row)
}
func (q *Queries) DefaultPrivacyPolicy(ctx context.Context) (*PrivacyPolicy, error) {
stmt, scan := preparePrivacyPolicyQuery()
query, args, err := stmt.Where(sq.Eq{
PrivacyColID.identifier(): q.iamID,
}).
OrderBy(PrivacyColIsDefault.identifier()).
Limit(1).ToSql()
if err != nil {
return nil, errors.ThrowInternal(err, "QUERY-LkFZ7", "Errors.Query.SQLStatement")
}
row := q.client.QueryRowContext(ctx, query, args...)
return scan(row)
}
func preparePrivacyPolicyQuery() (sq.SelectBuilder, func(*sql.Row) (*PrivacyPolicy, error)) {
return sq.Select(
PrivacyColID.identifier(),
PrivacyColSequence.identifier(),
PrivacyColCreationDate.identifier(),
PrivacyColChangeDate.identifier(),
PrivacyColResourceOwner.identifier(),
PrivacyColPrivacyLink.identifier(),
PrivacyColTOSLink.identifier(),
PrivacyColIsDefault.identifier(),
PrivacyColState.identifier(),
).
From(privacyTable.identifier()).PlaceholderFormat(sq.Dollar),
func(row *sql.Row) (*PrivacyPolicy, error) {
policy := new(PrivacyPolicy)
err := row.Scan(
&policy.ID,
&policy.Sequence,
&policy.CreationDate,
&policy.ChangeDate,
&policy.ResourceOwner,
&policy.PrivacyLink,
&policy.TOSLink,
&policy.IsDefault,
&policy.State,
)
if err != nil {
if errs.Is(err, sql.ErrNoRows) {
return nil, errors.ThrowNotFound(err, "QUERY-vNMHL", "Errors.PrivacyPolicy.NotFound")
}
return nil, errors.ThrowInternal(err, "QUERY-csrdo", "Errors.Internal")
}
return policy, nil
}
}

View File

@ -0,0 +1,147 @@
package projection
import (
"context"
"github.com/caos/logging"
"github.com/caos/zitadel/internal/domain"
"github.com/caos/zitadel/internal/errors"
"github.com/caos/zitadel/internal/eventstore"
"github.com/caos/zitadel/internal/eventstore/handler"
"github.com/caos/zitadel/internal/eventstore/handler/crdb"
"github.com/caos/zitadel/internal/repository/iam"
"github.com/caos/zitadel/internal/repository/org"
"github.com/caos/zitadel/internal/repository/policy"
)
type PrivacyPolicyProjection struct {
crdb.StatementHandler
}
const (
PrivacyPolicyTable = "zitadel.projections.privacy_policies"
PrivacyPolicyCreationDateCol = "creation_date"
PrivacyPolicyChangeDateCol = "change_date"
PrivacyPolicySequenceCol = "sequence"
PrivacyPolicyIDCol = "id"
PrivacyPolicyStateCol = "state"
PrivacyPolicyPrivacyLinkCol = "privacy_link"
PrivacyPolicyTOSLinkCol = "tos_link"
PrivacyPolicyIsDefaultCol = "is_default"
PrivacyPolicyResourceOwnerCol = "resource_owner"
)
func NewPrivacyPolicyProjection(ctx context.Context, config crdb.StatementHandlerConfig) *PrivacyPolicyProjection {
p := &PrivacyPolicyProjection{}
config.ProjectionName = PrivacyPolicyTable
config.Reducers = p.reducers()
p.StatementHandler = crdb.NewStatementHandler(ctx, config)
return p
}
func (p *PrivacyPolicyProjection) reducers() []handler.AggregateReducer {
return []handler.AggregateReducer{
{
Aggregate: org.AggregateType,
EventRedusers: []handler.EventReducer{
{
Event: org.PrivacyPolicyAddedEventType,
Reduce: p.reduceAdded,
},
{
Event: org.PrivacyPolicyChangedEventType,
Reduce: p.reduceChanged,
},
{
Event: org.PrivacyPolicyRemovedEventType,
Reduce: p.reduceRemoved,
},
},
},
{
Aggregate: iam.AggregateType,
EventRedusers: []handler.EventReducer{
{
Event: iam.PrivacyPolicyAddedEventType,
Reduce: p.reduceAdded,
},
{
Event: iam.PrivacyPolicyChangedEventType,
Reduce: p.reduceChanged,
},
},
},
}
}
func (p *PrivacyPolicyProjection) reduceAdded(event eventstore.EventReader) (*handler.Statement, error) {
var policyEvent policy.PrivacyPolicyAddedEvent
var isDefault bool
switch e := event.(type) {
case *org.PrivacyPolicyAddedEvent:
policyEvent = e.PrivacyPolicyAddedEvent
isDefault = false
case *iam.PrivacyPolicyAddedEvent:
policyEvent = e.PrivacyPolicyAddedEvent
isDefault = true
default:
logging.LogWithFields("PROJE-BrdLn", "seq", event.Sequence(), "expectedTypes", []eventstore.EventType{org.PrivacyPolicyAddedEventType, iam.PrivacyPolicyAddedEventType}).Error("wrong event type")
return nil, errors.ThrowInvalidArgument(nil, "PROJE-kRNh8", "reduce.wrong.event.type")
}
return crdb.NewCreateStatement(
&policyEvent,
[]handler.Column{
handler.NewCol(PrivacyPolicyCreationDateCol, policyEvent.CreationDate()),
handler.NewCol(PrivacyPolicyChangeDateCol, policyEvent.CreationDate()),
handler.NewCol(PrivacyPolicySequenceCol, policyEvent.Sequence()),
handler.NewCol(PrivacyPolicyIDCol, policyEvent.Aggregate().ID),
handler.NewCol(PrivacyPolicyStateCol, domain.PolicyStateActive),
handler.NewCol(PrivacyPolicyPrivacyLinkCol, policyEvent.PrivacyLink),
handler.NewCol(PrivacyPolicyTOSLinkCol, policyEvent.TOSLink),
handler.NewCol(PrivacyPolicyIsDefaultCol, isDefault),
handler.NewCol(PrivacyPolicyResourceOwnerCol, policyEvent.Aggregate().ResourceOwner),
}), nil
}
func (p *PrivacyPolicyProjection) reduceChanged(event eventstore.EventReader) (*handler.Statement, error) {
var policyEvent policy.PrivacyPolicyChangedEvent
switch e := event.(type) {
case *org.PrivacyPolicyChangedEvent:
policyEvent = e.PrivacyPolicyChangedEvent
case *iam.PrivacyPolicyChangedEvent:
policyEvent = e.PrivacyPolicyChangedEvent
default:
logging.LogWithFields("PROJE-1nQWm", "seq", event.Sequence(), "expectedTypes", []eventstore.EventType{org.PrivacyPolicyChangedEventType, iam.PrivacyPolicyChangedEventType}).Error("wrong event type")
return nil, errors.ThrowInvalidArgument(nil, "PROJE-91weZ", "reduce.wrong.event.type")
}
cols := []handler.Column{
handler.NewCol(PrivacyPolicyChangeDateCol, policyEvent.CreationDate()),
handler.NewCol(PrivacyPolicySequenceCol, policyEvent.Sequence()),
}
if policyEvent.PrivacyLink != nil {
cols = append(cols, handler.NewCol(PrivacyPolicyPrivacyLinkCol, *policyEvent.PrivacyLink))
}
if policyEvent.TOSLink != nil {
cols = append(cols, handler.NewCol(PrivacyPolicyTOSLinkCol, *policyEvent.TOSLink))
}
return crdb.NewUpdateStatement(
&policyEvent,
cols,
[]handler.Condition{
handler.NewCond(PrivacyPolicyIDCol, policyEvent.Aggregate().ID),
}), nil
}
func (p *PrivacyPolicyProjection) reduceRemoved(event eventstore.EventReader) (*handler.Statement, error) {
policyEvent, ok := event.(*org.PrivacyPolicyRemovedEvent)
if !ok {
logging.LogWithFields("PROJE-hN5Ip", "seq", event.Sequence(), "expectedType", org.PrivacyPolicyRemovedEventType).Error("wrong event type")
return nil, errors.ThrowInvalidArgument(nil, "PROJE-FvtGO", "reduce.wrong.event.type")
}
return crdb.NewDeleteStatement(
policyEvent,
[]handler.Condition{
handler.NewCond(PrivacyPolicyIDCol, policyEvent.Aggregate().ID),
}), nil
}

View File

@ -0,0 +1,210 @@
package projection
import (
"testing"
"github.com/caos/zitadel/internal/domain"
"github.com/caos/zitadel/internal/errors"
"github.com/caos/zitadel/internal/eventstore"
"github.com/caos/zitadel/internal/eventstore/handler"
"github.com/caos/zitadel/internal/eventstore/repository"
"github.com/caos/zitadel/internal/repository/iam"
"github.com/caos/zitadel/internal/repository/org"
)
func TestPrivacyPolicyProjection_reduces(t *testing.T) {
type args struct {
event func(t *testing.T) eventstore.EventReader
}
tests := []struct {
name string
args args
reduce func(event eventstore.EventReader) (*handler.Statement, error)
want wantReduce
}{
{
name: "org.reduceAdded",
args: args{
event: getEvent(testEvent(
repository.EventType(org.PrivacyPolicyAddedEventType),
org.AggregateType,
[]byte(`{
"tosLink": "http://tos.link",
"privacyLink": "http://privacy.link"
}`),
), org.PrivacyPolicyAddedEventMapper),
},
reduce: (&PrivacyPolicyProjection{}).reduceAdded,
want: wantReduce{
aggregateType: eventstore.AggregateType("org"),
sequence: 15,
previousSequence: 10,
projection: PrivacyPolicyTable,
executer: &testExecuter{
executions: []execution{
{
expectedStmt: "INSERT INTO zitadel.projections.privacy_policies (creation_date, change_date, sequence, id, state, privacy_link, tos_link, is_default, resource_owner) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)",
expectedArgs: []interface{}{
anyArg{},
anyArg{},
uint64(15),
"agg-id",
domain.PolicyStateActive,
"http://privacy.link",
"http://tos.link",
false,
"ro-id",
},
},
},
},
},
},
{
name: "org.reduceChanged",
reduce: (&PrivacyPolicyProjection{}).reduceChanged,
args: args{
event: getEvent(testEvent(
repository.EventType(org.PrivacyPolicyChangedEventType),
org.AggregateType,
[]byte(`{
"tosLink": "http://tos.link",
"privacyLink": "http://privacy.link"
}`),
), org.PrivacyPolicyChangedEventMapper),
},
want: wantReduce{
aggregateType: eventstore.AggregateType("org"),
sequence: 15,
previousSequence: 10,
projection: PrivacyPolicyTable,
executer: &testExecuter{
executions: []execution{
{
expectedStmt: "UPDATE zitadel.projections.privacy_policies SET (change_date, sequence, privacy_link, tos_link) = ($1, $2, $3, $4) WHERE (id = $5)",
expectedArgs: []interface{}{
anyArg{},
uint64(15),
"http://privacy.link",
"http://tos.link",
"agg-id",
},
},
},
},
},
},
{
name: "org.reduceRemoved",
reduce: (&PrivacyPolicyProjection{}).reduceRemoved,
args: args{
event: getEvent(testEvent(
repository.EventType(org.PrivacyPolicyRemovedEventType),
org.AggregateType,
nil,
), org.PrivacyPolicyRemovedEventMapper),
},
want: wantReduce{
aggregateType: eventstore.AggregateType("org"),
sequence: 15,
previousSequence: 10,
projection: PrivacyPolicyTable,
executer: &testExecuter{
executions: []execution{
{
expectedStmt: "DELETE FROM zitadel.projections.privacy_policies WHERE (id = $1)",
expectedArgs: []interface{}{
"agg-id",
},
},
},
},
},
},
{
name: "iam.reduceAdded",
reduce: (&PrivacyPolicyProjection{}).reduceAdded,
args: args{
event: getEvent(testEvent(
repository.EventType(iam.PrivacyPolicyAddedEventType),
iam.AggregateType,
[]byte(`{
"tosLink": "http://tos.link",
"privacyLink": "http://privacy.link"
}`),
), iam.PrivacyPolicyAddedEventMapper),
},
want: wantReduce{
aggregateType: eventstore.AggregateType("iam"),
sequence: 15,
previousSequence: 10,
projection: PrivacyPolicyTable,
executer: &testExecuter{
executions: []execution{
{
expectedStmt: "INSERT INTO zitadel.projections.privacy_policies (creation_date, change_date, sequence, id, state, privacy_link, tos_link, is_default, resource_owner) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)",
expectedArgs: []interface{}{
anyArg{},
anyArg{},
uint64(15),
"agg-id",
domain.PolicyStateActive,
"http://privacy.link",
"http://tos.link",
true,
"ro-id",
},
},
},
},
},
},
{
name: "iam.reduceChanged",
reduce: (&PrivacyPolicyProjection{}).reduceChanged,
args: args{
event: getEvent(testEvent(
repository.EventType(iam.PrivacyPolicyChangedEventType),
iam.AggregateType,
[]byte(`{
"tosLink": "http://tos.link",
"privacyLink": "http://privacy.link"
}`),
), iam.PrivacyPolicyChangedEventMapper),
},
want: wantReduce{
aggregateType: eventstore.AggregateType("iam"),
sequence: 15,
previousSequence: 10,
projection: PrivacyPolicyTable,
executer: &testExecuter{
executions: []execution{
{
expectedStmt: "UPDATE zitadel.projections.privacy_policies SET (change_date, sequence, privacy_link, tos_link) = ($1, $2, $3, $4) WHERE (id = $5)",
expectedArgs: []interface{}{
anyArg{},
uint64(15),
"http://privacy.link",
"http://tos.link",
"agg-id",
},
},
},
},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
event := baseEvent(t)
got, err := tt.reduce(event)
if _, ok := err.(errors.InvalidArgument); !ok {
t.Errorf("no wrong event mapping: %v, got: %v", err, got)
}
event = tt.args.event(t)
got, err = tt.reduce(event)
assertReduce(t, got, err, tt.want)
})
}
}

View File

@ -40,6 +40,7 @@ func Start(ctx context.Context, sqlClient *sql.DB, es *eventstore.Eventstore, co
NewPasswordComplexityProjection(ctx, applyCustomConfig(projectionConfig, config.Customizations["password_complexities"]))
NewPasswordAgeProjection(ctx, applyCustomConfig(projectionConfig, config.Customizations["password_age_policy"]))
NewLockoutPolicyProjection(ctx, applyCustomConfig(projectionConfig, config.Customizations["lockout_policy"]))
NewPrivacyPolicyProjection(ctx, applyCustomConfig(projectionConfig, config.Customizations["privacy_policy"]))
NewProjectGrantProjection(ctx, applyCustomConfig(projectionConfig, config.Customizations["project_grants"]))
NewProjectRoleProjection(ctx, applyCustomConfig(projectionConfig, config.Customizations["project_roles"]))
// owner.NewOrgOwnerProjection(ctx, applyCustomConfig(projectionConfig, config.Customizations["org_owners"]))

View File

@ -1,15 +0,0 @@
package handler
import (
"net/http"
iam_model "github.com/caos/zitadel/internal/iam/model"
)
func (l *Login) getDefaultPrivacyPolicy(r *http.Request) (*iam_model.PrivacyPolicyView, error) {
policy, err := l.authRepo.GetDefaultPrivacyPolicy(r.Context())
if err != nil {
return nil, err
}
return policy, nil
}

View File

@ -353,7 +353,7 @@ func (l *Login) getBaseData(r *http.Request, authReq *domain.AuthRequest, title
baseData.PrivacyLink = authReq.PrivacyPolicy.PrivacyLink
}
} else {
privacyPolicy, err := l.getDefaultPrivacyPolicy(r)
privacyPolicy, err := l.query.DefaultPrivacyPolicy(r.Context())
if err != nil {
return baseData
}

View File

@ -0,0 +1,14 @@
CREATE TABLE zitadel.projections.privacy_policies (
id STRING NOT NULL,
creation_date TIMESTAMPTZ NULL,
change_date TIMESTAMPTZ NULL,
sequence INT8 NULL,
state INT2 NULL,
resource_owner TEXT,
is_default BOOLEAN,
privacy_link TEXT,
tos_link TEXT,
PRIMARY KEY (id)
);