feat(domain): define user repositories (#11059)

This pull request introduces a new set of domain models and repositories
for managing users within the new v3 structure. The goal is to establish
a clean, robust, and extensible foundation for user management.

### Summary

This PR accomplishes the following:

- **Polymorphic User Model**: Introduces a `User` model in user.go that
can represent either a `Human` or a `Machine` user. This provides a
unified way to handle different user types while allowing for specific
attributes and logic for each.
- **Repository Pattern**: Implements the repository pattern for
accessing and manipulating user data. This decouples the business logic
from the data storage implementation. The main repository interfaces
(`UserRepository`, `HumanUserRepository`, `MachineUserRepository`) are
now defined in `backend/v3/domain/user_repository.go`.
- **Comprehensive User Models**: The user.go file now also defines the
domain models for associated user data, including `UserMetadata`,
`IdentityProviderLink`, `Passkey`, `PersonalAccessToken`, and
`MachineKey`.
- **Generic Verification and Check System**: Introduces verification.go
and check.go to provide a standardized way of handling various
verification flows (e.g., email verification, OTP checks).
- **Generated Code**: Adds new generated files for enums
(`humangender_enumer.go`, `machinekeytype_enumer.go`,
`passkeytype_enumer.go`, `personalaccesstokentype_enumer.go`,
`userstate_enumer.go`, `usertype_enumer.go`) and mocks for the new
repositories.
- **Session Domain Refactoring**: Updates the session domain
(`backend/v3/domain/session*.go`) to align with the new user model
structure.

This foundational work paves the way for migrating user management logic
to the new `v3` backend, with a more maintainable and testable
architecture.

part of #10224

---------

Co-authored-by: Copilot <[email protected]>
Co-authored-by: Marco A. <[email protected]>
This commit is contained in:
Silvan
2025-11-25 11:54:32 +01:00
committed by GitHub
co-authored by Copilot Marco A.
parent 5beeb5738a
commit f5ce288ea5
25 changed files with 8317 additions and 926 deletions
+67
View File
@@ -0,0 +1,67 @@
package domain
import "time"
type Check struct {
Code []byte `db:"code"`
ExpiresAt *time.Time `db:"expires_at"`
FailedAttempts uint8 `db:"failed_attempts"`
}
type CheckType interface {
isCheckType()
}
type PasswordCheckType interface {
isPasswordCheckType()
}
// CheckTypeInit initializes a new check.
type CheckTypeInit struct {
// CreatedAt is the time when the check was created.
// If zero, the current time will be used.
CreatedAt time.Time
// Expiry is the duration after which the check expires.
Expiry *time.Duration
// Code to be used for the check.
Code []byte
}
// isCheckType implements [CheckType].
func (v *CheckTypeInit) isCheckType() {}
var _ CheckType = (*CheckTypeInit)(nil)
// CheckTypeFailed indicates that the check failed.
// It is used to increment the failed attempts counter.
type CheckTypeFailed struct {
FailedAt time.Time
}
// isCheckType implements [CheckType].
func (v *CheckTypeFailed) isCheckType() {}
// isPasswordCheckType implements [PasswordCheckType].
func (v *CheckTypeFailed) isPasswordCheckType() {}
var (
_ CheckType = (*CheckTypeFailed)(nil)
_ PasswordCheckType = (*CheckTypeFailed)(nil)
)
// CheckTypeSucceeded indicates that the check succeeded.
// It is used to reset the failed attempts counter.
type CheckTypeSucceeded struct {
SucceededAt time.Time
}
// isCheckType implements [CheckType].
func (v *CheckTypeSucceeded) isCheckType() {}
// isPasswordCheckType implements [PasswordCheckType].
func (v *CheckTypeSucceeded) isPasswordCheckType() {}
var (
_ CheckType = (*CheckTypeSucceeded)(nil)
_ PasswordCheckType = (*CheckTypeSucceeded)(nil)
)
+86
View File
@@ -0,0 +1,86 @@
// Code generated by "enumer -type HumanGender -transform lower -trimprefix HumanGender"; DO NOT EDIT.
package domain
import (
"fmt"
"strings"
)
const _HumanGenderName = "unspecifiedfemalemalediverse"
var _HumanGenderIndex = [...]uint8{0, 11, 17, 21, 28}
const _HumanGenderLowerName = "unspecifiedfemalemalediverse"
func (i HumanGender) String() string {
if i >= HumanGender(len(_HumanGenderIndex)-1) {
return fmt.Sprintf("HumanGender(%d)", i)
}
return _HumanGenderName[_HumanGenderIndex[i]:_HumanGenderIndex[i+1]]
}
// An "invalid array index" compiler error signifies that the constant values have changed.
// Re-run the stringer command to generate them again.
func _HumanGenderNoOp() {
var x [1]struct{}
_ = x[HumanGenderUnspecified-(0)]
_ = x[HumanGenderFemale-(1)]
_ = x[HumanGenderMale-(2)]
_ = x[HumanGenderDiverse-(3)]
}
var _HumanGenderValues = []HumanGender{HumanGenderUnspecified, HumanGenderFemale, HumanGenderMale, HumanGenderDiverse}
var _HumanGenderNameToValueMap = map[string]HumanGender{
_HumanGenderName[0:11]: HumanGenderUnspecified,
_HumanGenderLowerName[0:11]: HumanGenderUnspecified,
_HumanGenderName[11:17]: HumanGenderFemale,
_HumanGenderLowerName[11:17]: HumanGenderFemale,
_HumanGenderName[17:21]: HumanGenderMale,
_HumanGenderLowerName[17:21]: HumanGenderMale,
_HumanGenderName[21:28]: HumanGenderDiverse,
_HumanGenderLowerName[21:28]: HumanGenderDiverse,
}
var _HumanGenderNames = []string{
_HumanGenderName[0:11],
_HumanGenderName[11:17],
_HumanGenderName[17:21],
_HumanGenderName[21:28],
}
// HumanGenderString retrieves an enum value from the enum constants string name.
// Throws an error if the param is not part of the enum.
func HumanGenderString(s string) (HumanGender, error) {
if val, ok := _HumanGenderNameToValueMap[s]; ok {
return val, nil
}
if val, ok := _HumanGenderNameToValueMap[strings.ToLower(s)]; ok {
return val, nil
}
return 0, fmt.Errorf("%s does not belong to HumanGender values", s)
}
// HumanGenderValues returns all values of the enum
func HumanGenderValues() []HumanGender {
return _HumanGenderValues
}
// HumanGenderStrings returns a slice of all String values of the enum
func HumanGenderStrings() []string {
strs := make([]string, len(_HumanGenderNames))
copy(strs, _HumanGenderNames)
return strs
}
// IsAHumanGender returns "true" if the value is listed in the enum definition. "false" otherwise
func (i HumanGender) IsAHumanGender() bool {
for _, v := range _HumanGenderValues {
if i == v {
return true
}
}
return false
}
@@ -0,0 +1,82 @@
// Code generated by "enumer -type MachineKeyType -transform lower -trimprefix MachineKeyType"; DO NOT EDIT.
package domain
import (
"fmt"
"strings"
)
const _MachineKeyTypeName = "unspecifiedjsonnone"
var _MachineKeyTypeIndex = [...]uint8{0, 11, 15, 19}
const _MachineKeyTypeLowerName = "unspecifiedjsonnone"
func (i MachineKeyType) String() string {
if i >= MachineKeyType(len(_MachineKeyTypeIndex)-1) {
return fmt.Sprintf("MachineKeyType(%d)", i)
}
return _MachineKeyTypeName[_MachineKeyTypeIndex[i]:_MachineKeyTypeIndex[i+1]]
}
// An "invalid array index" compiler error signifies that the constant values have changed.
// Re-run the stringer command to generate them again.
func _MachineKeyTypeNoOp() {
var x [1]struct{}
_ = x[MachineKeyTypeUnspecified-(0)]
_ = x[MachineKeyTypeJSON-(1)]
_ = x[MachineKeyTypeNone-(2)]
}
var _MachineKeyTypeValues = []MachineKeyType{MachineKeyTypeUnspecified, MachineKeyTypeJSON, MachineKeyTypeNone}
var _MachineKeyTypeNameToValueMap = map[string]MachineKeyType{
_MachineKeyTypeName[0:11]: MachineKeyTypeUnspecified,
_MachineKeyTypeLowerName[0:11]: MachineKeyTypeUnspecified,
_MachineKeyTypeName[11:15]: MachineKeyTypeJSON,
_MachineKeyTypeLowerName[11:15]: MachineKeyTypeJSON,
_MachineKeyTypeName[15:19]: MachineKeyTypeNone,
_MachineKeyTypeLowerName[15:19]: MachineKeyTypeNone,
}
var _MachineKeyTypeNames = []string{
_MachineKeyTypeName[0:11],
_MachineKeyTypeName[11:15],
_MachineKeyTypeName[15:19],
}
// MachineKeyTypeString retrieves an enum value from the enum constants string name.
// Throws an error if the param is not part of the enum.
func MachineKeyTypeString(s string) (MachineKeyType, error) {
if val, ok := _MachineKeyTypeNameToValueMap[s]; ok {
return val, nil
}
if val, ok := _MachineKeyTypeNameToValueMap[strings.ToLower(s)]; ok {
return val, nil
}
return 0, fmt.Errorf("%s does not belong to MachineKeyType values", s)
}
// MachineKeyTypeValues returns all values of the enum
func MachineKeyTypeValues() []MachineKeyType {
return _MachineKeyTypeValues
}
// MachineKeyTypeStrings returns a slice of all String values of the enum
func MachineKeyTypeStrings() []string {
strs := make([]string, len(_MachineKeyTypeNames))
copy(strs, _MachineKeyTypeNames)
return strs
}
// IsAMachineKeyType returns "true" if the value is listed in the enum definition. "false" otherwise
func (i MachineKeyType) IsAMachineKeyType() bool {
for _, v := range _MachineKeyTypeValues {
if i == v {
return true
}
}
return false
}
File diff suppressed because it is too large Load Diff
+60 -59
View File
@@ -24,6 +24,7 @@ import (
type MockInstanceRepository struct { type MockInstanceRepository struct {
ctrl *gomock.Controller ctrl *gomock.Controller
recorder *MockInstanceRepositoryMockRecorder recorder *MockInstanceRepositoryMockRecorder
isgomock struct{}
} }
// MockInstanceRepositoryMockRecorder is the mock recorder for MockInstanceRepository. // MockInstanceRepositoryMockRecorder is the mock recorder for MockInstanceRepository.
@@ -120,17 +121,17 @@ func (c *MockInstanceRepositoryConsoleClientIDColumnCall) DoAndReturn(f func() d
} }
// Create mocks base method. // Create mocks base method.
func (m *MockInstanceRepository) Create(arg0 context.Context, arg1 database.QueryExecutor, arg2 *domain.Instance) error { func (m *MockInstanceRepository) Create(ctx context.Context, client database.QueryExecutor, instance *domain.Instance) error {
m.ctrl.T.Helper() m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Create", arg0, arg1, arg2) ret := m.ctrl.Call(m, "Create", ctx, client, instance)
ret0, _ := ret[0].(error) ret0, _ := ret[0].(error)
return ret0 return ret0
} }
// Create indicates an expected call of Create. // Create indicates an expected call of Create.
func (mr *MockInstanceRepositoryMockRecorder) Create(arg0, arg1, arg2 any) *MockInstanceRepositoryCreateCall { func (mr *MockInstanceRepositoryMockRecorder) Create(ctx, client, instance any) *MockInstanceRepositoryCreateCall {
mr.mock.ctrl.T.Helper() mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Create", reflect.TypeOf((*MockInstanceRepository)(nil).Create), arg0, arg1, arg2) call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Create", reflect.TypeOf((*MockInstanceRepository)(nil).Create), ctx, client, instance)
return &MockInstanceRepositoryCreateCall{Call: call} return &MockInstanceRepositoryCreateCall{Call: call}
} }
@@ -272,18 +273,18 @@ func (c *MockInstanceRepositoryDefaultOrgIDColumnCall) DoAndReturn(f func() data
} }
// Delete mocks base method. // Delete mocks base method.
func (m *MockInstanceRepository) Delete(arg0 context.Context, arg1 database.QueryExecutor, arg2 string) (int64, error) { func (m *MockInstanceRepository) Delete(ctx context.Context, client database.QueryExecutor, id string) (int64, error) {
m.ctrl.T.Helper() m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Delete", arg0, arg1, arg2) ret := m.ctrl.Call(m, "Delete", ctx, client, id)
ret0, _ := ret[0].(int64) ret0, _ := ret[0].(int64)
ret1, _ := ret[1].(error) ret1, _ := ret[1].(error)
return ret0, ret1 return ret0, ret1
} }
// Delete indicates an expected call of Delete. // Delete indicates an expected call of Delete.
func (mr *MockInstanceRepositoryMockRecorder) Delete(arg0, arg1, arg2 any) *MockInstanceRepositoryDeleteCall { func (mr *MockInstanceRepositoryMockRecorder) Delete(ctx, client, id any) *MockInstanceRepositoryDeleteCall {
mr.mock.ctrl.T.Helper() mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Delete", reflect.TypeOf((*MockInstanceRepository)(nil).Delete), arg0, arg1, arg2) call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Delete", reflect.TypeOf((*MockInstanceRepository)(nil).Delete), ctx, client, id)
return &MockInstanceRepositoryDeleteCall{Call: call} return &MockInstanceRepositoryDeleteCall{Call: call}
} }
@@ -311,17 +312,17 @@ func (c *MockInstanceRepositoryDeleteCall) DoAndReturn(f func(context.Context, d
} }
// ExistsDomain mocks base method. // ExistsDomain mocks base method.
func (m *MockInstanceRepository) ExistsDomain(arg0 database.Condition) database.Condition { func (m *MockInstanceRepository) ExistsDomain(cond database.Condition) database.Condition {
m.ctrl.T.Helper() m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "ExistsDomain", arg0) ret := m.ctrl.Call(m, "ExistsDomain", cond)
ret0, _ := ret[0].(database.Condition) ret0, _ := ret[0].(database.Condition)
return ret0 return ret0
} }
// ExistsDomain indicates an expected call of ExistsDomain. // ExistsDomain indicates an expected call of ExistsDomain.
func (mr *MockInstanceRepositoryMockRecorder) ExistsDomain(arg0 any) *MockInstanceRepositoryExistsDomainCall { func (mr *MockInstanceRepositoryMockRecorder) ExistsDomain(cond any) *MockInstanceRepositoryExistsDomainCall {
mr.mock.ctrl.T.Helper() mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ExistsDomain", reflect.TypeOf((*MockInstanceRepository)(nil).ExistsDomain), arg0) call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ExistsDomain", reflect.TypeOf((*MockInstanceRepository)(nil).ExistsDomain), cond)
return &MockInstanceRepositoryExistsDomainCall{Call: call} return &MockInstanceRepositoryExistsDomainCall{Call: call}
} }
@@ -349,10 +350,10 @@ func (c *MockInstanceRepositoryExistsDomainCall) DoAndReturn(f func(database.Con
} }
// Get mocks base method. // Get mocks base method.
func (m *MockInstanceRepository) Get(arg0 context.Context, arg1 database.QueryExecutor, arg2 ...database.QueryOption) (*domain.Instance, error) { func (m *MockInstanceRepository) Get(ctx context.Context, client database.QueryExecutor, opts ...database.QueryOption) (*domain.Instance, error) {
m.ctrl.T.Helper() m.ctrl.T.Helper()
varargs := []any{arg0, arg1} varargs := []any{ctx, client}
for _, a := range arg2 { for _, a := range opts {
varargs = append(varargs, a) varargs = append(varargs, a)
} }
ret := m.ctrl.Call(m, "Get", varargs...) ret := m.ctrl.Call(m, "Get", varargs...)
@@ -362,9 +363,9 @@ func (m *MockInstanceRepository) Get(arg0 context.Context, arg1 database.QueryEx
} }
// Get indicates an expected call of Get. // Get indicates an expected call of Get.
func (mr *MockInstanceRepositoryMockRecorder) Get(arg0, arg1 any, arg2 ...any) *MockInstanceRepositoryGetCall { func (mr *MockInstanceRepositoryMockRecorder) Get(ctx, client any, opts ...any) *MockInstanceRepositoryGetCall {
mr.mock.ctrl.T.Helper() mr.mock.ctrl.T.Helper()
varargs := append([]any{arg0, arg1}, arg2...) varargs := append([]any{ctx, client}, opts...)
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Get", reflect.TypeOf((*MockInstanceRepository)(nil).Get), varargs...) call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Get", reflect.TypeOf((*MockInstanceRepository)(nil).Get), varargs...)
return &MockInstanceRepositoryGetCall{Call: call} return &MockInstanceRepositoryGetCall{Call: call}
} }
@@ -469,17 +470,17 @@ func (c *MockInstanceRepositoryIDColumnCall) DoAndReturn(f func() database.Colum
} }
// IDCondition mocks base method. // IDCondition mocks base method.
func (m *MockInstanceRepository) IDCondition(arg0 string) database.Condition { func (m *MockInstanceRepository) IDCondition(instanceID string) database.Condition {
m.ctrl.T.Helper() m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "IDCondition", arg0) ret := m.ctrl.Call(m, "IDCondition", instanceID)
ret0, _ := ret[0].(database.Condition) ret0, _ := ret[0].(database.Condition)
return ret0 return ret0
} }
// IDCondition indicates an expected call of IDCondition. // IDCondition indicates an expected call of IDCondition.
func (mr *MockInstanceRepositoryMockRecorder) IDCondition(arg0 any) *MockInstanceRepositoryIDConditionCall { func (mr *MockInstanceRepositoryMockRecorder) IDCondition(instanceID any) *MockInstanceRepositoryIDConditionCall {
mr.mock.ctrl.T.Helper() mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "IDCondition", reflect.TypeOf((*MockInstanceRepository)(nil).IDCondition), arg0) call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "IDCondition", reflect.TypeOf((*MockInstanceRepository)(nil).IDCondition), instanceID)
return &MockInstanceRepositoryIDConditionCall{Call: call} return &MockInstanceRepositoryIDConditionCall{Call: call}
} }
@@ -507,10 +508,10 @@ func (c *MockInstanceRepositoryIDConditionCall) DoAndReturn(f func(string) datab
} }
// List mocks base method. // List mocks base method.
func (m *MockInstanceRepository) List(arg0 context.Context, arg1 database.QueryExecutor, arg2 ...database.QueryOption) ([]*domain.Instance, error) { func (m *MockInstanceRepository) List(ctx context.Context, client database.QueryExecutor, opts ...database.QueryOption) ([]*domain.Instance, error) {
m.ctrl.T.Helper() m.ctrl.T.Helper()
varargs := []any{arg0, arg1} varargs := []any{ctx, client}
for _, a := range arg2 { for _, a := range opts {
varargs = append(varargs, a) varargs = append(varargs, a)
} }
ret := m.ctrl.Call(m, "List", varargs...) ret := m.ctrl.Call(m, "List", varargs...)
@@ -520,9 +521,9 @@ func (m *MockInstanceRepository) List(arg0 context.Context, arg1 database.QueryE
} }
// List indicates an expected call of List. // List indicates an expected call of List.
func (mr *MockInstanceRepositoryMockRecorder) List(arg0, arg1 any, arg2 ...any) *MockInstanceRepositoryListCall { func (mr *MockInstanceRepositoryMockRecorder) List(ctx, client any, opts ...any) *MockInstanceRepositoryListCall {
mr.mock.ctrl.T.Helper() mr.mock.ctrl.T.Helper()
varargs := append([]any{arg0, arg1}, arg2...) varargs := append([]any{ctx, client}, opts...)
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "List", reflect.TypeOf((*MockInstanceRepository)(nil).List), varargs...) call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "List", reflect.TypeOf((*MockInstanceRepository)(nil).List), varargs...)
return &MockInstanceRepositoryListCall{Call: call} return &MockInstanceRepositoryListCall{Call: call}
} }
@@ -627,17 +628,17 @@ func (c *MockInstanceRepositoryNameColumnCall) DoAndReturn(f func() database.Col
} }
// NameCondition mocks base method. // NameCondition mocks base method.
func (m *MockInstanceRepository) NameCondition(arg0 database.TextOperation, arg1 string) database.Condition { func (m *MockInstanceRepository) NameCondition(op database.TextOperation, name string) database.Condition {
m.ctrl.T.Helper() m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "NameCondition", arg0, arg1) ret := m.ctrl.Call(m, "NameCondition", op, name)
ret0, _ := ret[0].(database.Condition) ret0, _ := ret[0].(database.Condition)
return ret0 return ret0
} }
// NameCondition indicates an expected call of NameCondition. // NameCondition indicates an expected call of NameCondition.
func (mr *MockInstanceRepositoryMockRecorder) NameCondition(arg0, arg1 any) *MockInstanceRepositoryNameConditionCall { func (mr *MockInstanceRepositoryMockRecorder) NameCondition(op, name any) *MockInstanceRepositoryNameConditionCall {
mr.mock.ctrl.T.Helper() mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "NameCondition", reflect.TypeOf((*MockInstanceRepository)(nil).NameCondition), arg0, arg1) call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "NameCondition", reflect.TypeOf((*MockInstanceRepository)(nil).NameCondition), op, name)
return &MockInstanceRepositoryNameConditionCall{Call: call} return &MockInstanceRepositoryNameConditionCall{Call: call}
} }
@@ -703,17 +704,17 @@ func (c *MockInstanceRepositoryPrimaryKeyColumnsCall) DoAndReturn(f func() []dat
} }
// PrimaryKeyCondition mocks base method. // PrimaryKeyCondition mocks base method.
func (m *MockInstanceRepository) PrimaryKeyCondition(arg0 string) database.Condition { func (m *MockInstanceRepository) PrimaryKeyCondition(instanceID string) database.Condition {
m.ctrl.T.Helper() m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "PrimaryKeyCondition", arg0) ret := m.ctrl.Call(m, "PrimaryKeyCondition", instanceID)
ret0, _ := ret[0].(database.Condition) ret0, _ := ret[0].(database.Condition)
return ret0 return ret0
} }
// PrimaryKeyCondition indicates an expected call of PrimaryKeyCondition. // PrimaryKeyCondition indicates an expected call of PrimaryKeyCondition.
func (mr *MockInstanceRepositoryMockRecorder) PrimaryKeyCondition(arg0 any) *MockInstanceRepositoryPrimaryKeyConditionCall { func (mr *MockInstanceRepositoryMockRecorder) PrimaryKeyCondition(instanceID any) *MockInstanceRepositoryPrimaryKeyConditionCall {
mr.mock.ctrl.T.Helper() mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PrimaryKeyCondition", reflect.TypeOf((*MockInstanceRepository)(nil).PrimaryKeyCondition), arg0) call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PrimaryKeyCondition", reflect.TypeOf((*MockInstanceRepository)(nil).PrimaryKeyCondition), instanceID)
return &MockInstanceRepositoryPrimaryKeyConditionCall{Call: call} return &MockInstanceRepositoryPrimaryKeyConditionCall{Call: call}
} }
@@ -741,17 +742,17 @@ func (c *MockInstanceRepositoryPrimaryKeyConditionCall) DoAndReturn(f func(strin
} }
// SetConsoleAppID mocks base method. // SetConsoleAppID mocks base method.
func (m *MockInstanceRepository) SetConsoleAppID(arg0 string) database.Change { func (m *MockInstanceRepository) SetConsoleAppID(id string) database.Change {
m.ctrl.T.Helper() m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "SetConsoleAppID", arg0) ret := m.ctrl.Call(m, "SetConsoleAppID", id)
ret0, _ := ret[0].(database.Change) ret0, _ := ret[0].(database.Change)
return ret0 return ret0
} }
// SetConsoleAppID indicates an expected call of SetConsoleAppID. // SetConsoleAppID indicates an expected call of SetConsoleAppID.
func (mr *MockInstanceRepositoryMockRecorder) SetConsoleAppID(arg0 any) *MockInstanceRepositorySetConsoleAppIDCall { func (mr *MockInstanceRepositoryMockRecorder) SetConsoleAppID(id any) *MockInstanceRepositorySetConsoleAppIDCall {
mr.mock.ctrl.T.Helper() mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetConsoleAppID", reflect.TypeOf((*MockInstanceRepository)(nil).SetConsoleAppID), arg0) call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetConsoleAppID", reflect.TypeOf((*MockInstanceRepository)(nil).SetConsoleAppID), id)
return &MockInstanceRepositorySetConsoleAppIDCall{Call: call} return &MockInstanceRepositorySetConsoleAppIDCall{Call: call}
} }
@@ -779,17 +780,17 @@ func (c *MockInstanceRepositorySetConsoleAppIDCall) DoAndReturn(f func(string) d
} }
// SetConsoleClientID mocks base method. // SetConsoleClientID mocks base method.
func (m *MockInstanceRepository) SetConsoleClientID(arg0 string) database.Change { func (m *MockInstanceRepository) SetConsoleClientID(id string) database.Change {
m.ctrl.T.Helper() m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "SetConsoleClientID", arg0) ret := m.ctrl.Call(m, "SetConsoleClientID", id)
ret0, _ := ret[0].(database.Change) ret0, _ := ret[0].(database.Change)
return ret0 return ret0
} }
// SetConsoleClientID indicates an expected call of SetConsoleClientID. // SetConsoleClientID indicates an expected call of SetConsoleClientID.
func (mr *MockInstanceRepositoryMockRecorder) SetConsoleClientID(arg0 any) *MockInstanceRepositorySetConsoleClientIDCall { func (mr *MockInstanceRepositoryMockRecorder) SetConsoleClientID(id any) *MockInstanceRepositorySetConsoleClientIDCall {
mr.mock.ctrl.T.Helper() mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetConsoleClientID", reflect.TypeOf((*MockInstanceRepository)(nil).SetConsoleClientID), arg0) call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetConsoleClientID", reflect.TypeOf((*MockInstanceRepository)(nil).SetConsoleClientID), id)
return &MockInstanceRepositorySetConsoleClientIDCall{Call: call} return &MockInstanceRepositorySetConsoleClientIDCall{Call: call}
} }
@@ -855,17 +856,17 @@ func (c *MockInstanceRepositorySetDefaultLanguageCall) DoAndReturn(f func(langua
} }
// SetDefaultOrg mocks base method. // SetDefaultOrg mocks base method.
func (m *MockInstanceRepository) SetDefaultOrg(arg0 string) database.Change { func (m *MockInstanceRepository) SetDefaultOrg(id string) database.Change {
m.ctrl.T.Helper() m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "SetDefaultOrg", arg0) ret := m.ctrl.Call(m, "SetDefaultOrg", id)
ret0, _ := ret[0].(database.Change) ret0, _ := ret[0].(database.Change)
return ret0 return ret0
} }
// SetDefaultOrg indicates an expected call of SetDefaultOrg. // SetDefaultOrg indicates an expected call of SetDefaultOrg.
func (mr *MockInstanceRepositoryMockRecorder) SetDefaultOrg(arg0 any) *MockInstanceRepositorySetDefaultOrgCall { func (mr *MockInstanceRepositoryMockRecorder) SetDefaultOrg(id any) *MockInstanceRepositorySetDefaultOrgCall {
mr.mock.ctrl.T.Helper() mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetDefaultOrg", reflect.TypeOf((*MockInstanceRepository)(nil).SetDefaultOrg), arg0) call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetDefaultOrg", reflect.TypeOf((*MockInstanceRepository)(nil).SetDefaultOrg), id)
return &MockInstanceRepositorySetDefaultOrgCall{Call: call} return &MockInstanceRepositorySetDefaultOrgCall{Call: call}
} }
@@ -893,17 +894,17 @@ func (c *MockInstanceRepositorySetDefaultOrgCall) DoAndReturn(f func(string) dat
} }
// SetIAMProject mocks base method. // SetIAMProject mocks base method.
func (m *MockInstanceRepository) SetIAMProject(arg0 string) database.Change { func (m *MockInstanceRepository) SetIAMProject(id string) database.Change {
m.ctrl.T.Helper() m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "SetIAMProject", arg0) ret := m.ctrl.Call(m, "SetIAMProject", id)
ret0, _ := ret[0].(database.Change) ret0, _ := ret[0].(database.Change)
return ret0 return ret0
} }
// SetIAMProject indicates an expected call of SetIAMProject. // SetIAMProject indicates an expected call of SetIAMProject.
func (mr *MockInstanceRepositoryMockRecorder) SetIAMProject(arg0 any) *MockInstanceRepositorySetIAMProjectCall { func (mr *MockInstanceRepositoryMockRecorder) SetIAMProject(id any) *MockInstanceRepositorySetIAMProjectCall {
mr.mock.ctrl.T.Helper() mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetIAMProject", reflect.TypeOf((*MockInstanceRepository)(nil).SetIAMProject), arg0) call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetIAMProject", reflect.TypeOf((*MockInstanceRepository)(nil).SetIAMProject), id)
return &MockInstanceRepositorySetIAMProjectCall{Call: call} return &MockInstanceRepositorySetIAMProjectCall{Call: call}
} }
@@ -931,17 +932,17 @@ func (c *MockInstanceRepositorySetIAMProjectCall) DoAndReturn(f func(string) dat
} }
// SetName mocks base method. // SetName mocks base method.
func (m *MockInstanceRepository) SetName(arg0 string) database.Change { func (m *MockInstanceRepository) SetName(name string) database.Change {
m.ctrl.T.Helper() m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "SetName", arg0) ret := m.ctrl.Call(m, "SetName", name)
ret0, _ := ret[0].(database.Change) ret0, _ := ret[0].(database.Change)
return ret0 return ret0
} }
// SetName indicates an expected call of SetName. // SetName indicates an expected call of SetName.
func (mr *MockInstanceRepositoryMockRecorder) SetName(arg0 any) *MockInstanceRepositorySetNameCall { func (mr *MockInstanceRepositoryMockRecorder) SetName(name any) *MockInstanceRepositorySetNameCall {
mr.mock.ctrl.T.Helper() mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetName", reflect.TypeOf((*MockInstanceRepository)(nil).SetName), arg0) call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetName", reflect.TypeOf((*MockInstanceRepository)(nil).SetName), name)
return &MockInstanceRepositorySetNameCall{Call: call} return &MockInstanceRepositorySetNameCall{Call: call}
} }
@@ -1007,10 +1008,10 @@ func (c *MockInstanceRepositorySetUpdatedAtCall) DoAndReturn(f func(time.Time) d
} }
// Update mocks base method. // Update mocks base method.
func (m *MockInstanceRepository) Update(arg0 context.Context, arg1 database.QueryExecutor, arg2 string, arg3 ...database.Change) (int64, error) { func (m *MockInstanceRepository) Update(ctx context.Context, client database.QueryExecutor, id string, changes ...database.Change) (int64, error) {
m.ctrl.T.Helper() m.ctrl.T.Helper()
varargs := []any{arg0, arg1, arg2} varargs := []any{ctx, client, id}
for _, a := range arg3 { for _, a := range changes {
varargs = append(varargs, a) varargs = append(varargs, a)
} }
ret := m.ctrl.Call(m, "Update", varargs...) ret := m.ctrl.Call(m, "Update", varargs...)
@@ -1020,9 +1021,9 @@ func (m *MockInstanceRepository) Update(arg0 context.Context, arg1 database.Quer
} }
// Update indicates an expected call of Update. // Update indicates an expected call of Update.
func (mr *MockInstanceRepositoryMockRecorder) Update(arg0, arg1, arg2 any, arg3 ...any) *MockInstanceRepositoryUpdateCall { func (mr *MockInstanceRepositoryMockRecorder) Update(ctx, client, id any, changes ...any) *MockInstanceRepositoryUpdateCall {
mr.mock.ctrl.T.Helper() mr.mock.ctrl.T.Helper()
varargs := append([]any{arg0, arg1, arg2}, arg3...) varargs := append([]any{ctx, client, id}, changes...)
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Update", reflect.TypeOf((*MockInstanceRepository)(nil).Update), varargs...) call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Update", reflect.TypeOf((*MockInstanceRepository)(nil).Update), varargs...)
return &MockInstanceRepositoryUpdateCall{Call: call} return &MockInstanceRepositoryUpdateCall{Call: call}
} }
+48 -47
View File
@@ -23,6 +23,7 @@ import (
type MockInstanceDomainRepository struct { type MockInstanceDomainRepository struct {
ctrl *gomock.Controller ctrl *gomock.Controller
recorder *MockInstanceDomainRepositoryMockRecorder recorder *MockInstanceDomainRepositoryMockRecorder
isgomock struct{}
} }
// MockInstanceDomainRepositoryMockRecorder is the mock recorder for MockInstanceDomainRepository. // MockInstanceDomainRepositoryMockRecorder is the mock recorder for MockInstanceDomainRepository.
@@ -43,17 +44,17 @@ func (m *MockInstanceDomainRepository) EXPECT() *MockInstanceDomainRepositoryMoc
} }
// Add mocks base method. // Add mocks base method.
func (m *MockInstanceDomainRepository) Add(arg0 context.Context, arg1 database.QueryExecutor, arg2 *domain.AddInstanceDomain) error { func (m *MockInstanceDomainRepository) Add(ctx context.Context, client database.QueryExecutor, arg2 *domain.AddInstanceDomain) error {
m.ctrl.T.Helper() m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Add", arg0, arg1, arg2) ret := m.ctrl.Call(m, "Add", ctx, client, arg2)
ret0, _ := ret[0].(error) ret0, _ := ret[0].(error)
return ret0 return ret0
} }
// Add indicates an expected call of Add. // Add indicates an expected call of Add.
func (mr *MockInstanceDomainRepositoryMockRecorder) Add(arg0, arg1, arg2 any) *MockInstanceDomainRepositoryAddCall { func (mr *MockInstanceDomainRepositoryMockRecorder) Add(ctx, client, arg2 any) *MockInstanceDomainRepositoryAddCall {
mr.mock.ctrl.T.Helper() mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Add", reflect.TypeOf((*MockInstanceDomainRepository)(nil).Add), arg0, arg1, arg2) call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Add", reflect.TypeOf((*MockInstanceDomainRepository)(nil).Add), ctx, client, arg2)
return &MockInstanceDomainRepositoryAddCall{Call: call} return &MockInstanceDomainRepositoryAddCall{Call: call}
} }
@@ -157,17 +158,17 @@ func (c *MockInstanceDomainRepositoryDomainColumnCall) DoAndReturn(f func() data
} }
// DomainCondition mocks base method. // DomainCondition mocks base method.
func (m *MockInstanceDomainRepository) DomainCondition(arg0 database.TextOperation, arg1 string) database.Condition { func (m *MockInstanceDomainRepository) DomainCondition(op database.TextOperation, arg1 string) database.Condition {
m.ctrl.T.Helper() m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "DomainCondition", arg0, arg1) ret := m.ctrl.Call(m, "DomainCondition", op, arg1)
ret0, _ := ret[0].(database.Condition) ret0, _ := ret[0].(database.Condition)
return ret0 return ret0
} }
// DomainCondition indicates an expected call of DomainCondition. // DomainCondition indicates an expected call of DomainCondition.
func (mr *MockInstanceDomainRepositoryMockRecorder) DomainCondition(arg0, arg1 any) *MockInstanceDomainRepositoryDomainConditionCall { func (mr *MockInstanceDomainRepositoryMockRecorder) DomainCondition(op, arg1 any) *MockInstanceDomainRepositoryDomainConditionCall {
mr.mock.ctrl.T.Helper() mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DomainCondition", reflect.TypeOf((*MockInstanceDomainRepository)(nil).DomainCondition), arg0, arg1) call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DomainCondition", reflect.TypeOf((*MockInstanceDomainRepository)(nil).DomainCondition), op, arg1)
return &MockInstanceDomainRepositoryDomainConditionCall{Call: call} return &MockInstanceDomainRepositoryDomainConditionCall{Call: call}
} }
@@ -195,10 +196,10 @@ func (c *MockInstanceDomainRepositoryDomainConditionCall) DoAndReturn(f func(dat
} }
// Get mocks base method. // Get mocks base method.
func (m *MockInstanceDomainRepository) Get(arg0 context.Context, arg1 database.QueryExecutor, arg2 ...database.QueryOption) (*domain.InstanceDomain, error) { func (m *MockInstanceDomainRepository) Get(ctx context.Context, client database.QueryExecutor, opts ...database.QueryOption) (*domain.InstanceDomain, error) {
m.ctrl.T.Helper() m.ctrl.T.Helper()
varargs := []any{arg0, arg1} varargs := []any{ctx, client}
for _, a := range arg2 { for _, a := range opts {
varargs = append(varargs, a) varargs = append(varargs, a)
} }
ret := m.ctrl.Call(m, "Get", varargs...) ret := m.ctrl.Call(m, "Get", varargs...)
@@ -208,9 +209,9 @@ func (m *MockInstanceDomainRepository) Get(arg0 context.Context, arg1 database.Q
} }
// Get indicates an expected call of Get. // Get indicates an expected call of Get.
func (mr *MockInstanceDomainRepositoryMockRecorder) Get(arg0, arg1 any, arg2 ...any) *MockInstanceDomainRepositoryGetCall { func (mr *MockInstanceDomainRepositoryMockRecorder) Get(ctx, client any, opts ...any) *MockInstanceDomainRepositoryGetCall {
mr.mock.ctrl.T.Helper() mr.mock.ctrl.T.Helper()
varargs := append([]any{arg0, arg1}, arg2...) varargs := append([]any{ctx, client}, opts...)
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Get", reflect.TypeOf((*MockInstanceDomainRepository)(nil).Get), varargs...) call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Get", reflect.TypeOf((*MockInstanceDomainRepository)(nil).Get), varargs...)
return &MockInstanceDomainRepositoryGetCall{Call: call} return &MockInstanceDomainRepositoryGetCall{Call: call}
} }
@@ -277,17 +278,17 @@ func (c *MockInstanceDomainRepositoryInstanceIDColumnCall) DoAndReturn(f func()
} }
// InstanceIDCondition mocks base method. // InstanceIDCondition mocks base method.
func (m *MockInstanceDomainRepository) InstanceIDCondition(arg0 string) database.Condition { func (m *MockInstanceDomainRepository) InstanceIDCondition(instanceID string) database.Condition {
m.ctrl.T.Helper() m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "InstanceIDCondition", arg0) ret := m.ctrl.Call(m, "InstanceIDCondition", instanceID)
ret0, _ := ret[0].(database.Condition) ret0, _ := ret[0].(database.Condition)
return ret0 return ret0
} }
// InstanceIDCondition indicates an expected call of InstanceIDCondition. // InstanceIDCondition indicates an expected call of InstanceIDCondition.
func (mr *MockInstanceDomainRepositoryMockRecorder) InstanceIDCondition(arg0 any) *MockInstanceDomainRepositoryInstanceIDConditionCall { func (mr *MockInstanceDomainRepositoryMockRecorder) InstanceIDCondition(instanceID any) *MockInstanceDomainRepositoryInstanceIDConditionCall {
mr.mock.ctrl.T.Helper() mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "InstanceIDCondition", reflect.TypeOf((*MockInstanceDomainRepository)(nil).InstanceIDCondition), arg0) call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "InstanceIDCondition", reflect.TypeOf((*MockInstanceDomainRepository)(nil).InstanceIDCondition), instanceID)
return &MockInstanceDomainRepositoryInstanceIDConditionCall{Call: call} return &MockInstanceDomainRepositoryInstanceIDConditionCall{Call: call}
} }
@@ -391,17 +392,17 @@ func (c *MockInstanceDomainRepositoryIsPrimaryColumnCall) DoAndReturn(f func() d
} }
// IsPrimaryCondition mocks base method. // IsPrimaryCondition mocks base method.
func (m *MockInstanceDomainRepository) IsPrimaryCondition(arg0 bool) database.Condition { func (m *MockInstanceDomainRepository) IsPrimaryCondition(isPrimary bool) database.Condition {
m.ctrl.T.Helper() m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "IsPrimaryCondition", arg0) ret := m.ctrl.Call(m, "IsPrimaryCondition", isPrimary)
ret0, _ := ret[0].(database.Condition) ret0, _ := ret[0].(database.Condition)
return ret0 return ret0
} }
// IsPrimaryCondition indicates an expected call of IsPrimaryCondition. // IsPrimaryCondition indicates an expected call of IsPrimaryCondition.
func (mr *MockInstanceDomainRepositoryMockRecorder) IsPrimaryCondition(arg0 any) *MockInstanceDomainRepositoryIsPrimaryConditionCall { func (mr *MockInstanceDomainRepositoryMockRecorder) IsPrimaryCondition(isPrimary any) *MockInstanceDomainRepositoryIsPrimaryConditionCall {
mr.mock.ctrl.T.Helper() mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "IsPrimaryCondition", reflect.TypeOf((*MockInstanceDomainRepository)(nil).IsPrimaryCondition), arg0) call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "IsPrimaryCondition", reflect.TypeOf((*MockInstanceDomainRepository)(nil).IsPrimaryCondition), isPrimary)
return &MockInstanceDomainRepositoryIsPrimaryConditionCall{Call: call} return &MockInstanceDomainRepositoryIsPrimaryConditionCall{Call: call}
} }
@@ -429,10 +430,10 @@ func (c *MockInstanceDomainRepositoryIsPrimaryConditionCall) DoAndReturn(f func(
} }
// List mocks base method. // List mocks base method.
func (m *MockInstanceDomainRepository) List(arg0 context.Context, arg1 database.QueryExecutor, arg2 ...database.QueryOption) ([]*domain.InstanceDomain, error) { func (m *MockInstanceDomainRepository) List(ctx context.Context, client database.QueryExecutor, opts ...database.QueryOption) ([]*domain.InstanceDomain, error) {
m.ctrl.T.Helper() m.ctrl.T.Helper()
varargs := []any{arg0, arg1} varargs := []any{ctx, client}
for _, a := range arg2 { for _, a := range opts {
varargs = append(varargs, a) varargs = append(varargs, a)
} }
ret := m.ctrl.Call(m, "List", varargs...) ret := m.ctrl.Call(m, "List", varargs...)
@@ -442,9 +443,9 @@ func (m *MockInstanceDomainRepository) List(arg0 context.Context, arg1 database.
} }
// List indicates an expected call of List. // List indicates an expected call of List.
func (mr *MockInstanceDomainRepositoryMockRecorder) List(arg0, arg1 any, arg2 ...any) *MockInstanceDomainRepositoryListCall { func (mr *MockInstanceDomainRepositoryMockRecorder) List(ctx, client any, opts ...any) *MockInstanceDomainRepositoryListCall {
mr.mock.ctrl.T.Helper() mr.mock.ctrl.T.Helper()
varargs := append([]any{arg0, arg1}, arg2...) varargs := append([]any{ctx, client}, opts...)
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "List", reflect.TypeOf((*MockInstanceDomainRepository)(nil).List), varargs...) call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "List", reflect.TypeOf((*MockInstanceDomainRepository)(nil).List), varargs...)
return &MockInstanceDomainRepositoryListCall{Call: call} return &MockInstanceDomainRepositoryListCall{Call: call}
} }
@@ -549,18 +550,18 @@ func (c *MockInstanceDomainRepositoryPrimaryKeyConditionCall) DoAndReturn(f func
} }
// Remove mocks base method. // Remove mocks base method.
func (m *MockInstanceDomainRepository) Remove(arg0 context.Context, arg1 database.QueryExecutor, arg2 database.Condition) (int64, error) { func (m *MockInstanceDomainRepository) Remove(ctx context.Context, client database.QueryExecutor, condition database.Condition) (int64, error) {
m.ctrl.T.Helper() m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Remove", arg0, arg1, arg2) ret := m.ctrl.Call(m, "Remove", ctx, client, condition)
ret0, _ := ret[0].(int64) ret0, _ := ret[0].(int64)
ret1, _ := ret[1].(error) ret1, _ := ret[1].(error)
return ret0, ret1 return ret0, ret1
} }
// Remove indicates an expected call of Remove. // Remove indicates an expected call of Remove.
func (mr *MockInstanceDomainRepositoryMockRecorder) Remove(arg0, arg1, arg2 any) *MockInstanceDomainRepositoryRemoveCall { func (mr *MockInstanceDomainRepositoryMockRecorder) Remove(ctx, client, condition any) *MockInstanceDomainRepositoryRemoveCall {
mr.mock.ctrl.T.Helper() mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Remove", reflect.TypeOf((*MockInstanceDomainRepository)(nil).Remove), arg0, arg1, arg2) call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Remove", reflect.TypeOf((*MockInstanceDomainRepository)(nil).Remove), ctx, client, condition)
return &MockInstanceDomainRepositoryRemoveCall{Call: call} return &MockInstanceDomainRepositoryRemoveCall{Call: call}
} }
@@ -626,17 +627,17 @@ func (c *MockInstanceDomainRepositorySetPrimaryCall) DoAndReturn(f func() databa
} }
// SetType mocks base method. // SetType mocks base method.
func (m *MockInstanceDomainRepository) SetType(arg0 domain.DomainType) database.Change { func (m *MockInstanceDomainRepository) SetType(typ domain.DomainType) database.Change {
m.ctrl.T.Helper() m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "SetType", arg0) ret := m.ctrl.Call(m, "SetType", typ)
ret0, _ := ret[0].(database.Change) ret0, _ := ret[0].(database.Change)
return ret0 return ret0
} }
// SetType indicates an expected call of SetType. // SetType indicates an expected call of SetType.
func (mr *MockInstanceDomainRepositoryMockRecorder) SetType(arg0 any) *MockInstanceDomainRepositorySetTypeCall { func (mr *MockInstanceDomainRepositoryMockRecorder) SetType(typ any) *MockInstanceDomainRepositorySetTypeCall {
mr.mock.ctrl.T.Helper() mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetType", reflect.TypeOf((*MockInstanceDomainRepository)(nil).SetType), arg0) call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetType", reflect.TypeOf((*MockInstanceDomainRepository)(nil).SetType), typ)
return &MockInstanceDomainRepositorySetTypeCall{Call: call} return &MockInstanceDomainRepositorySetTypeCall{Call: call}
} }
@@ -664,17 +665,17 @@ func (c *MockInstanceDomainRepositorySetTypeCall) DoAndReturn(f func(domain.Doma
} }
// SetUpdatedAt mocks base method. // SetUpdatedAt mocks base method.
func (m *MockInstanceDomainRepository) SetUpdatedAt(arg0 time.Time) database.Change { func (m *MockInstanceDomainRepository) SetUpdatedAt(t time.Time) database.Change {
m.ctrl.T.Helper() m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "SetUpdatedAt", arg0) ret := m.ctrl.Call(m, "SetUpdatedAt", t)
ret0, _ := ret[0].(database.Change) ret0, _ := ret[0].(database.Change)
return ret0 return ret0
} }
// SetUpdatedAt indicates an expected call of SetUpdatedAt. // SetUpdatedAt indicates an expected call of SetUpdatedAt.
func (mr *MockInstanceDomainRepositoryMockRecorder) SetUpdatedAt(arg0 any) *MockInstanceDomainRepositorySetUpdatedAtCall { func (mr *MockInstanceDomainRepositoryMockRecorder) SetUpdatedAt(t any) *MockInstanceDomainRepositorySetUpdatedAtCall {
mr.mock.ctrl.T.Helper() mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetUpdatedAt", reflect.TypeOf((*MockInstanceDomainRepository)(nil).SetUpdatedAt), arg0) call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetUpdatedAt", reflect.TypeOf((*MockInstanceDomainRepository)(nil).SetUpdatedAt), t)
return &MockInstanceDomainRepositorySetUpdatedAtCall{Call: call} return &MockInstanceDomainRepositorySetUpdatedAtCall{Call: call}
} }
@@ -740,17 +741,17 @@ func (c *MockInstanceDomainRepositoryTypeColumnCall) DoAndReturn(f func() databa
} }
// TypeCondition mocks base method. // TypeCondition mocks base method.
func (m *MockInstanceDomainRepository) TypeCondition(arg0 domain.DomainType) database.Condition { func (m *MockInstanceDomainRepository) TypeCondition(typ domain.DomainType) database.Condition {
m.ctrl.T.Helper() m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "TypeCondition", arg0) ret := m.ctrl.Call(m, "TypeCondition", typ)
ret0, _ := ret[0].(database.Condition) ret0, _ := ret[0].(database.Condition)
return ret0 return ret0
} }
// TypeCondition indicates an expected call of TypeCondition. // TypeCondition indicates an expected call of TypeCondition.
func (mr *MockInstanceDomainRepositoryMockRecorder) TypeCondition(arg0 any) *MockInstanceDomainRepositoryTypeConditionCall { func (mr *MockInstanceDomainRepositoryMockRecorder) TypeCondition(typ any) *MockInstanceDomainRepositoryTypeConditionCall {
mr.mock.ctrl.T.Helper() mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "TypeCondition", reflect.TypeOf((*MockInstanceDomainRepository)(nil).TypeCondition), arg0) call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "TypeCondition", reflect.TypeOf((*MockInstanceDomainRepository)(nil).TypeCondition), typ)
return &MockInstanceDomainRepositoryTypeConditionCall{Call: call} return &MockInstanceDomainRepositoryTypeConditionCall{Call: call}
} }
@@ -778,10 +779,10 @@ func (c *MockInstanceDomainRepositoryTypeConditionCall) DoAndReturn(f func(domai
} }
// Update mocks base method. // Update mocks base method.
func (m *MockInstanceDomainRepository) Update(arg0 context.Context, arg1 database.QueryExecutor, arg2 database.Condition, arg3 ...database.Change) (int64, error) { func (m *MockInstanceDomainRepository) Update(ctx context.Context, client database.QueryExecutor, condition database.Condition, changes ...database.Change) (int64, error) {
m.ctrl.T.Helper() m.ctrl.T.Helper()
varargs := []any{arg0, arg1, arg2} varargs := []any{ctx, client, condition}
for _, a := range arg3 { for _, a := range changes {
varargs = append(varargs, a) varargs = append(varargs, a)
} }
ret := m.ctrl.Call(m, "Update", varargs...) ret := m.ctrl.Call(m, "Update", varargs...)
@@ -791,9 +792,9 @@ func (m *MockInstanceDomainRepository) Update(arg0 context.Context, arg1 databas
} }
// Update indicates an expected call of Update. // Update indicates an expected call of Update.
func (mr *MockInstanceDomainRepositoryMockRecorder) Update(arg0, arg1, arg2 any, arg3 ...any) *MockInstanceDomainRepositoryUpdateCall { func (mr *MockInstanceDomainRepositoryMockRecorder) Update(ctx, client, condition any, changes ...any) *MockInstanceDomainRepositoryUpdateCall {
mr.mock.ctrl.T.Helper() mr.mock.ctrl.T.Helper()
varargs := append([]any{arg0, arg1, arg2}, arg3...) varargs := append([]any{ctx, client, condition}, changes...)
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Update", reflect.TypeOf((*MockInstanceDomainRepository)(nil).Update), varargs...) call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Update", reflect.TypeOf((*MockInstanceDomainRepository)(nil).Update), varargs...)
return &MockInstanceDomainRepositoryUpdateCall{Call: call} return &MockInstanceDomainRepositoryUpdateCall{Call: call}
} }
File diff suppressed because it is too large Load Diff
+17 -16
View File
@@ -20,6 +20,7 @@ import (
type MockPermissionChecker struct { type MockPermissionChecker struct {
ctrl *gomock.Controller ctrl *gomock.Controller
recorder *MockPermissionCheckerMockRecorder recorder *MockPermissionCheckerMockRecorder
isgomock struct{}
} }
// MockPermissionCheckerMockRecorder is the mock recorder for MockPermissionChecker. // MockPermissionCheckerMockRecorder is the mock recorder for MockPermissionChecker.
@@ -40,17 +41,17 @@ func (m *MockPermissionChecker) EXPECT() *MockPermissionCheckerMockRecorder {
} }
// CheckInstancePermission mocks base method. // CheckInstancePermission mocks base method.
func (m *MockPermissionChecker) CheckInstancePermission(arg0 context.Context, arg1 string) error { func (m *MockPermissionChecker) CheckInstancePermission(ctx context.Context, permission string) error {
m.ctrl.T.Helper() m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "CheckInstancePermission", arg0, arg1) ret := m.ctrl.Call(m, "CheckInstancePermission", ctx, permission)
ret0, _ := ret[0].(error) ret0, _ := ret[0].(error)
return ret0 return ret0
} }
// CheckInstancePermission indicates an expected call of CheckInstancePermission. // CheckInstancePermission indicates an expected call of CheckInstancePermission.
func (mr *MockPermissionCheckerMockRecorder) CheckInstancePermission(arg0, arg1 any) *MockPermissionCheckerCheckInstancePermissionCall { func (mr *MockPermissionCheckerMockRecorder) CheckInstancePermission(ctx, permission any) *MockPermissionCheckerCheckInstancePermissionCall {
mr.mock.ctrl.T.Helper() mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CheckInstancePermission", reflect.TypeOf((*MockPermissionChecker)(nil).CheckInstancePermission), arg0, arg1) call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CheckInstancePermission", reflect.TypeOf((*MockPermissionChecker)(nil).CheckInstancePermission), ctx, permission)
return &MockPermissionCheckerCheckInstancePermissionCall{Call: call} return &MockPermissionCheckerCheckInstancePermissionCall{Call: call}
} }
@@ -78,17 +79,17 @@ func (c *MockPermissionCheckerCheckInstancePermissionCall) DoAndReturn(f func(co
} }
// CheckOrganizationPermission mocks base method. // CheckOrganizationPermission mocks base method.
func (m *MockPermissionChecker) CheckOrganizationPermission(arg0 context.Context, arg1, arg2 string) error { func (m *MockPermissionChecker) CheckOrganizationPermission(ctx context.Context, permission, orgID string) error {
m.ctrl.T.Helper() m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "CheckOrganizationPermission", arg0, arg1, arg2) ret := m.ctrl.Call(m, "CheckOrganizationPermission", ctx, permission, orgID)
ret0, _ := ret[0].(error) ret0, _ := ret[0].(error)
return ret0 return ret0
} }
// CheckOrganizationPermission indicates an expected call of CheckOrganizationPermission. // CheckOrganizationPermission indicates an expected call of CheckOrganizationPermission.
func (mr *MockPermissionCheckerMockRecorder) CheckOrganizationPermission(arg0, arg1, arg2 any) *MockPermissionCheckerCheckOrganizationPermissionCall { func (mr *MockPermissionCheckerMockRecorder) CheckOrganizationPermission(ctx, permission, orgID any) *MockPermissionCheckerCheckOrganizationPermissionCall {
mr.mock.ctrl.T.Helper() mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CheckOrganizationPermission", reflect.TypeOf((*MockPermissionChecker)(nil).CheckOrganizationPermission), arg0, arg1, arg2) call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CheckOrganizationPermission", reflect.TypeOf((*MockPermissionChecker)(nil).CheckOrganizationPermission), ctx, permission, orgID)
return &MockPermissionCheckerCheckOrganizationPermissionCall{Call: call} return &MockPermissionCheckerCheckOrganizationPermissionCall{Call: call}
} }
@@ -116,17 +117,17 @@ func (c *MockPermissionCheckerCheckOrganizationPermissionCall) DoAndReturn(f fun
} }
// CheckProjectGrantPermission mocks base method. // CheckProjectGrantPermission mocks base method.
func (m *MockPermissionChecker) CheckProjectGrantPermission(arg0 context.Context, arg1, arg2 string) error { func (m *MockPermissionChecker) CheckProjectGrantPermission(ctx context.Context, permission, projectGrantID string) error {
m.ctrl.T.Helper() m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "CheckProjectGrantPermission", arg0, arg1, arg2) ret := m.ctrl.Call(m, "CheckProjectGrantPermission", ctx, permission, projectGrantID)
ret0, _ := ret[0].(error) ret0, _ := ret[0].(error)
return ret0 return ret0
} }
// CheckProjectGrantPermission indicates an expected call of CheckProjectGrantPermission. // CheckProjectGrantPermission indicates an expected call of CheckProjectGrantPermission.
func (mr *MockPermissionCheckerMockRecorder) CheckProjectGrantPermission(arg0, arg1, arg2 any) *MockPermissionCheckerCheckProjectGrantPermissionCall { func (mr *MockPermissionCheckerMockRecorder) CheckProjectGrantPermission(ctx, permission, projectGrantID any) *MockPermissionCheckerCheckProjectGrantPermissionCall {
mr.mock.ctrl.T.Helper() mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CheckProjectGrantPermission", reflect.TypeOf((*MockPermissionChecker)(nil).CheckProjectGrantPermission), arg0, arg1, arg2) call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CheckProjectGrantPermission", reflect.TypeOf((*MockPermissionChecker)(nil).CheckProjectGrantPermission), ctx, permission, projectGrantID)
return &MockPermissionCheckerCheckProjectGrantPermissionCall{Call: call} return &MockPermissionCheckerCheckProjectGrantPermissionCall{Call: call}
} }
@@ -154,17 +155,17 @@ func (c *MockPermissionCheckerCheckProjectGrantPermissionCall) DoAndReturn(f fun
} }
// CheckProjectPermission mocks base method. // CheckProjectPermission mocks base method.
func (m *MockPermissionChecker) CheckProjectPermission(arg0 context.Context, arg1, arg2 string) error { func (m *MockPermissionChecker) CheckProjectPermission(ctx context.Context, permission, projectID string) error {
m.ctrl.T.Helper() m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "CheckProjectPermission", arg0, arg1, arg2) ret := m.ctrl.Call(m, "CheckProjectPermission", ctx, permission, projectID)
ret0, _ := ret[0].(error) ret0, _ := ret[0].(error)
return ret0 return ret0
} }
// CheckProjectPermission indicates an expected call of CheckProjectPermission. // CheckProjectPermission indicates an expected call of CheckProjectPermission.
func (mr *MockPermissionCheckerMockRecorder) CheckProjectPermission(arg0, arg1, arg2 any) *MockPermissionCheckerCheckProjectPermissionCall { func (mr *MockPermissionCheckerMockRecorder) CheckProjectPermission(ctx, permission, projectID any) *MockPermissionCheckerCheckProjectPermissionCall {
mr.mock.ctrl.T.Helper() mr.mock.ctrl.T.Helper()
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CheckProjectPermission", reflect.TypeOf((*MockPermissionChecker)(nil).CheckProjectPermission), arg0, arg1, arg2) call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CheckProjectPermission", reflect.TypeOf((*MockPermissionChecker)(nil).CheckProjectPermission), ctx, permission, projectID)
return &MockPermissionCheckerCheckProjectPermissionCall{Call: call} return &MockPermissionCheckerCheckProjectPermissionCall{Call: call}
} }
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+82
View File
@@ -0,0 +1,82 @@
// Code generated by "enumer -type PasskeyType -transform lower -trimprefix PasskeyType"; DO NOT EDIT.
package domain
import (
"fmt"
"strings"
)
const _PasskeyTypeName = "unspecifiedpasswordlessu2f"
var _PasskeyTypeIndex = [...]uint8{0, 11, 23, 26}
const _PasskeyTypeLowerName = "unspecifiedpasswordlessu2f"
func (i PasskeyType) String() string {
if i >= PasskeyType(len(_PasskeyTypeIndex)-1) {
return fmt.Sprintf("PasskeyType(%d)", i)
}
return _PasskeyTypeName[_PasskeyTypeIndex[i]:_PasskeyTypeIndex[i+1]]
}
// An "invalid array index" compiler error signifies that the constant values have changed.
// Re-run the stringer command to generate them again.
func _PasskeyTypeNoOp() {
var x [1]struct{}
_ = x[PasskeyTypeUnspecified-(0)]
_ = x[PasskeyTypePasswordless-(1)]
_ = x[PasskeyTypeU2F-(2)]
}
var _PasskeyTypeValues = []PasskeyType{PasskeyTypeUnspecified, PasskeyTypePasswordless, PasskeyTypeU2F}
var _PasskeyTypeNameToValueMap = map[string]PasskeyType{
_PasskeyTypeName[0:11]: PasskeyTypeUnspecified,
_PasskeyTypeLowerName[0:11]: PasskeyTypeUnspecified,
_PasskeyTypeName[11:23]: PasskeyTypePasswordless,
_PasskeyTypeLowerName[11:23]: PasskeyTypePasswordless,
_PasskeyTypeName[23:26]: PasskeyTypeU2F,
_PasskeyTypeLowerName[23:26]: PasskeyTypeU2F,
}
var _PasskeyTypeNames = []string{
_PasskeyTypeName[0:11],
_PasskeyTypeName[11:23],
_PasskeyTypeName[23:26],
}
// PasskeyTypeString retrieves an enum value from the enum constants string name.
// Throws an error if the param is not part of the enum.
func PasskeyTypeString(s string) (PasskeyType, error) {
if val, ok := _PasskeyTypeNameToValueMap[s]; ok {
return val, nil
}
if val, ok := _PasskeyTypeNameToValueMap[strings.ToLower(s)]; ok {
return val, nil
}
return 0, fmt.Errorf("%s does not belong to PasskeyType values", s)
}
// PasskeyTypeValues returns all values of the enum
func PasskeyTypeValues() []PasskeyType {
return _PasskeyTypeValues
}
// PasskeyTypeStrings returns a slice of all String values of the enum
func PasskeyTypeStrings() []string {
strs := make([]string, len(_PasskeyTypeNames))
copy(strs, _PasskeyTypeNames)
return strs
}
// IsAPasskeyType returns "true" if the value is listed in the enum definition. "false" otherwise
func (i PasskeyType) IsAPasskeyType() bool {
for _, v := range _PasskeyTypeValues {
if i == v {
return true
}
}
return false
}
@@ -0,0 +1,82 @@
// Code generated by "enumer -type PersonalAccessTokenType -transform lower -trimprefix PersonalAccessTokenType"; DO NOT EDIT.
package domain
import (
"fmt"
"strings"
)
const _PersonalAccessTokenTypeName = "unspecifiedbearerjwt"
var _PersonalAccessTokenTypeIndex = [...]uint8{0, 11, 17, 20}
const _PersonalAccessTokenTypeLowerName = "unspecifiedbearerjwt"
func (i PersonalAccessTokenType) String() string {
if i >= PersonalAccessTokenType(len(_PersonalAccessTokenTypeIndex)-1) {
return fmt.Sprintf("PersonalAccessTokenType(%d)", i)
}
return _PersonalAccessTokenTypeName[_PersonalAccessTokenTypeIndex[i]:_PersonalAccessTokenTypeIndex[i+1]]
}
// An "invalid array index" compiler error signifies that the constant values have changed.
// Re-run the stringer command to generate them again.
func _PersonalAccessTokenTypeNoOp() {
var x [1]struct{}
_ = x[PersonalAccessTokenTypeUnspecified-(0)]
_ = x[PersonalAccessTokenTypeBearer-(1)]
_ = x[PersonalAccessTokenTypeJWT-(2)]
}
var _PersonalAccessTokenTypeValues = []PersonalAccessTokenType{PersonalAccessTokenTypeUnspecified, PersonalAccessTokenTypeBearer, PersonalAccessTokenTypeJWT}
var _PersonalAccessTokenTypeNameToValueMap = map[string]PersonalAccessTokenType{
_PersonalAccessTokenTypeName[0:11]: PersonalAccessTokenTypeUnspecified,
_PersonalAccessTokenTypeLowerName[0:11]: PersonalAccessTokenTypeUnspecified,
_PersonalAccessTokenTypeName[11:17]: PersonalAccessTokenTypeBearer,
_PersonalAccessTokenTypeLowerName[11:17]: PersonalAccessTokenTypeBearer,
_PersonalAccessTokenTypeName[17:20]: PersonalAccessTokenTypeJWT,
_PersonalAccessTokenTypeLowerName[17:20]: PersonalAccessTokenTypeJWT,
}
var _PersonalAccessTokenTypeNames = []string{
_PersonalAccessTokenTypeName[0:11],
_PersonalAccessTokenTypeName[11:17],
_PersonalAccessTokenTypeName[17:20],
}
// PersonalAccessTokenTypeString retrieves an enum value from the enum constants string name.
// Throws an error if the param is not part of the enum.
func PersonalAccessTokenTypeString(s string) (PersonalAccessTokenType, error) {
if val, ok := _PersonalAccessTokenTypeNameToValueMap[s]; ok {
return val, nil
}
if val, ok := _PersonalAccessTokenTypeNameToValueMap[strings.ToLower(s)]; ok {
return val, nil
}
return 0, fmt.Errorf("%s does not belong to PersonalAccessTokenType values", s)
}
// PersonalAccessTokenTypeValues returns all values of the enum
func PersonalAccessTokenTypeValues() []PersonalAccessTokenType {
return _PersonalAccessTokenTypeValues
}
// PersonalAccessTokenTypeStrings returns a slice of all String values of the enum
func PersonalAccessTokenTypeStrings() []string {
strs := make([]string, len(_PersonalAccessTokenTypeNames))
copy(strs, _PersonalAccessTokenTypeNames)
return strs
}
// IsAPersonalAccessTokenType returns "true" if the value is listed in the enum definition. "false" otherwise
func (i PersonalAccessTokenType) IsAPersonalAccessTokenType() bool {
for _, v := range _PersonalAccessTokenTypeValues {
if i == v {
return true
}
}
return false
}
+6 -6
View File
@@ -64,11 +64,11 @@ type sessionColumns interface {
UpdatedAtColumn() database.Column UpdatedAtColumn() database.Column
// FactorColumns returns the columns for the factors fields. // FactorColumns returns the columns for the factors fields.
FactorColumns() sessionFactorColumns FactorColumns() SessionFactorColumns
// MetadataColumns returns the columns for the metadata fields. // MetadataColumns returns the columns for the metadata fields.
MetadataColumns() sessionMetadataColumns MetadataColumns() SessionMetadataColumns
// UserAgentColumns returns the columns for the user agent fields. // UserAgentColumns returns the columns for the user agent fields.
UserAgentColumns() sessionUserAgentColumns UserAgentColumns() SessionUserAgentColumns
} }
// sessionConditions define all the conditions for the session table. // sessionConditions define all the conditions for the session table.
@@ -89,11 +89,11 @@ type sessionConditions interface {
UpdatedAtCondition(op database.NumberOperation, updatedAt time.Time) database.Condition UpdatedAtCondition(op database.NumberOperation, updatedAt time.Time) database.Condition
// FactorConditions returns the conditions for the factors fields. // FactorConditions returns the conditions for the factors fields.
FactorConditions() sessionFactorConditions FactorConditions() SessionFactorConditions
// MetadataConditions returns the conditions for the metadata fields. // MetadataConditions returns the conditions for the metadata fields.
MetadataConditions() sessionMetadataConditions MetadataConditions() SessionMetadataConditions
// UserAgentConditions returns the conditions for the user agent fields. // UserAgentConditions returns the conditions for the user agent fields.
UserAgentConditions() sessionUserAgentConditions UserAgentConditions() SessionUserAgentConditions
} }
type sessionChanges interface { type sessionChanges interface {
+2 -2
View File
@@ -225,7 +225,7 @@ func GetChallenge[T SessionChallenge](challenges SessionChallenges) (T, bool) {
return nilT, false return nilT, false
} }
type sessionFactorColumns interface { type SessionFactorColumns interface {
// InstanceIDColumn returns the column for the instance id field. // InstanceIDColumn returns the column for the instance id field.
InstanceIDColumn() database.Column InstanceIDColumn() database.Column
// SessionIDColumn returns the column for the session id field. // SessionIDColumn returns the column for the session id field.
@@ -240,7 +240,7 @@ type sessionFactorColumns interface {
LastVerifiedAtColumn() database.Column LastVerifiedAtColumn() database.Column
} }
type sessionFactorConditions interface { type SessionFactorConditions interface {
// PrimaryKeyCondition returns a filter on the primary key fields. // PrimaryKeyCondition returns a filter on the primary key fields.
PrimaryKeyCondition(instanceID, sessionID string, factorType SessionFactorType) database.Condition PrimaryKeyCondition(instanceID, sessionID string, factorType SessionFactorType) database.Condition
// InstanceIDCondition returns an equal filter on the instance id field. // InstanceIDCondition returns an equal filter on the instance id field.
+2 -2
View File
@@ -7,13 +7,13 @@ type SessionMetadata struct {
SessionID string `json:"sessionId,omitempty" db:"session_id"` SessionID string `json:"sessionId,omitempty" db:"session_id"`
} }
type sessionMetadataColumns interface { type SessionMetadataColumns interface {
MetadataColumns MetadataColumns
// SessionIDColumn returns the column for the session id field. // SessionIDColumn returns the column for the session id field.
SessionIDColumn() database.Column SessionIDColumn() database.Column
} }
type sessionMetadataConditions interface { type SessionMetadataConditions interface {
MetadataConditions MetadataConditions
// PrimaryKeyCondition returns a filter on the primary key fields. // PrimaryKeyCondition returns a filter on the primary key fields.
PrimaryKeyCondition(instanceID, sessionID, key string) database.Condition PrimaryKeyCondition(instanceID, sessionID, key string) database.Condition
+2 -2
View File
@@ -15,7 +15,7 @@ type SessionUserAgent struct {
Header http.Header `json:"header,omitempty" db:"headers"` Header http.Header `json:"header,omitempty" db:"headers"`
} }
type sessionUserAgentColumns interface { type SessionUserAgentColumns interface {
// InstanceIDColumn returns the column for the instance id field. // InstanceIDColumn returns the column for the instance id field.
InstanceIDColumn() database.Column InstanceIDColumn() database.Column
// FingerprintIDColumn returns the column for the fingerprint id field. // FingerprintIDColumn returns the column for the fingerprint id field.
@@ -28,7 +28,7 @@ type sessionUserAgentColumns interface {
HeadersColumn() database.Column HeadersColumn() database.Column
} }
type sessionUserAgentConditions interface { type SessionUserAgentConditions interface {
// PrimaryKeyCondition returns a filter on the primary key fields. // PrimaryKeyCondition returns a filter on the primary key fields.
PrimaryKeyCondition(instanceID, fingerprintID string) database.Condition PrimaryKeyCondition(instanceID, fingerprintID string) database.Condition
// InstanceIDCondition returns an equal filter on the instance id field. // InstanceIDCondition returns an equal filter on the instance id field.
+200 -222
View File
@@ -1,245 +1,223 @@
package domain package domain
import ( import (
"context"
"time" "time"
"github.com/zitadel/zitadel/backend/v3/storage/database" "golang.org/x/text/language"
)
// userColumns define all the columns of the user table.
type userColumns interface {
// InstanceIDColumn returns the column for the instance id field.
InstanceIDColumn() database.Column
// OrgIDColumn returns the column for the org id field.
OrgIDColumn() database.Column
// IDColumn returns the column for the id field.
IDColumn() database.Column
// UsernameColumn returns the column for the username field.
UsernameColumn() database.Column
// CreatedAtColumn returns the column for the created at field.
CreatedAtColumn() database.Column
// UpdatedAtColumn returns the column for the updated at field.
UpdatedAtColumn() database.Column
// DeletedAtColumn returns the column for the deleted at field.
DeletedAtColumn() database.Column
}
// userConditions define all the conditions for the user table.
type userConditions interface {
// PrimaryKeyCondition returns a filter on the primary key fields.
PrimaryKeyCondition(instanceID, userID string) database.Condition
// InstanceIDCondition returns an equal filter on the instance id field.
InstanceIDCondition(instanceID string) database.Condition
// OrgIDCondition returns an equal filter on the org id field.
OrgIDCondition(orgID string) database.Condition
// IDCondition returns an equal filter on the id field.
IDCondition(userID string) database.Condition
// UsernameCondition returns a filter on the username field.
UsernameCondition(op database.TextOperation, username string) database.Condition
// CreatedAtCondition returns a filter on the created at field.
CreatedAtCondition(op database.NumberOperation, createdAt time.Time) database.Condition
// UpdatedAtCondition returns a filter on the updated at field.
UpdatedAtCondition(op database.NumberOperation, updatedAt time.Time) database.Condition
// DeletedAtCondition filters for deleted users is isDeleted is set to true otherwise only not deleted users must be filtered.
DeletedCondition(isDeleted bool) database.Condition
// DeletedAtCondition filters for deleted users based on the given parameters.
DeletedAtCondition(op database.NumberOperation, deletedAt time.Time) database.Condition
}
// userChanges define all the changes for the user table.
type userChanges interface {
// SetUsername sets the username column.
SetUsername(username string) database.Change
}
// UserRepository is the interface for the user repository.
type UserRepository interface {
Repository
userColumns
userConditions
userChanges
// Get returns a user based on the given condition.
Get(ctx context.Context, client database.QueryExecutor, opts ...database.QueryOption) (*User, error)
// List returns a list of users based on the given condition.
List(ctx context.Context, client database.QueryExecutor, opts ...database.QueryOption) ([]*User, error)
// Create creates a new user.
Create(ctx context.Context, client database.QueryExecutor, user *User) error
// Delete removes users based on the given condition.
Delete(ctx context.Context, client database.QueryExecutor, condition database.Condition) error
// Human returns the [HumanRepository].
Human() HumanRepository
// Machine returns the [MachineRepository].
Machine() MachineRepository
}
// humanColumns define all the columns of the human table which inherits the user table.
type humanColumns interface {
userColumns
// FirstNameColumn returns the column for the first name field.
FirstNameColumn() database.Column
// LastNameColumn returns the column for the last name field.
LastNameColumn() database.Column
// EmailAddressColumn returns the column for the email address field.
EmailAddressColumn() database.Column
// EmailVerifiedAtColumn returns the column for the email verified at field.
EmailVerifiedAtColumn() database.Column
// PhoneNumberColumn returns the column for the phone number field.
PhoneNumberColumn() database.Column
// PhoneVerifiedAtColumn returns the column for the phone verified at field.
PhoneVerifiedAtColumn() database.Column
}
// humanConditions define all the conditions for the human table which inherits the user table.
type humanConditions interface {
userConditions
// FirstNameCondition returns a filter on the first name field.
FirstNameCondition(op database.TextOperation, firstName string) database.Condition
// LastNameCondition returns a filter on the last name field.
LastNameCondition(op database.TextOperation, lastName string) database.Condition
// EmailAddressCondition returns a filter on the email address field.
EmailAddressCondition(op database.TextOperation, email string) database.Condition
// EmailVerifiedCondition returns a filter that checks if the email is verified or not.
EmailVerifiedCondition(isVerified bool) database.Condition
// EmailVerifiedAtCondition returns a filter on the email verified at field.
EmailVerifiedAtCondition(op database.NumberOperation, emailVerifiedAt time.Time) database.Condition
// PhoneNumberCondition returns a filter on the phone number field.
PhoneNumberCondition(op database.TextOperation, phoneNumber string) database.Condition
// PhoneVerifiedCondition returns a filter that checks if the phone is verified or not.
PhoneVerifiedCondition(isVerified bool) database.Condition
// PhoneVerifiedAtCondition returns a filter on the phone verified at field.
PhoneVerifiedAtCondition(op database.NumberOperation, phoneVerifiedAt time.Time) database.Condition
}
// humanChanges define all the changes for the human table which inherits the user table.
type humanChanges interface {
userChanges
// SetFirstName sets the first name field of the human.
SetFirstName(firstName string) database.Change
// SetLastName sets the last name field of the human.
SetLastName(lastName string) database.Change
// SetEmail sets the email address and verified field of the email
// if verifiedAt is nil the email is not verified
SetEmail(address string, verifiedAt *time.Time) database.Change
// SetEmailAddress sets the email address field of the email
SetEmailAddress(email string) database.Change
// SetEmailVerifiedAt sets the verified column of the email
// if at is zero the statement uses the database timestamp
SetEmailVerifiedAt(at time.Time) database.Change
// SetPhone sets the phone number and verified field
// if verifiedAt is nil the phone is not verified
SetPhone(number string, verifiedAt *time.Time) database.Change
// SetPhoneNumber sets the phone number field
SetPhoneNumber(phoneNumber string) database.Change
// SetPhoneVerifiedAt sets the verified field of the phone
// if at is zero the statement uses the database timestamp
SetPhoneVerifiedAt(at time.Time) database.Change
}
// HumanRepository is the interface for the human repository it inherits the user repository.
type HumanRepository interface {
humanColumns
humanConditions
humanChanges
// Get returns an email based on the given condition.
GetEmail(ctx context.Context, client database.QueryExecutor, condition database.Condition) (*Email, error)
// Update updates human users based on the given condition and changes.
Update(ctx context.Context, client database.QueryExecutor, condition database.Condition, changes ...database.Change) error
}
// machineColumns define all the columns of the machine table which inherits the user table.
type machineColumns interface {
userColumns
// DescriptionColumn returns the column for the description field.
DescriptionColumn() database.Column
}
// machineConditions define all the conditions for the machine table which inherits the user table.
type machineConditions interface {
userConditions
// DescriptionCondition returns a filter on the description field.
DescriptionCondition(op database.TextOperation, description string) database.Condition
}
// machineChanges define all the changes for the machine table which inherits the user table.
type machineChanges interface {
userChanges
// SetDescription sets the description field of the machine.
SetDescription(description string) database.Change
}
// MachineRepository is the interface for the machine repository it inherits the user repository.
type MachineRepository interface {
// Update updates machine users based on the given condition and changes.
Update(ctx context.Context, client database.QueryExecutor, condition database.Condition, changes ...database.Change) error
machineColumns
machineConditions
machineChanges
}
// UserTraits is implemented by [Human] and [Machine].
type UserTraits interface {
Type() UserType
}
type UserType string
const (
UserTypeHuman UserType = "human"
UserTypeMachine UserType = "machine"
) )
type User struct { type User struct {
InstanceID string InstanceID string `json:"instanceId,omitempty" db:"instance_id"`
OrgID string OrganizationID string `json:"organizationId,omitempty" db:"organization_id"`
ID string ID string `json:"id,omitempty" db:"id"`
Username string `json:"username,omitempty" db:"username"`
State UserState `json:"state,omitempty" db:"state"`
CreatedAt time.Time `json:"createdAt,omitzero" db:"created_at"`
UpdatedAt time.Time `json:"updatedAt,omitzero" db:"updated_at"`
CreatedAt time.Time Machine *MachineUser `json:"machine,omitempty" db:"machine"`
UpdatedAt time.Time Human *HumanUser `json:"human,omitempty" db:"human"`
DeletedAt time.Time Metadata []*UserMetadata `json:"metadata,omitempty" db:"metadata"`
Username string
Traits UserTraits
} }
type Human struct { type MachineUser struct {
FirstName string `json:"firstName"` Name string `json:"name,omitempty" db:"name"`
LastName string `json:"lastName"` Description string `json:"description,omitempty" db:"description"`
Email *Email `json:"email,omitempty"` Secret string `json:"secret,omitempty" db:"secret"`
Phone *Phone `json:"phone,omitempty"` AccessTokenType PersonalAccessTokenType `json:"access_token_type,omitempty" db:"access_token_type"`
PATs []*PersonalAccessToken `json:"pats,omitempty" db:"pats"`
Keys []*MachineKey `json:"keys,omitempty" db:"keys"`
} }
// Type implements [UserTraits]. type HumanUser struct {
func (h *Human) Type() UserType { FirstName string `json:"firstName,omitempty" db:"first_name"`
return UserTypeHuman LastName string `json:"lastName,omitempty" db:"last_name"`
Nickname string `json:"nickname,omitempty" db:"nickname"`
DisplayName string `json:"displayName,omitempty" db:"display_name"`
PreferredLanguage language.Tag `json:"preferredLanguage,omitzero" db:"preferred_language"`
Gender HumanGender `json:"gender,omitempty" db:"gender"`
AvatarKey string `json:"avatarKey,omitempty" db:"avatar_key"`
MultifactorInitializationSkippedAt time.Time `json:"multifactorInitializationSkippedAt,omitzero" db:"multifactor_initialization_skipped_at"`
Email HumanEmail `json:"email,omitzero" db:"email"`
Phone *HumanPhone `json:"phone,omitempty" db:"phone"`
Passkeys []*Passkey `json:"passkeys,omitempty" db:"passkeys"`
Password HumanPassword `json:"password,omitzero" db:"password"`
TOTP HumanTOTP `json:"totp,omitzero" db:"totp"`
IdentityProviderLinks []*IdentityProviderLink `json:"identityProviderLinks,omitempty" db:"identity_provider_links"`
// Verifications are used if the Login does something on behalf of the user that requires verification
// e.g. starting passkey registration
Verifications []*Verification `db:"verifications" json:"verifications,omitempty"`
} }
var _ UserTraits = (*Human)(nil) type UserMetadata struct {
Metadata
type Email struct { UserID string `json:"userId,omitempty" db:"user_id"`
Address string `json:"address"`
VerifiedAt time.Time `json:"verifiedAt"`
} }
type Phone struct { //go:generate enumer -type UserState -transform lower -trimprefix UserState -sql
Number string `json:"number"`
VerifiedAt time.Time `json:"verifiedAt"` type UserState uint8
const (
UserStateUnspecified UserState = iota
UserStateActive
UserStateInactive
UserStateLocked
UserStateInitial
)
//go:generate enumer -type HumanGender -transform lower -trimprefix HumanGender
type HumanGender uint8
const (
HumanGenderUnspecified HumanGender = iota
HumanGenderFemale
HumanGenderMale
HumanGenderDiverse
)
type HumanPassword struct {
// Password is the hashed password
Password string `json:"-" db:"password"`
// IsChangeRequired indicates if the user must change their password
IsChangeRequired bool `json:"isChangeRequired,omitempty" db:"is_change_required"`
// VerifiedAt is the time when the current password was verified
VerifiedAt time.Time `json:"verifiedAt,omitzero" db:"verified_at"`
// Unverified is the verification data for setting a new password
// If nil, no password change is in progress
Unverified *Verification `json:"-"`
// FailedAttempts is the number of consecutive failed password attempts
// It is reset to 0 on successful verification
FailedAttempts uint8 `json:"failedAttempts,omitempty" db:"failed_attempts"`
} }
type Machine struct { type HumanEmail struct {
Description string `json:"description"` Address string `json:"address" db:"email"`
VerifiedAt time.Time `json:"verifiedAt,omitzero" db:"verified_at"`
OTP OTP `json:"-"`
// Unverified is the verification data for setting a new email
// If nil, no email change is in progress
Unverified *Verification `json:"-"`
} }
// Type implements [UserTraits]. type HumanPhone struct {
func (m *Machine) Type() UserType { Number string `json:"number" db:"phone"`
return UserTypeMachine VerifiedAt time.Time `json:"verifiedAt,omitzero" db:"verified_at"`
OTP OTP `json:"-"`
// Unverified is the verification data for setting a new phone number
// If nil, no phone change is in progress
Unverified *Verification `json:"-"`
} }
var _ UserTraits = (*Machine)(nil) type HumanTOTP struct {
VerifiedAt time.Time `json:"verifiedAt,omitzero" db:"verified_at"`
LastSuccessfullyCheckedAt time.Time `json:"lastSuccessfullyCheckedAt,omitzero" db:"last_successfully_checked_at"`
// Check is the verified secret
Check *Check `json:"-"`
// Unverified is the unverified secret
Unverified *Verification `json:"-"`
}
type OTP struct {
EnabledAt time.Time `json:"enabledAt,omitzero" db:"enabled_at"`
LastSuccessfullyCheckedAt time.Time `json:"lastSuccessfullyCheckedAt,omitzero" db:"last_successfully_checked_at"`
// Check is the currently active OTP check
// If nil, no OTP check is active
Check *Check `json:"-"`
}
type PersonalAccessToken struct {
ID string `json:"id" db:"id"`
CreatedAt time.Time `json:"createdAt,omitzero" db:"created_at"`
ExpiresAt time.Time `json:"expiresAt,omitzero" db:"expires_at"`
Type PersonalAccessTokenType `json:"type" db:"type"`
PublicKey string `json:"-" db:"public_key"`
Scopes []string `json:"scopes" db:"scopes"`
}
//go:generate enumer -type PersonalAccessTokenType -transform lower -trimprefix PersonalAccessTokenType
type PersonalAccessTokenType uint8
const (
PersonalAccessTokenTypeUnspecified PersonalAccessTokenType = iota
PersonalAccessTokenTypeBearer
PersonalAccessTokenTypeJWT
)
type MachineKey struct {
ID string `json:"id" db:"id"`
PublicKey []byte `json:"-" db:"public_key"`
CreatedAt time.Time `json:"createdAt,omitzero" db:"created_at"`
ExpiresAt time.Time `json:"expiresAt,omitzero" db:"expires_at"`
Type MachineKeyType `json:"type" db:"type"`
}
//go:generate enumer -type MachineKeyType -transform lower -trimprefix MachineKeyType
type MachineKeyType uint8
const (
MachineKeyTypeUnspecified MachineKeyType = iota
MachineKeyTypeJSON
MachineKeyTypeNone
)
type Passkey struct {
ID string `json:"id" db:"id"`
KeyID []byte `json:"-" db:"key_id"`
Name string `json:"name" db:"name"`
SignCount uint32 `json:"-" db:"sign_count"`
PublicKey []byte `json:"-" db:"public_key"`
AttestationType string `json:"attestationType" db:"attestation_type"`
AuthenticatorAttestationGUID []byte `json:"aaGuid" db:"authenticator_attestation_guid"`
Type PasskeyType `json:"type" db:"type"`
CreatedAt time.Time `json:"createdAt,omitzero" db:"created_at"`
UpdatedAt time.Time `json:"updatedAt,omitzero" db:"updated_at"`
VerifiedAt time.Time `json:"verifiedAt,omitzero" db:"verified_at"`
// Challenge is used during device registration
Challenge []byte `json:"-" db:"challenge"`
// RelyingPartyID is used during device registration
RelyingPartyID string `json:"-" db:"relying_party_id"`
// Initialization is used during user registration
Initialization *Verification `json:"-" db:"initialization"`
}
//go:generate enumer -type PasskeyType -transform lower -trimprefix PasskeyType
type PasskeyType uint8
const (
PasskeyTypeUnspecified PasskeyType = iota
PasskeyTypePasswordless
PasskeyTypeU2F
)
type IdentityProviderLink struct {
ProviderID string `json:"providerId" db:"provider_id"`
ProvidedUserID string `json:"providedUserId" db:"provided_user_id"`
ProvidedUsername string `json:"providedUsername" db:"provided_username"`
CreatedAt time.Time `json:"createdAt,omitzero" db:"created_at"`
UpdatedAt time.Time `json:"updatedAt,omitzero" db:"updated_at"`
}
//go:generate enumer -type UserType -transform lower -trimprefix UserType
type UserType uint8
const (
UserTypeUnspecified UserType = iota
UserTypeHuman
UserTypeMachine
)
+314
View File
@@ -0,0 +1,314 @@
package domain
import (
"context"
"time"
"golang.org/x/text/language"
"github.com/zitadel/zitadel/backend/v3/storage/database"
)
//go:generate mockgen -typed -package domainmock -destination ./mock/user.mock.go . UserRepository
type UserRepository interface {
Repository
Get(ctx context.Context, client database.QueryExecutor, opts ...database.QueryOption) (*User, error)
List(ctx context.Context, client database.QueryExecutor, opts ...database.QueryOption) ([]*User, error)
Create(ctx context.Context, client database.QueryExecutor, user *User) error
Update(ctx context.Context, client database.QueryExecutor, condition database.Condition, changes ...database.Change) (int64, error)
Delete(ctx context.Context, client database.QueryExecutor, condition database.Condition) (int64, error)
Human() HumanUserRepository
Machine() MachineUserRepository
LoadMetadata() UserRepository
LoadPasskeys() UserRepository
LoadIdentityProviderLinks() UserRepository
LoadVerifications() UserRepository
LoadPATs() UserRepository
LoadKeys() UserRepository
userConditions
userChanges
userColumns
}
type userConditions interface {
PrimaryKeyCondition(instanceID, userID string) database.Condition
InstanceIDCondition(instanceID string) database.Condition
OrgIDCondition(orgID string) database.Condition
IDCondition(userID string) database.Condition
UsernameCondition(op database.TextOperation, username string) database.Condition
StateCondition(state UserState) database.Condition
TypeCondition(userType UserType) database.Condition
LoginNameCondition(op database.TextOperation, loginName string) database.Condition
userMetadataConditions
}
type userMetadataConditions interface {
ExistsMetadata(condition database.Condition) database.Condition
MetadataKeyCondition(op database.TextOperation, key string) database.Condition
MetadataValueCondition(op database.BytesOperation, value []byte) database.Condition
}
type userChanges interface {
// SetUsername sets the username field
SetUsername(username string) database.Change
// SetState sets the state field
// [UserStateUnspecified] is not allowed and will result in no change
SetState(state UserState) database.Change
// SetUpdatedAt sets the updated at field
// This is used to replay events
SetUpdatedAt(updatedAt time.Time) database.Change
// AddMetadata adds metadata for the user
AddMetadata(metadata ...*Metadata) database.Change
// RemoveMetadata removes the metadata for the user
// Use one of the following conditions to specify which metadata to remove:
// - [userMetadataConditions.MetadataKeyCondition]
// - [userMetadataConditions.MetadataValueCondition]
// - nil to remove all metadata for the user
RemoveMetadata(condition database.Condition) database.Change
}
type userColumns interface {
PrimaryKeyColumns() []database.Column
UsernameColumn() database.Column
StateColumn() database.Column
TypeColumn() database.Column
CreatedAtColumn() database.Column
}
//go:generate mockgen -typed -package domainmock -destination ./mock/human_user.mock.go . HumanUserRepository
type HumanUserRepository interface {
// Update updates the human user
// It ensures that updates are only applied to human users
Update(ctx context.Context, client database.QueryExecutor, condition database.Condition, changes ...database.Change) (int64, error)
humanConditions
humanChanges
humanColumns
}
type humanConditions interface {
userConditions
FirstNameCondition(op database.TextOperation, firstName string) database.Condition
LastNameCondition(op database.TextOperation, lastName string) database.Condition
NicknameCondition(op database.TextOperation, nickname string) database.Condition
DisplayNameCondition(op database.TextOperation, displayName string) database.Condition
PreferredLanguageCondition(lang language.Tag) database.Condition
EmailCondition(op database.TextOperation, email string) database.Condition
PhoneCondition(op database.TextOperation, phone string) database.Condition
PasskeyIDCondition(passkeyID string) database.Condition
IdentityProviderIDCondition(idpID string) database.Condition
ProvidedUserIDCondition(providedUserID string) database.Condition
ProvidedUsernameCondition(username string) database.Condition
humanPasskeyConditions
}
type humanChanges interface {
userChanges
// SetFirstName sets the first name field
SetFirstName(firstName string) database.Change
// SetLastName sets the last name field
SetLastName(lastName string) database.Change
// SetNickname sets the nickname field
SetNickname(nickname string) database.Change
// SetDisplayName sets the display name field
SetDisplayName(displayName string) database.Change
// SetPreferredLanguage sets the preferred language field
// If preferredLanguage is [language.Und], it will be set to NULL in the database
SetPreferredLanguage(preferredLanguage language.Tag) database.Change
// SetGender sets the gender field
// If gender is [HumanGenderUnspecified], it will be set to NULL in the database
SetGender(gender HumanGender) database.Change
// SetAvatarKey sets the avatar key field
// If avatarKey is nil, it will be set to NULL in the database
SetAvatarKey(avatarKey *string) database.Change
// SetMultifactorInitializationSkippedAt sets the multifactor initialization skipped at field
SetMultifactorInitializationSkippedAt(skippedAt time.Time) database.Change
// SetPassword sets the password based on the verification
SetPassword(verification VerificationType) database.Change
// SetPasswordChangeRequired sets whether a password change is required
SetPasswordChangeRequired(required bool) database.Change
// CheckPassword sets the password check based on the check type
// * [CheckTypeFailed] increments failed attempts
// * [CheckTypeSucceeded] to mark the check as succeeded, removes the check and updates verified at time
CheckPassword(check PasswordCheckType) database.Change
// SetVerification sets the verification based on the verification type
SetVerification(id string, verification VerificationType) database.Change
humanEmailChanges
humanPhoneChanges
humanTOTPChanges
identityProviderLinkChanges
humanPasskeyChanges
}
type humanEmailChanges interface {
// SetEmail sets the email based on the verification
// * [VerificationTypeInit] to initialize email verification, previously verified email remains verified
// * [VerificationTypeVerified] to mark email as verified, a verification must exist
// * [VerificationTypeUpdate] to update email verification, a verification must exist (e.g. resend code)
// * [VerificationTypeSkipped] to skip email verification, existing verification is removed (e.g. admin set email)
SetEmail(verification VerificationType) database.Change
// CheckEmailOTP sets the email OTP based on the check
// * [CheckTypeInit] to initialize a new check, previous check is overwritten
// * [CheckTypeFailed] increments failed attempts
// * [CheckTypeSucceeded] to mark the check as succeeded, removes the check and updates verified at time
CheckEmailOTP(check CheckType) database.Change
// EnableEmailOTPAt enables the email OTP
// If enabledAt is zero, it will be set to NOW()
EnableEmailOTPAt(enabledAt time.Time) database.Change
// EnableEmailOTP sets the enabled at time to NOW()
EnableEmailOTP() database.Change
// DisableEmailOTP clears the enabled at time
DisableEmailOTP() database.Change
}
type humanPhoneChanges interface {
// SetPhone sets the phone based on the verification
// * [VerificationTypeInit] to initialize phone verification, previously verified phone remains verified
// * [VerificationTypeVerified] to mark phone as verified, a verification must exist
// * [VerificationTypeUpdate] to update phone verification, a verification must exist (e.g. resend code)
// * [VerificationTypeSkipped] to skip phone verification, existing verification is removed (e.g. admin set phone)
SetPhone(verification VerificationType) database.Change
// RemovePhone removes the phone number
RemovePhone() database.Change
// CheckSMSOTP sets the SMS OTP based on the check
// * [CheckTypeInit] to initialize a new check, previous check is overwritten
// * [CheckTypeFailed] increments failed attempts
// * [CheckTypeSucceeded] to mark the check as succeeded, removes the check and updates verified at time
CheckSMSOTP(check CheckType) database.Change
// EnableSMSOTPAt enables the SMS OTP
// If enabledAt is zero, it will be set to NOW()
EnableSMSOTPAt(enabledAt time.Time) database.Change
// EnableSMSOTP sets the enabled at time to NOW()
EnableSMSOTP() database.Change
// DisableSMSOTP clears the enabled at time
DisableSMSOTP() database.Change
}
type humanTOTPChanges interface {
// SetTOTP changes the TOTP secret based on the verification
// * [VerificationTypeInit] to initialize totp verification, previously verified totp remains verified
// * [VerificationTypeVerified] to mark totp as verified, a verification must exist
// * [VerificationTypeUpdate] to update totp verification, a verification must exist (e.g. resend code)
// * [VerificationTypeSkipped] to skip totp verification, existing verification is removed (e.g. admin set totp)
SetTOTP(verification VerificationType) database.Change
// SetTOTPCheck sets the TOTP check based on the check type
// * [CheckTypeFailed] increments failed attempts
// * [CheckTypeSucceeded] to mark the check as succeeded, removes the check and updates verified at time
// * [CheckTypeInit] is not allowed for TOTP
CheckTOTP(check CheckType) database.Change
// RemoveTOTP removes the TOTP
RemoveTOTP() database.Change
}
type identityProviderLinkChanges interface {
// AddIdentityProviderLink adds or updates an identity provider link
AddIdentityProviderLink(link *IdentityProviderLink) database.Change
UpdateIdentityProviderLink(changes ...database.Change) database.Change
// RemoveIdentityProviderLink removes an identity provider link based on the condition
RemoveIdentityProviderLink(providerID, providedUserID string) database.Change
// SetIdentityProviderLinkUsername sets the username for an identity provider link
SetIdentityProviderLinkUsername(providerID, providedUserID, username string) database.Change
// SetIdentityProviderLinkProvidedID sets the provided user ID for an identity provider link
SetIdentityProviderLinkProvidedID(providerID, currentProvidedUserID, newProvidedUserID string) database.Change
}
type humanColumns interface {
userColumns
FirstNameColumn() database.Column
LastNameColumn() database.Column
NicknameColumn() database.Column
DisplayNameColumn() database.Column
EmailColumn() database.Column
}
//go:generate mockgen -typed -package domainmock -destination ./mock/machine_user.mock.go . MachineUserRepository
type MachineUserRepository interface {
// Update updates the machine user
// It ensures that updates are only applied to machine users
Update(ctx context.Context, client database.QueryExecutor, condition database.Condition, changes ...database.Change) (int64, error)
machineConditions
machineChanges
machineColumns
}
type machineConditions interface {
userConditions
}
type machineChanges interface {
userChanges
// SetName sets the name field
SetName(name string) database.Change
// SetDescription sets the description field
SetDescription(description string) database.Change
// SetSecret sets the secret field
// nil will set the secret to NULL in the database
SetSecret(secret *string) database.Change
// SetAccessTokenType sets the personal access token type field
SetAccessTokenType(tokenType PersonalAccessTokenType) database.Change
// AddKey adds a key for the machine user
AddKey(key *MachineKey) database.Change
// RemoveKey removes a key for the machine user
RemoveKey(id string) database.Change
// AddPersonalAccessToken adds a personal access token for the machine user
AddPersonalAccessToken(pat *PersonalAccessToken) database.Change
// RemovePersonalAccessToken removes a personal access token for the machine user
RemovePersonalAccessToken(id string) database.Change
}
type machineColumns interface {
userColumns
}
type humanPasskeyConditions interface {
PasskeyIDCondition(passkeyID string) database.Condition
PasskeyKeyIDCondition(keyID string) database.Condition
PasskeyChallengeCondition(challenge string) database.Condition
}
type humanPasskeyChanges interface {
// AddPasskey adds a passkey for the user
AddPasskey(passkey *Passkey) database.Change
// UpdatePasskey updates a passkey for the user.
// The condition must specify which passkey to update, use [humanPasskeyConditions].
// Use [humanPasskeyFieldChanges] to specify the fields to update.
UpdatePasskey(condition database.Condition, changes ...database.Change) database.Change
// RemovePasskey removes a passkey for the user
// The condition must specify which passkey to update, use [humanPasskeyConditions].
RemovePasskey(condition database.Condition) database.Change
passkeyFieldChanges
}
type passkeyFieldChanges interface {
// SetPasskeyKeyID sets the key ID field
SetPasskeyKeyID(keyID []byte) database.Change
// SetPasskeyPublicKey sets the public key field
SetPasskeyPublicKey(publicKey []byte) database.Change
// SetPasskeyAttestationType sets the attestation type field
SetPasskeyAttestationType(attestationType string) database.Change
// SetPasskeyAuthenticatorAttestationGUID sets the AAGUID field
SetPasskeyAuthenticatorAttestationGUID(aaguid []byte) database.Change
// SetPasskeyName sets the name field
SetPasskeyName(name string) database.Change
// SetPasskeySignCount sets the sign count field
SetPasskeySignCount(signCount uint32) database.Change
// SetPasskeyUpdatedAt sets the updated at field
SetPasskeyUpdatedAt(updatedAt time.Time) database.Change
// SetPasskeyVerifiedAt sets the verified at field
// If verifiedAt is zero, it will be set to NOW()
SetPasskeyVerifiedAt(verifiedAt time.Time) database.Change
}
+121
View File
@@ -0,0 +1,121 @@
// Code generated by "enumer -type UserState -transform lower -trimprefix UserState -sql"; DO NOT EDIT.
package domain
import (
"database/sql/driver"
"fmt"
"strings"
)
const _UserStateName = "unspecifiedactiveinactivelockedinitial"
var _UserStateIndex = [...]uint8{0, 11, 17, 25, 31, 38}
const _UserStateLowerName = "unspecifiedactiveinactivelockedinitial"
func (i UserState) String() string {
if i >= UserState(len(_UserStateIndex)-1) {
return fmt.Sprintf("UserState(%d)", i)
}
return _UserStateName[_UserStateIndex[i]:_UserStateIndex[i+1]]
}
// An "invalid array index" compiler error signifies that the constant values have changed.
// Re-run the stringer command to generate them again.
func _UserStateNoOp() {
var x [1]struct{}
_ = x[UserStateUnspecified-(0)]
_ = x[UserStateActive-(1)]
_ = x[UserStateInactive-(2)]
_ = x[UserStateLocked-(3)]
_ = x[UserStateInitial-(4)]
}
var _UserStateValues = []UserState{UserStateUnspecified, UserStateActive, UserStateInactive, UserStateLocked, UserStateInitial}
var _UserStateNameToValueMap = map[string]UserState{
_UserStateName[0:11]: UserStateUnspecified,
_UserStateLowerName[0:11]: UserStateUnspecified,
_UserStateName[11:17]: UserStateActive,
_UserStateLowerName[11:17]: UserStateActive,
_UserStateName[17:25]: UserStateInactive,
_UserStateLowerName[17:25]: UserStateInactive,
_UserStateName[25:31]: UserStateLocked,
_UserStateLowerName[25:31]: UserStateLocked,
_UserStateName[31:38]: UserStateInitial,
_UserStateLowerName[31:38]: UserStateInitial,
}
var _UserStateNames = []string{
_UserStateName[0:11],
_UserStateName[11:17],
_UserStateName[17:25],
_UserStateName[25:31],
_UserStateName[31:38],
}
// UserStateString retrieves an enum value from the enum constants string name.
// Throws an error if the param is not part of the enum.
func UserStateString(s string) (UserState, error) {
if val, ok := _UserStateNameToValueMap[s]; ok {
return val, nil
}
if val, ok := _UserStateNameToValueMap[strings.ToLower(s)]; ok {
return val, nil
}
return 0, fmt.Errorf("%s does not belong to UserState values", s)
}
// UserStateValues returns all values of the enum
func UserStateValues() []UserState {
return _UserStateValues
}
// UserStateStrings returns a slice of all String values of the enum
func UserStateStrings() []string {
strs := make([]string, len(_UserStateNames))
copy(strs, _UserStateNames)
return strs
}
// IsAUserState returns "true" if the value is listed in the enum definition. "false" otherwise
func (i UserState) IsAUserState() bool {
for _, v := range _UserStateValues {
if i == v {
return true
}
}
return false
}
func (i UserState) Value() (driver.Value, error) {
return i.String(), nil
}
func (i *UserState) Scan(value interface{}) error {
if value == nil {
return nil
}
var str string
switch v := value.(type) {
case []byte:
str = string(v)
case string:
str = v
case fmt.Stringer:
str = v.String()
default:
return fmt.Errorf("invalid value of UserState: %[1]T(%[1]v)", value)
}
val, err := UserStateString(str)
if err != nil {
return err
}
*i = val
return nil
}
+82
View File
@@ -0,0 +1,82 @@
// Code generated by "enumer -type UserType -transform lower -trimprefix UserType"; DO NOT EDIT.
package domain
import (
"fmt"
"strings"
)
const _UserTypeName = "unspecifiedhumanmachine"
var _UserTypeIndex = [...]uint8{0, 11, 16, 23}
const _UserTypeLowerName = "unspecifiedhumanmachine"
func (i UserType) String() string {
if i >= UserType(len(_UserTypeIndex)-1) {
return fmt.Sprintf("UserType(%d)", i)
}
return _UserTypeName[_UserTypeIndex[i]:_UserTypeIndex[i+1]]
}
// An "invalid array index" compiler error signifies that the constant values have changed.
// Re-run the stringer command to generate them again.
func _UserTypeNoOp() {
var x [1]struct{}
_ = x[UserTypeUnspecified-(0)]
_ = x[UserTypeHuman-(1)]
_ = x[UserTypeMachine-(2)]
}
var _UserTypeValues = []UserType{UserTypeUnspecified, UserTypeHuman, UserTypeMachine}
var _UserTypeNameToValueMap = map[string]UserType{
_UserTypeName[0:11]: UserTypeUnspecified,
_UserTypeLowerName[0:11]: UserTypeUnspecified,
_UserTypeName[11:16]: UserTypeHuman,
_UserTypeLowerName[11:16]: UserTypeHuman,
_UserTypeName[16:23]: UserTypeMachine,
_UserTypeLowerName[16:23]: UserTypeMachine,
}
var _UserTypeNames = []string{
_UserTypeName[0:11],
_UserTypeName[11:16],
_UserTypeName[16:23],
}
// UserTypeString retrieves an enum value from the enum constants string name.
// Throws an error if the param is not part of the enum.
func UserTypeString(s string) (UserType, error) {
if val, ok := _UserTypeNameToValueMap[s]; ok {
return val, nil
}
if val, ok := _UserTypeNameToValueMap[strings.ToLower(s)]; ok {
return val, nil
}
return 0, fmt.Errorf("%s does not belong to UserType values", s)
}
// UserTypeValues returns all values of the enum
func UserTypeValues() []UserType {
return _UserTypeValues
}
// UserTypeStrings returns a slice of all String values of the enum
func UserTypeStrings() []string {
strs := make([]string, len(_UserTypeNames))
copy(strs, _UserTypeNames)
return strs
}
// IsAUserType returns "true" if the value is listed in the enum definition. "false" otherwise
func (i UserType) IsAUserType() bool {
for _, v := range _UserTypeValues {
if i == v {
return true
}
}
return false
}
+79
View File
@@ -0,0 +1,79 @@
package domain
import "time"
type Verification struct {
Value *string `db:"value"`
Code []byte `db:"code"`
ExpiresAt *time.Time `db:"expires_at"`
FailedAttempts uint8 `db:"failed_attempts"`
VerifiedAt time.Time `db:"verified_at"`
}
type VerificationType interface {
isVerificationType()
}
// VerificationTypeInit indicates that an object which needs verification is created.
type VerificationTypeInit struct {
// CreatedAt is the time when the verification was created.
// If zero, the current time will be used.
CreatedAt time.Time
// Expiry is the duration after which the verification expires.
Expiry *time.Duration
// Code is the code to be used for verification.
Code []byte
// Value is the value to be set after successful verification.
Value *string
}
// isVerificationType implements [VerificationType].
func (v *VerificationTypeInit) isVerificationType() {}
var _ VerificationType = (*VerificationTypeInit)(nil)
// VerificationTypeVerified indicates that the verification was successful.
// If VerifiedAt is zero, the current time will be used.
// If the Value of the verification is present, it is used as the new value to be set.
type VerificationTypeVerified struct {
VerifiedAt time.Time
}
// isVerificationType implements [VerificationType].
func (v *VerificationTypeVerified) isVerificationType() {}
var _ VerificationType = (*VerificationTypeVerified)(nil)
// VerificationTypeUpdate updates an existing verification.
// Non-nil fields get updated.
type VerificationTypeUpdate struct {
Code []byte
Value *string
Expiry *time.Duration
}
// isVerificationType implements [VerificationType].
func (v *VerificationTypeUpdate) isVerificationType() {}
var _ VerificationType = (*VerificationTypeUpdate)(nil)
// VerificationTypeSkipped indicates that the verification was skipped.
// If Value is present, it is used as the new value to be set.
type VerificationTypeSkipped struct {
VerifiedAt time.Time
Value *string
}
// isVerificationType implements [VerificationType].
func (v *VerificationTypeSkipped) isVerificationType() {}
var _ VerificationType = (*VerificationTypeSkipped)(nil)
type VerificationTypeFailed struct {
FailedAt time.Time
}
// isVerificationType implements [VerificationType].
func (v *VerificationTypeFailed) isVerificationType() {}
var _ VerificationType = (*VerificationTypeFailed)(nil)
@@ -94,11 +94,11 @@ func (i NumberOperation) IsANumberOperation() bool {
return false return false
} }
const _TextOperationName = "=<>LIKELIKELIKELIKELIKELIKE" const _TextOperationName = "=<>LIKELIKELIKELIKELIKELIKE=<>"
var _TextOperationIndex = [...]uint8{0, 1, 3, 7, 11, 15, 19, 23, 27} var _TextOperationIndex = [...]uint8{0, 1, 3, 7, 11, 15, 19, 23, 27, 28, 30}
const _TextOperationLowerName = "=<>likelikelikelikelikelike" const _TextOperationLowerName = "=<>likelikelikelikelikelike=<>"
func (i TextOperation) String() string { func (i TextOperation) String() string {
i -= 1 i -= 1
@@ -120,9 +120,11 @@ func _TextOperationNoOp() {
_ = x[TextOperationContainsIgnoreCase-(6)] _ = x[TextOperationContainsIgnoreCase-(6)]
_ = x[TextOperationEndsWithIgnoreCase-(7)] _ = x[TextOperationEndsWithIgnoreCase-(7)]
_ = x[TextOperationStartsWithIgnoreCase-(8)] _ = x[TextOperationStartsWithIgnoreCase-(8)]
_ = x[TextOperationEqualIgnoreCase-(9)]
_ = x[TextOperationNotEqualIgnoreCase-(10)]
} }
var _TextOperationValues = []TextOperation{TextOperationEqual, TextOperationNotEqual, TextOperationStartsWith, TextOperationContains, TextOperationEndsWith, TextOperationContainsIgnoreCase, TextOperationEndsWithIgnoreCase, TextOperationStartsWithIgnoreCase} var _TextOperationValues = []TextOperation{TextOperationEqual, TextOperationNotEqual, TextOperationStartsWith, TextOperationContains, TextOperationEndsWith, TextOperationContainsIgnoreCase, TextOperationEndsWithIgnoreCase, TextOperationStartsWithIgnoreCase, TextOperationEqualIgnoreCase, TextOperationNotEqualIgnoreCase}
var _TextOperationNameToValueMap = map[string]TextOperation{ var _TextOperationNameToValueMap = map[string]TextOperation{
_TextOperationName[0:1]: TextOperationEqual, _TextOperationName[0:1]: TextOperationEqual,
@@ -141,6 +143,10 @@ var _TextOperationNameToValueMap = map[string]TextOperation{
_TextOperationLowerName[19:23]: TextOperationEndsWithIgnoreCase, _TextOperationLowerName[19:23]: TextOperationEndsWithIgnoreCase,
_TextOperationName[23:27]: TextOperationStartsWithIgnoreCase, _TextOperationName[23:27]: TextOperationStartsWithIgnoreCase,
_TextOperationLowerName[23:27]: TextOperationStartsWithIgnoreCase, _TextOperationLowerName[23:27]: TextOperationStartsWithIgnoreCase,
_TextOperationName[27:28]: TextOperationEqualIgnoreCase,
_TextOperationLowerName[27:28]: TextOperationEqualIgnoreCase,
_TextOperationName[28:30]: TextOperationNotEqualIgnoreCase,
_TextOperationLowerName[28:30]: TextOperationNotEqualIgnoreCase,
} }
var _TextOperationNames = []string{ var _TextOperationNames = []string{
@@ -152,6 +158,8 @@ var _TextOperationNames = []string{
_TextOperationName[15:19], _TextOperationName[15:19],
_TextOperationName[19:23], _TextOperationName[19:23],
_TextOperationName[23:27], _TextOperationName[23:27],
_TextOperationName[27:28],
_TextOperationName[28:30],
} }
// TextOperationString retrieves an enum value from the enum constants string name. // TextOperationString retrieves an enum value from the enum constants string name.
@@ -1,291 +0,0 @@
package repository
import (
"context"
"time"
"github.com/zitadel/zitadel/backend/v3/domain"
"github.com/zitadel/zitadel/backend/v3/storage/database"
)
const queryUserStmt = `SELECT instance_id, org_id, id, username, type, created_at, updated_at, deleted_at,` +
` first_name, last_name, email_address, email_verified_at, phone_number, phone_verified_at, description` +
` FROM users_view users`
type user struct{}
func UserRepository() domain.UserRepository {
return new(user)
}
var _ domain.UserRepository = (*user)(nil)
// -------------------------------------------------------------
// repository
// -------------------------------------------------------------
// Human implements [domain.UserRepository].
func (u user) Human() domain.HumanRepository {
return &userHuman{user: u}
}
// Machine implements [domain.UserRepository].
func (u user) Machine() domain.MachineRepository {
return &userMachine{user: u}
}
// List implements [domain.UserRepository].
func (u user) List(ctx context.Context, client database.QueryExecutor, opts ...database.QueryOption) (users []*domain.User, err error) {
options := new(database.QueryOpts)
for _, opt := range opts {
opt(options)
}
builder := database.StatementBuilder{}
builder.WriteString(queryUserStmt)
options.WriteCondition(&builder)
options.WriteOrderBy(&builder)
options.WriteLimit(&builder)
options.WriteOffset(&builder)
rows, err := client.Query(ctx, builder.String(), builder.Args()...)
if err != nil {
return nil, err
}
defer func() {
closeErr := rows.Close()
if err != nil {
return
}
err = closeErr
}()
for rows.Next() {
user, err := scanUser(rows)
if err != nil {
return nil, err
}
users = append(users, user)
}
if err := rows.Err(); err != nil {
return nil, err
}
return users, nil
}
// Get implements [domain.UserRepository].
func (u user) Get(ctx context.Context, client database.QueryExecutor, opts ...database.QueryOption) (*domain.User, error) {
options := new(database.QueryOpts)
for _, opt := range opts {
opt(options)
}
builder := database.StatementBuilder{}
builder.WriteString(queryUserStmt)
options.WriteCondition(&builder)
options.WriteOrderBy(&builder)
options.WriteLimit(&builder)
options.WriteOffset(&builder)
return scanUser(client.QueryRow(ctx, builder.String(), builder.Args()...))
}
const (
createHumanStmt = `INSERT INTO human_users (instance_id, org_id, user_id, username, first_name, last_name, email_address, email_verified_at, phone_number, phone_verified_at)` +
` VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)` +
` RETURNING created_at, updated_at`
createMachineStmt = `INSERT INTO user_machines (instance_id, org_id, user_id, username, description)` +
` VALUES ($1, $2, $3, $4, $5)` +
` RETURNING created_at, updated_at`
)
// Create implements [domain.UserRepository].
func (u user) Create(ctx context.Context, client database.QueryExecutor, user *domain.User) error {
builder := database.StatementBuilder{}
builder.AppendArgs(user.InstanceID, user.OrgID, user.ID, user.Username, user.Traits.Type())
switch trait := user.Traits.(type) {
case *domain.Human:
builder.WriteString(createHumanStmt)
builder.AppendArgs(trait.FirstName, trait.LastName, trait.Email.Address, trait.Email.VerifiedAt, trait.Phone.Number, trait.Phone.VerifiedAt)
case *domain.Machine:
builder.WriteString(createMachineStmt)
builder.AppendArgs(trait.Description)
}
return client.QueryRow(ctx, builder.String(), builder.Args()...).Scan(&user.CreatedAt, &user.UpdatedAt)
}
// Delete implements [domain.UserRepository].
func (u user) Delete(ctx context.Context, client database.QueryExecutor, condition database.Condition) error {
builder := database.StatementBuilder{}
builder.WriteString("DELETE FROM users")
writeCondition(&builder, condition)
_, err := client.Exec(ctx, builder.String(), builder.Args()...)
return err
}
// -------------------------------------------------------------
// changes
// -------------------------------------------------------------
// SetUsername implements [domain.userChanges].
func (u user) SetUsername(username string) database.Change {
return database.NewChange(u.UsernameColumn(), username)
}
// -------------------------------------------------------------
// conditions
// -------------------------------------------------------------
func (u user) PrimaryKeyCondition(instanceID, userID string) database.Condition {
return database.And(
u.InstanceIDCondition(instanceID),
u.IDCondition(userID),
)
}
// InstanceIDCondition implements [domain.userConditions].
func (u user) InstanceIDCondition(instanceID string) database.Condition {
return database.NewTextCondition(u.InstanceIDColumn(), database.TextOperationEqual, instanceID)
}
// OrgIDCondition implements [domain.userConditions].
func (u user) OrgIDCondition(orgID string) database.Condition {
return database.NewTextCondition(u.OrgIDColumn(), database.TextOperationEqual, orgID)
}
// IDCondition implements [domain.userConditions].
func (u user) IDCondition(userID string) database.Condition {
return database.NewTextCondition(u.IDColumn(), database.TextOperationEqual, userID)
}
// UsernameCondition implements [domain.userConditions].
func (u user) UsernameCondition(op database.TextOperation, username string) database.Condition {
return database.NewTextCondition(u.UsernameColumn(), op, username)
}
// CreatedAtCondition implements [domain.userConditions].
func (u user) CreatedAtCondition(op database.NumberOperation, createdAt time.Time) database.Condition {
return database.NewNumberCondition(u.CreatedAtColumn(), op, createdAt)
}
// UpdatedAtCondition implements [domain.userConditions].
func (u user) UpdatedAtCondition(op database.NumberOperation, updatedAt time.Time) database.Condition {
return database.NewNumberCondition(u.UpdatedAtColumn(), op, updatedAt)
}
// DeletedCondition implements [domain.userConditions].
func (u user) DeletedCondition(isDeleted bool) database.Condition {
if isDeleted {
return database.IsNotNull(u.DeletedAtColumn())
}
return database.IsNull(u.DeletedAtColumn())
}
// DeletedAtCondition implements [domain.userConditions].
func (u user) DeletedAtCondition(op database.NumberOperation, deletedAt time.Time) database.Condition {
return database.NewNumberCondition(u.DeletedAtColumn(), op, deletedAt)
}
// -------------------------------------------------------------
// columns
// -------------------------------------------------------------
// PrimaryKeyColumns implements [domain.Repository].
func (u user) PrimaryKeyColumns() []database.Column {
return []database.Column{
u.InstanceIDColumn(),
u.IDColumn(),
}
}
// InstanceIDColumn implements [domain.userColumns].
func (user) InstanceIDColumn() database.Column {
return database.NewColumn("users", "instance_id")
}
// OrgIDColumn implements [domain.userColumns].
func (user) OrgIDColumn() database.Column {
return database.NewColumn("users", "org_id")
}
// IDColumn implements [domain.userColumns].
func (user) IDColumn() database.Column {
return database.NewColumn("users", "id")
}
// UsernameColumn implements [domain.userColumns].
func (user) UsernameColumn() database.Column {
return database.NewColumn("users", "username")
}
// FirstNameColumn implements [domain.userColumns].
func (user) CreatedAtColumn() database.Column {
return database.NewColumn("users", "created_at")
}
// UpdatedAtColumn implements [domain.userColumns].
func (user) UpdatedAtColumn() database.Column {
return database.NewColumn("users", "updated_at")
}
// DeletedAtColumn implements [domain.userColumns].
func (user) DeletedAtColumn() database.Column {
return database.NewColumn("users", "deleted_at")
}
func (u user) columns() database.Columns {
return database.Columns{
u.InstanceIDColumn(),
u.OrgIDColumn(),
u.IDColumn(),
u.UsernameColumn(),
u.CreatedAtColumn(),
u.UpdatedAtColumn(),
u.DeletedAtColumn(),
}
}
func scanUser(scanner database.Scanner) (*domain.User, error) {
var (
user domain.User
human domain.Human
email domain.Email
phone domain.Phone
machine domain.Machine
typ domain.UserType
)
err := scanner.Scan(
&user.InstanceID,
&user.OrgID,
&user.ID,
&user.Username,
&typ,
&user.CreatedAt,
&user.UpdatedAt,
&user.DeletedAt,
&human.FirstName,
&human.LastName,
&email.Address,
&email.VerifiedAt,
&phone.Number,
&phone.VerifiedAt,
&machine.Description,
)
if err != nil {
return nil, err
}
switch typ {
case domain.UserTypeHuman:
if email.Address != "" {
human.Email = &email
}
if phone.Number != "" {
human.Phone = &phone
}
user.Traits = &human
case domain.UserTypeMachine:
user.Traits = &machine
}
return &user, nil
}
@@ -1,208 +0,0 @@
package repository
import (
"context"
"time"
"github.com/zitadel/zitadel/backend/v3/domain"
"github.com/zitadel/zitadel/backend/v3/storage/database"
)
// -------------------------------------------------------------
// repository
// -------------------------------------------------------------
type userHuman struct {
user
}
var _ domain.HumanRepository = (*userHuman)(nil)
const userEmailQuery = `SELECT h.email_address, h.email_verified_at FROM user_humans h`
// GetEmail implements [domain.HumanRepository].
func (u *userHuman) GetEmail(ctx context.Context, client database.QueryExecutor, condition database.Condition) (*domain.Email, error) {
var email domain.Email
builder := database.StatementBuilder{}
builder.WriteString(userEmailQuery)
writeCondition(&builder, condition)
err := client.QueryRow(ctx, builder.String(), builder.Args()...).Scan(
&email.Address,
&email.VerifiedAt,
)
if err != nil {
return nil, err
}
return &email, nil
}
// Update implements [domain.HumanRepository].
func (h userHuman) Update(ctx context.Context, client database.QueryExecutor, condition database.Condition, changes ...database.Change) error {
builder := database.StatementBuilder{}
builder.WriteString(`UPDATE human_users SET `)
database.Changes(changes).Write(&builder)
writeCondition(&builder, condition)
stmt := builder.String()
_, err := client.Exec(ctx, stmt, builder.Args()...)
return err
}
// -------------------------------------------------------------
// changes
// -------------------------------------------------------------
// SetFirstName implements [domain.humanChanges].
func (h userHuman) SetFirstName(firstName string) database.Change {
return database.NewChange(h.FirstNameColumn(), firstName)
}
// SetLastName implements [domain.humanChanges].
func (h userHuman) SetLastName(lastName string) database.Change {
return database.NewChange(h.LastNameColumn(), lastName)
}
// SetEmail implements [domain.humanChanges].
func (h userHuman) SetEmail(address string, verified *time.Time) database.Change {
return database.NewChanges(
h.SetEmailAddress(address),
database.NewChangePtr(h.EmailVerifiedAtColumn(), verified),
)
}
// SetEmailAddress implements [domain.humanChanges].
func (h userHuman) SetEmailAddress(address string) database.Change {
return database.NewChange(h.EmailAddressColumn(), address)
}
// SetEmailVerifiedAt implements [domain.humanChanges].
func (h userHuman) SetEmailVerifiedAt(at time.Time) database.Change {
if at.IsZero() {
return database.NewChange(h.EmailVerifiedAtColumn(), database.NowInstruction)
}
return database.NewChange(h.EmailVerifiedAtColumn(), at)
}
// SetPhone implements [domain.humanChanges].
func (h userHuman) SetPhone(number string, verifiedAt *time.Time) database.Change {
return database.NewChanges(
h.SetPhoneNumber(number),
database.NewChangePtr(h.PhoneVerifiedAtColumn(), verifiedAt),
)
}
// SetPhoneNumber implements [domain.humanChanges].
func (h userHuman) SetPhoneNumber(number string) database.Change {
return database.NewChange(h.PhoneNumberColumn(), number)
}
// SetPhoneVerifiedAt implements [domain.humanChanges].
func (h userHuman) SetPhoneVerifiedAt(at time.Time) database.Change {
if at.IsZero() {
return database.NewChange(h.PhoneVerifiedAtColumn(), database.NowInstruction)
}
return database.NewChange(h.PhoneVerifiedAtColumn(), at)
}
// -------------------------------------------------------------
// conditions
// -------------------------------------------------------------
// FirstNameCondition implements [domain.humanConditions].
func (h userHuman) FirstNameCondition(op database.TextOperation, firstName string) database.Condition {
return database.NewTextCondition(h.FirstNameColumn(), op, firstName)
}
// LastNameCondition implements [domain.humanConditions].
func (h userHuman) LastNameCondition(op database.TextOperation, lastName string) database.Condition {
return database.NewTextCondition(h.LastNameColumn(), op, lastName)
}
// EmailAddressCondition implements [domain.humanConditions].
func (h userHuman) EmailAddressCondition(op database.TextOperation, email string) database.Condition {
return database.NewTextCondition(h.EmailAddressColumn(), op, email)
}
// EmailVerifiedCondition implements [domain.humanConditions].
func (h *userHuman) EmailVerifiedCondition(isVerified bool) database.Condition {
if isVerified {
return database.IsNotNull(h.EmailVerifiedAtColumn())
}
return database.IsNull(h.EmailVerifiedAtColumn())
}
// EmailVerifiedAtCondition implements [domain.humanConditions].
func (h userHuman) EmailVerifiedAtCondition(op database.NumberOperation, verifiedAt time.Time) database.Condition {
return database.NewNumberCondition(h.EmailVerifiedAtColumn(), op, verifiedAt)
}
// PhoneNumberCondition implements [domain.humanConditions].
func (h userHuman) PhoneNumberCondition(op database.TextOperation, phoneNumber string) database.Condition {
return database.NewTextCondition(h.PhoneNumberColumn(), op, phoneNumber)
}
// PhoneVerifiedCondition implements [domain.humanConditions].
func (h userHuman) PhoneVerifiedCondition(isVerified bool) database.Condition {
if isVerified {
return database.IsNotNull(h.PhoneVerifiedAtColumn())
}
return database.IsNull(h.PhoneVerifiedAtColumn())
}
// PhoneVerifiedAtCondition implements [domain.humanConditions].
func (h userHuman) PhoneVerifiedAtCondition(op database.NumberOperation, verifiedAt time.Time) database.Condition {
return database.NewNumberCondition(h.PhoneVerifiedAtColumn(), op, verifiedAt)
}
// -------------------------------------------------------------
// columns
// -------------------------------------------------------------
// FirstNameColumn implements [domain.humanColumns].
func (h userHuman) FirstNameColumn() database.Column {
return database.NewColumn("user_humans", "first_name")
}
// LastNameColumn implements [domain.humanColumns].
func (h userHuman) LastNameColumn() database.Column {
return database.NewColumn("user_humans", "last_name")
}
// EmailAddressColumn implements [domain.humanColumns].
func (h userHuman) EmailAddressColumn() database.Column {
return database.NewColumn("user_humans", "email_address")
}
// EmailVerifiedAtColumn implements [domain.humanColumns].
func (h userHuman) EmailVerifiedAtColumn() database.Column {
return database.NewColumn("user_humans", "email_verified_at")
}
// PhoneNumberColumn implements [domain.humanColumns].
func (h userHuman) PhoneNumberColumn() database.Column {
return database.NewColumn("user_humans", "phone_number")
}
// PhoneVerifiedAtColumn implements [domain.humanColumns].
func (h userHuman) PhoneVerifiedAtColumn() database.Column {
return database.NewColumn("user_humans", "phone_verified_at")
}
// func (h userHuman) columns() database.Columns {
// return append(h.user.columns(),
// h.FirstNameColumn(),
// h.LastNameColumn(),
// h.EmailAddressColumn(),
// h.EmailVerifiedAtColumn(),
// h.PhoneNumberColumn(),
// h.PhoneVerifiedAtColumn(),
// )
// }
// func (h userHuman) writeReturning(builder *database.StatementBuilder) {
// builder.WriteString(" RETURNING ")
// h.columns().Write(builder)
// }
@@ -1,67 +0,0 @@
package repository
import (
"context"
"github.com/zitadel/zitadel/backend/v3/domain"
"github.com/zitadel/zitadel/backend/v3/storage/database"
)
type userMachine struct {
user
}
var _ domain.MachineRepository = (*userMachine)(nil)
// -------------------------------------------------------------
// repository
// -------------------------------------------------------------
// Update implements [domain.MachineRepository].
func (m userMachine) Update(ctx context.Context, client database.QueryExecutor, condition database.Condition, changes ...database.Change) error {
builder := database.StatementBuilder{}
builder.WriteString("UPDATE user_machines SET ")
database.Changes(changes).Write(&builder)
writeCondition(&builder, condition)
m.writeReturning()
_, err := client.Exec(ctx, builder.String(), builder.Args()...)
return err
}
// -------------------------------------------------------------
// changes
// -------------------------------------------------------------
// SetDescription implements [domain.machineChanges].
func (m userMachine) SetDescription(description string) database.Change {
return database.NewChange(m.DescriptionColumn(), description)
}
// -------------------------------------------------------------
// conditions
// -------------------------------------------------------------
// DescriptionCondition implements [domain.machineConditions].
func (m userMachine) DescriptionCondition(op database.TextOperation, description string) database.Condition {
return database.NewTextCondition(m.DescriptionColumn(), op, description)
}
// -------------------------------------------------------------
// columns
// -------------------------------------------------------------
// DescriptionColumn implements [domain.machineColumns].
func (m userMachine) DescriptionColumn() database.Column {
return database.NewColumn("user_machines", "description")
}
func (m userMachine) columns() database.Columns {
return append(m.user.columns(), m.DescriptionColumn())
}
func (m *userMachine) writeReturning() {
builder := database.StatementBuilder{}
builder.WriteString(" RETURNING ")
m.columns().WriteQualified(&builder)
}