diff --git a/.secrets.baseline b/.secrets.baseline index c5258ed0f..a5c91df52 100644 --- a/.secrets.baseline +++ b/.secrets.baseline @@ -115,7 +115,7 @@ "filename": "core/apis.go", "hashed_secret": "f776bc8b6836b3498c27139f23f5d64e4041af0f", "is_verified": false, - "line_number": 169 + "line_number": 150 } ], "core/auth/apis.go": [ @@ -124,7 +124,7 @@ "filename": "core/auth/apis.go", "hashed_secret": "4d55af37dbbb6a42088d917caa1ca25428ec42c9", "is_verified": false, - "line_number": 1938 + "line_number": 1940 } ], "core/auth/auth.go": [ @@ -133,7 +133,7 @@ "filename": "core/auth/auth.go", "hashed_secret": "4d55af37dbbb6a42088d917caa1ca25428ec42c9", "is_verified": false, - "line_number": 2388 + "line_number": 2295 } ], "core/auth/auth_type_email.go": [ @@ -193,7 +193,7 @@ "filename": "core/auth/auth_type_oidc.go", "hashed_secret": "0ade4f3edccc8888bef404fe6b3c92c13cdfad6b", "is_verified": false, - "line_number": 377 + "line_number": 368 } ], "driven/emailer/adapter.go": [ @@ -279,5 +279,5 @@ } ] }, - "generated_at": "2022-08-09T22:15:53Z" + "generated_at": "2022-08-29T22:01:22Z" } diff --git a/core/apis.go b/core/apis.go index b66647996..c9d9b21c4 100644 --- a/core/apis.go +++ b/core/apis.go @@ -75,22 +75,7 @@ func (c *APIs) storeSystemData() error { transaction := func(context storage.TransactionContext) error { createAccount := false - //1. insert email auth type if does not exist - emailAuthType, err := c.app.storage.FindAuthType(auth.AuthTypeEmail) - if err != nil { - return errors.WrapErrorAction(logutils.ActionFind, model.TypeAuthType, nil, err) - } - if emailAuthType == nil { - newDocuments["auth_type"] = uuid.NewString() - emailAuthType = &model.AuthType{ID: newDocuments["auth_type"], Code: auth.AuthTypeEmail, Description: "Authentication type relying on email and password", - IsExternal: false, IsAnonymous: false, UseCredentials: true, IgnoreMFA: false} - _, err = c.app.storage.InsertAuthType(context, *emailAuthType) - if err != nil { - return errors.WrapErrorAction(logutils.ActionInsert, model.TypeAuthType, nil, err) - } - } - - //2. insert system org if does not exist + //1. insert system org if does not exist systemOrg, err := c.app.storage.FindSystemOrganization() if err != nil { return errors.WrapErrorAction(logutils.ActionFind, model.TypeOrganization, nil, err) @@ -108,7 +93,8 @@ func (c *APIs) storeSystemData() error { createAccount = true } - //3. insert system app and appOrg if they do not exist + //2. insert system app and appOrg if they do not exist + var systemAppOrg model.ApplicationOrganization systemAdminAppOrgs, err := c.app.storage.FindApplicationsOrganizationsByOrgID(systemOrg.ID) if err != nil { return errors.WrapErrorAction(logutils.ActionFind, model.TypeApplicationOrganization, nil, err) @@ -130,32 +116,27 @@ func (c *APIs) storeSystemData() error { systemAdminApp := &newSystemAdminApp //insert system admin apporg - emailSupport := []struct { - AuthTypeID string `bson:"auth_type_id"` - Params map[string]interface{} `bson:"params"` - }{ - {emailAuthType.ID, nil}, - } - supportedAuthTypes := make([]model.AuthTypesSupport, len(systemAdminApp.Types)) - for i, appType := range systemAdminApp.Types { - supportedAuthTypes[i] = model.AuthTypesSupport{AppTypeID: appType.ID, SupportedAuthTypes: emailSupport} - } - newDocuments["application_organization"] = uuid.NewString() newSystemAdminAppOrg := model.ApplicationOrganization{ID: newDocuments["application_organization"], Application: *systemAdminApp, Organization: *systemOrg, - SupportedAuthTypes: supportedAuthTypes, DateCreated: time.Now().UTC()} - _, err = c.app.storage.InsertApplicationOrganization(context, newSystemAdminAppOrg) + AuthTypes: map[string]model.SupportedAuthType{auth.AuthTypeEmail: {}}, DateCreated: time.Now().UTC()} + err = c.app.storage.InsertApplicationOrganization(context, newSystemAdminAppOrg) if err != nil { return errors.WrapErrorAction(logutils.ActionSave, model.TypeApplicationOrganization, nil, err) } - systemAdminAppOrgs = append(systemAdminAppOrgs, newSystemAdminAppOrg) + systemAppOrg = newSystemAdminAppOrg createAccount = true + } else if !systemAdminAppOrgs[0].IsAuthTypeSupported(auth.AuthTypeEmail) { + //insert email auth type if does not exist + systemAppOrg = systemAdminAppOrgs[0] + systemAppOrg.AuthTypes[auth.AuthTypeEmail] = model.SupportedAuthType{} + err = c.app.storage.UpdateApplicationOrganization(context, systemAppOrg) + if err != nil { + return errors.WrapErrorAction(logutils.ActionUpdate, model.TypeApplicationOrganization, nil, err) + } } - systemAppOrg := systemAdminAppOrgs[0] - - //4. insert api key if does not exist + //3. insert api key if does not exist apiKeys, err := c.Auth.GetApplicationAPIKeys(systemAppOrg.Application.ID) if err != nil { return errors.WrapErrorAction(logutils.ActionFind, model.TypeAPIKey, nil, err) @@ -173,7 +154,7 @@ func (c *APIs) storeSystemData() error { } } - //5. insert all_system_core permission and grant_all_permissions permission if they do not exist + //4. insert all_system_core permission and grant_all_permissions permission if they do not exist requiredPermissions := map[string]string{ model.PermissionAllSystemCore: "Gives access to all admin and system APIs", model.PermissionGrantAllPermissions: "Gives the ability to grant any permission", @@ -223,7 +204,7 @@ func (c *APIs) storeSystemData() error { if c.systemAccountEmail == "" || c.systemAccountPassword == "" { return errors.ErrorData(logutils.StatusMissing, "initial system account email or password", nil) } - newDocuments["account"], err = c.Auth.InitializeSystemAccount(context, *emailAuthType, systemAppOrg, model.PermissionAllSystemCore, c.systemAccountEmail, c.systemAccountPassword, c.logger.NewRequestLog(nil)) + newDocuments["account"], err = c.Auth.InitializeSystemAccount(context, systemAppOrg, model.PermissionAllSystemCore, c.systemAccountEmail, c.systemAccountPassword, c.logger.NewRequestLog(nil)) if err != nil { return errors.WrapErrorAction(logutils.ActionInitialize, "system account", nil, err) } @@ -529,16 +510,4 @@ func (s *systemImpl) SysDeleteAppConfig(id string) error { return s.app.sysDeleteAppConfig(id) } -func (s *systemImpl) SysCreateAuthTypes(code string, description string, isExternal bool, isAnonymous bool, useCredentials bool, ignoreMFA bool, params map[string]interface{}) (*model.AuthType, error) { - return s.app.sysCreateAuthTypes(code, description, isExternal, isAnonymous, useCredentials, ignoreMFA, params) -} - -func (s *systemImpl) SysGetAuthTypes() ([]model.AuthType, error) { - return s.app.sysGetAuthTypes() -} - -func (s *systemImpl) SysUpdateAuthTypes(ID string, code string, description string, isExternal bool, isAnonymous bool, useCredentials bool, ignoreMFA bool, params map[string]interface{}) error { - return s.app.SysUpdateAuthTypes(ID, code, description, isExternal, isAnonymous, useCredentials, ignoreMFA, params) -} - /// diff --git a/core/app_system.go b/core/app_system.go index cbf2b134e..b73a0ddc6 100644 --- a/core/app_system.go +++ b/core/app_system.go @@ -333,37 +333,3 @@ func (app *application) sysDeleteAppConfig(id string) error { return nil } - -func (app *application) sysCreateAuthTypes(code string, description string, isExternal bool, - isAnonymous bool, useCredentials bool, ignoreMFA bool, params map[string]interface{}) (*model.AuthType, error) { - - authTypeID, _ := uuid.NewUUID() - authType := model.AuthType{ID: authTypeID.String(), Code: code, Description: description, - IsExternal: isExternal, IsAnonymous: isAnonymous, UseCredentials: useCredentials, - IgnoreMFA: ignoreMFA, Params: params} - - insertedAuthType, err := app.storage.InsertAuthType(nil, authType) - if err != nil { - return nil, errors.WrapErrorAction(logutils.ActionFind, model.TypeAuthType, nil, err) - } - return insertedAuthType, nil -} - -func (app *application) sysGetAuthTypes() ([]model.AuthType, error) { - getAuthTypes, err := app.storage.FindAuthTypes() - if err != nil { - return nil, errors.WrapErrorAction(logutils.ActionGet, model.TypeAuthType, nil, err) - } - - return getAuthTypes, nil -} - -func (app *application) SysUpdateAuthTypes(ID string, code string, description string, isExternal bool, isAnonymous bool, useCredentials bool, ignoreMFA bool, params map[string]interface{}) error { - err := app.storage.UpdateAuthTypes(ID, code, description, isExternal, isAnonymous, useCredentials, ignoreMFA, params) - if err != nil { - return errors.WrapErrorAction(logutils.ActionUpdate, model.TypeAuthType, nil, err) - } - - return err - -} diff --git a/core/auth/apis.go b/core/auth/apis.go index 8f9304916..98f69c33c 100644 --- a/core/auth/apis.go +++ b/core/auth/apis.go @@ -78,7 +78,7 @@ func (a *Auth) Login(ipAddress string, deviceType string, deviceOS *string, devi //TODO - analyse what should go in one transaction //validate if the provided auth type is supported by the provided application and organization - authType, appType, appOrg, err := a.validateAuthType(authenticationType, appTypeIdentifier, orgID) + appType, appOrg, err := a.validateAuthType(authenticationType, appTypeIdentifier, orgID) if err != nil { return nil, nil, nil, errors.WrapErrorAction(logutils.ActionValidate, typeAuthType, nil, err) } @@ -107,26 +107,26 @@ func (a *Auth) Login(ipAddress string, deviceType string, deviceOS *string, devi var state string //get the auth type implementation for the auth type - if authType.IsAnonymous && !admin { + if authImpl, err := a.getAnonymousAuthTypeImpl(authenticationType); err == nil && !admin { anonymous = true anonymousID := "" - anonymousID, responseParams, err = a.applyAnonymousAuthType(*authType, creds) + anonymousID, responseParams, err = a.applyAnonymousAuthType(authImpl, creds) if err != nil { return nil, nil, nil, errors.WrapErrorAction("apply anonymous auth type", "user", nil, err) } sub = anonymousID - } else if authType.IsExternal { - accountAuthType, responseParams, mfaTypes, externalIDs, err = a.applyExternalAuthType(*authType, *appType, *appOrg, creds, params, profile, preferences, admin, l) + } else if authImpl, err := a.getExternalAuthTypeImpl(authenticationType); err == nil { + accountAuthType, responseParams, mfaTypes, externalIDs, err = a.applyExternalAuthType(authImpl, *appType, *appOrg, creds, params, profile, preferences, admin, l) if err != nil { return nil, nil, nil, errors.WrapErrorAction("apply external auth type", "user", nil, err) } sub = accountAuthType.Account.ID - } else { - message, accountAuthType, mfaTypes, externalIDs, err = a.applyAuthType(*authType, *appOrg, creds, params, profile, preferences, admin, l) + } else if authImpl, err := a.getAuthTypeImpl(authenticationType); err == nil { + message, accountAuthType, mfaTypes, externalIDs, err = a.applyAuthType(authImpl, *appOrg, creds, params, profile, preferences, admin, l) if err != nil { return nil, nil, nil, errors.WrapErrorAction("apply auth type", "user", nil, err) } @@ -138,6 +138,8 @@ func (a *Auth) Login(ipAddress string, deviceType string, deviceOS *string, devi sub = accountAuthType.Account.ID //the credentials are valid + } else { + return nil, nil, nil, errors.ErrorData(logutils.StatusInvalid, typeAuthType, logutils.StringArgs(authenticationType)) } //check if account is enrolled in MFA @@ -239,13 +241,13 @@ func (a *Auth) CanSignIn(authenticationType string, userIdentifier string, apiKe // Returns: // canLink (bool): valid when error is nil func (a *Auth) CanLink(authenticationType string, userIdentifier string, apiKey string, appTypeIdentifier string, orgID string) (bool, error) { - account, authTypeID, err := a.getAccount(authenticationType, userIdentifier, apiKey, appTypeIdentifier, orgID) + account, err := a.getAccount(authenticationType, userIdentifier, apiKey, appTypeIdentifier, orgID) if err != nil { return false, errors.WrapErrorAction(logutils.ActionGet, model.TypeAccount, nil, err) } if account != nil { - aat := account.GetAccountAuthType(authTypeID, userIdentifier) + aat := account.GetAccountAuthType(authenticationType, userIdentifier) return (aat != nil && aat.Unverified), nil } @@ -1614,10 +1616,10 @@ func (a *Auth) DeleteAccount(id string) error { } // InitializeSystemAccount initializes the first system account -func (a *Auth) InitializeSystemAccount(context storage.TransactionContext, authType model.AuthType, appOrg model.ApplicationOrganization, - allSystemPermission string, email string, password string, l *logs.Log) (string, error) { +func (a *Auth) InitializeSystemAccount(context storage.TransactionContext, appOrg model.ApplicationOrganization, allSystemPermission string, + email string, password string, l *logs.Log) (string, error) { //auth type - authImpl, err := a.getAuthTypeImpl(authType) + authImpl, err := a.getAuthTypeImpl(AuthTypeEmail) if err != nil { return "", errors.WrapErrorAction(logutils.ActionLoadCache, typeAuthType, nil, err) } diff --git a/core/auth/auth.go b/core/auth/auth.go index fc4c1c5a4..70f8fc29a 100644 --- a/core/auth/auth.go +++ b/core/auth/auth.go @@ -34,7 +34,6 @@ import ( "github.com/rokwire/core-auth-library-go/v2/sigauth" "github.com/rokwire/core-auth-library-go/v2/tokenauth" "golang.org/x/sync/syncmap" - "gopkg.in/go-playground/validator.v9" "gopkg.in/gomail.v2" "github.com/rokwire/logging-library-go/errors" @@ -101,9 +100,6 @@ type Auth struct { emailFrom string emailDialer *gomail.Dialer - cachedIdentityProviders *syncmap.Map //cache identityProviders - identityProvidersLock *sync.RWMutex - apiKeys *syncmap.Map //cache api keys / api_key (string) -> APIKey apiKeysLock *sync.RWMutex @@ -133,9 +129,6 @@ func NewAuth(serviceID string, host string, authPrivKey *rsa.PrivateKey, storage serviceAuthTypes := map[string]serviceAuthType{} mfaTypes := map[string]mfaType{} - cachedIdentityProviders := &syncmap.Map{} - identityProvidersLock := &sync.RWMutex{} - apiKeys := &syncmap.Map{} apiKeysLock := &sync.RWMutex{} @@ -143,8 +136,7 @@ func NewAuth(serviceID string, host string, authPrivKey *rsa.PrivateKey, storage auth := &Auth{storage: storage, emailer: emailer, logger: logger, authTypes: authTypes, externalAuthTypes: externalAuthTypes, anonymousAuthTypes: anonymousAuthTypes, serviceAuthTypes: serviceAuthTypes, mfaTypes: mfaTypes, authPrivKey: authPrivKey, ServiceRegManager: nil, serviceID: serviceID, host: host, minTokenExp: *minTokenExp, - maxTokenExp: *maxTokenExp, profileBB: profileBB, cachedIdentityProviders: cachedIdentityProviders, identityProvidersLock: identityProvidersLock, - timerDone: timerDone, emailDialer: emailDialer, emailFrom: smtpFrom, apiKeys: apiKeys, apiKeysLock: apiKeysLock} + maxTokenExp: *maxTokenExp, profileBB: profileBB, timerDone: timerDone, emailDialer: emailDialer, emailFrom: smtpFrom, apiKeys: apiKeys, apiKeysLock: apiKeysLock} err := auth.storeReg() if err != nil { @@ -193,11 +185,6 @@ func NewAuth(serviceID string, host string, authPrivKey *rsa.PrivateKey, storage initPhoneMfa(auth) initRecoveryMfa(auth) - err = auth.cacheIdentityProviders() - if err != nil { - logger.Warnf("NewAuth() failed to cache identity providers: %v", err) - } - err = auth.cacheAPIKeys() if err != nil { logger.Warnf("NewAuth() failed to cache api keys: %v", err) @@ -207,18 +194,12 @@ func NewAuth(serviceID string, host string, authPrivKey *rsa.PrivateKey, storage } -func (a *Auth) applyExternalAuthType(authType model.AuthType, appType model.ApplicationType, appOrg model.ApplicationOrganization, +func (a *Auth) applyExternalAuthType(authImpl externalAuthType, appType model.ApplicationType, appOrg model.ApplicationOrganization, creds string, params string, regProfile model.Profile, regPreferences map[string]interface{}, admin bool, l *logs.Log) (*model.AccountAuthType, map[string]interface{}, []model.MFAType, map[string]string, error) { var accountAuthType *model.AccountAuthType var mfaTypes []model.MFAType var externalIDs map[string]string - //external auth type - authImpl, err := a.getExternalAuthTypeImpl(authType) - if err != nil { - return nil, nil, nil, nil, errors.WrapErrorAction(logutils.ActionLoadCache, typeExternalAuthType, nil, err) - } - //1. get the user from the external system //var externalUser *model.ExternalSystemUser externalUser, extParams, err := authImpl.externalLogin(authType, appType, appOrg, creds, params, l) @@ -542,12 +523,7 @@ func (a *Auth) updateProfileIfNeeded(account model.Account, externalUser model.E return nil } -func (a *Auth) applyAnonymousAuthType(authType model.AuthType, creds string) (string, map[string]interface{}, error) { //auth type - authImpl, err := a.getAnonymousAuthTypeImpl(authType) - if err != nil { - return "", nil, errors.WrapErrorAction(logutils.ActionLoadCache, typeAnonymousAuthType, nil, err) - } - +func (a *Auth) applyAnonymousAuthType(authImpl anonymousAuthType, creds string) (string, map[string]interface{}, error) { //auth type //Check the credentials anonymousID, anonymousParams, err := authImpl.checkCredentials(creds) if err != nil { @@ -557,15 +533,8 @@ func (a *Auth) applyAnonymousAuthType(authType model.AuthType, creds string) (st return anonymousID, anonymousParams, nil } -func (a *Auth) applyAuthType(authType model.AuthType, appOrg model.ApplicationOrganization, creds string, params string, +func (a *Auth) applyAuthType(authImpl authType, appOrg model.ApplicationOrganization, creds string, params string, regProfile model.Profile, regPreferences map[string]interface{}, admin bool, l *logs.Log) (string, *model.AccountAuthType, []model.MFAType, map[string]string, error) { - - //auth type - authImpl, err := a.getAuthTypeImpl(authType) - if err != nil { - return "", nil, nil, nil, errors.WrapErrorAction(logutils.ActionLoadCache, typeAuthType, nil, err) - } - //check if the user exists check userIdentifier, err := authImpl.getUserIdentifier(creds) if err != nil { @@ -894,9 +863,9 @@ func (a *Auth) validateAPIKey(apiKey string, appID string) error { return nil } -func (a *Auth) canSignIn(account *model.Account, authTypeID string, userIdentifier string) bool { +func (a *Auth) canSignIn(account *model.Account, authType string, userIdentifier string) bool { if account != nil { - aat := account.GetAccountAuthType(authTypeID, userIdentifier) + aat := account.GetAccountAuthType(authType, userIdentifier) return aat == nil || !aat.Linked || !aat.Unverified } @@ -933,31 +902,31 @@ func (a *Auth) isSignUp(accountExists bool, params string, l *logs.Log) (bool, e return true, nil } -func (a *Auth) getAccount(authenticationType string, userIdentifier string, apiKey string, appTypeIdentifier string, orgID string) (*model.Account, string, error) { +func (a *Auth) getAccount(authenticationType string, userIdentifier string, apiKey string, appTypeIdentifier string, orgID string) (*model.Account, error) { //validate if the provided auth type is supported by the provided application and organization - authType, _, appOrg, err := a.validateAuthType(authenticationType, appTypeIdentifier, orgID) + _, appOrg, err := a.validateAuthType(authenticationType, appTypeIdentifier, orgID) if err != nil { - return nil, "", errors.WrapErrorAction(logutils.ActionValidate, typeAuthType, nil, err) + return nil, errors.WrapErrorAction(logutils.ActionValidate, typeAuthType, nil, err) } //do not allow for admins if appOrg.Application.Admin { - return nil, "", errors.New("not allowed for admins") + return nil, errors.New("not allowed for admins") } //TODO: Ideally we would not make many database calls before validating the API key. Currently needed to get app ID err = a.validateAPIKey(apiKey, appOrg.Application.ID) if err != nil { - return nil, "", errors.WrapErrorData(logutils.StatusInvalid, model.TypeAPIKey, nil, err) + return nil, errors.WrapErrorData(logutils.StatusInvalid, model.TypeAPIKey, nil, err) } //check if the account exists check - account, err := a.storage.FindAccount(nil, appOrg.ID, authType.ID, userIdentifier) + account, err := a.storage.FindAccount(nil, appOrg.ID, authenticationType, userIdentifier) if err != nil { - return nil, "", errors.WrapErrorAction(logutils.ActionFind, model.TypeAccount, nil, err) + return nil, errors.WrapErrorAction(logutils.ActionFind, model.TypeAccount, nil, err) } - return account, authType.ID, nil + return account, nil } func (a *Auth) findAccountAuthType(account *model.Account, authType *model.AuthType, identifier string) (*model.AccountAuthType, error) { @@ -2000,39 +1969,33 @@ func (a *Auth) registerMfaType(name string, mfa mfaType) error { return nil } -func (a *Auth) validateAuthType(authenticationType string, appTypeIdentifier string, orgID string) (*model.AuthType, *model.ApplicationType, *model.ApplicationOrganization, error) { - //get the auth type - authType, err := a.storage.FindAuthType(authenticationType) - if err != nil || authType == nil { - return nil, nil, nil, errors.WrapErrorAction(logutils.ActionValidate, typeAuthType, logutils.StringArgs(authenticationType), err) - } - +func (a *Auth) validateAuthType(authenticationType string, appTypeIdentifier string, orgID string) (*model.ApplicationType, *model.ApplicationOrganization, error) { //get the app type applicationType, err := a.storage.FindApplicationType(appTypeIdentifier) if err != nil { - return nil, nil, nil, errors.WrapErrorAction(logutils.ActionFind, model.TypeApplicationType, logutils.StringArgs(appTypeIdentifier), err) + return nil, nil, errors.WrapErrorAction(logutils.ActionFind, model.TypeApplicationType, logutils.StringArgs(appTypeIdentifier), err) } if applicationType == nil { - return nil, nil, nil, errors.ErrorData(logutils.StatusMissing, model.TypeApplicationType, logutils.StringArgs(appTypeIdentifier)) + return nil, nil, errors.ErrorData(logutils.StatusMissing, model.TypeApplicationType, logutils.StringArgs(appTypeIdentifier)) } //get the app org applicationID := applicationType.Application.ID appOrg, err := a.storage.FindApplicationOrganization(applicationID, orgID) if err != nil { - return nil, nil, nil, errors.WrapErrorAction(logutils.ActionFind, model.TypeApplicationOrganization, &logutils.FieldArgs{"app_id": applicationID, "org_id": orgID}, err) + return nil, nil, errors.WrapErrorAction(logutils.ActionFind, model.TypeApplicationOrganization, &logutils.FieldArgs{"app_id": applicationID, "org_id": orgID}, err) } if appOrg == nil { - return nil, nil, nil, errors.ErrorData(logutils.StatusMissing, model.TypeApplicationOrganization, &logutils.FieldArgs{"app_id": applicationID, "org_id": orgID}) + return nil, nil, errors.ErrorData(logutils.StatusMissing, model.TypeApplicationOrganization, &logutils.FieldArgs{"app_id": applicationID, "org_id": orgID}) } //check if the auth type is supported for this application and organization - if !appOrg.IsAuthTypeSupported(*applicationType, *authType) { - return nil, nil, nil, errors.ErrorAction(logutils.ActionValidate, "not supported auth type for application and organization", &logutils.FieldArgs{"app_type_id": applicationType.ID, "auth_type_id": authType.ID}) + if !appOrg.IsAuthTypeSupported(authenticationType) { + return nil, nil, errors.ErrorData(logutils.StatusInvalid, typeAuthType, &logutils.FieldArgs{"auth_type_id": authenticationType, "app_id": applicationID, "org_id": orgID}) } - return authType, applicationType, appOrg, nil + return applicationType, appOrg, nil } func (a *Auth) validateAuthTypeForAppOrg(authenticationType string, appID string, orgID string) (*model.AuthType, *model.ApplicationOrganization, error) { @@ -2058,35 +2021,33 @@ func (a *Auth) validateAuthTypeForAppOrg(authenticationType string, appID string return nil, nil, errors.ErrorData(logutils.StatusInvalid, typeAuthType, &logutils.FieldArgs{"app_org_id": appOrg.ID, "auth_type": authenticationType}) } -func (a *Auth) getAuthTypeImpl(authType model.AuthType) (authType, error) { - if auth, ok := a.authTypes[authType.Code]; ok { +func (a *Auth) getAuthTypeImpl(authType string) (authType, error) { + if auth, ok := a.authTypes[authType]; ok { return auth, nil } - return nil, errors.ErrorData(logutils.StatusInvalid, typeAuthType, logutils.StringArgs(authType.Code)) + return nil, errors.ErrorData(logutils.StatusInvalid, typeAuthType, logutils.StringArgs(authType)) } -func (a *Auth) getExternalAuthTypeImpl(authType model.AuthType) (externalAuthType, error) { - key := authType.Code - +func (a *Auth) getExternalAuthTypeImpl(authType string) (externalAuthType, error) { //illinois_oidc, other_oidc - if strings.HasSuffix(authType.Code, "_oidc") { - key = "oidc" + if strings.HasSuffix(authType, "_oidc") { + authType = "oidc" } - if auth, ok := a.externalAuthTypes[key]; ok { + if auth, ok := a.externalAuthTypes[authType]; ok { return auth, nil } - return nil, errors.ErrorData(logutils.StatusInvalid, typeExternalAuthType, logutils.StringArgs(key)) + return nil, errors.ErrorData(logutils.StatusInvalid, typeExternalAuthType, logutils.StringArgs(authType)) } -func (a *Auth) getAnonymousAuthTypeImpl(authType model.AuthType) (anonymousAuthType, error) { - if auth, ok := a.anonymousAuthTypes[authType.Code]; ok { +func (a *Auth) getAnonymousAuthTypeImpl(authType string) (anonymousAuthType, error) { + if auth, ok := a.anonymousAuthTypes[authType]; ok { return auth, nil } - return nil, errors.ErrorData(logutils.StatusInvalid, typeAnonymousAuthType, logutils.StringArgs(authType.Code)) + return nil, errors.ErrorData(logutils.StatusInvalid, typeAnonymousAuthType, logutils.StringArgs(authType)) } func (a *Auth) getServiceAuthTypeImpl(serviceAuthType string) (serviceAuthType, error) { @@ -2317,60 +2278,6 @@ func (a *Auth) storeReg() error { return nil } -// cacheIdentityProviders caches the identity providers -func (a *Auth) cacheIdentityProviders() error { - a.logger.Info("cacheIdentityProviders..") - - identityProviders, err := a.storage.LoadIdentityProviders() - if err != nil { - return errors.WrapErrorAction(logutils.ActionFind, model.TypeIdentityProvider, nil, err) - } - - a.setCachedIdentityProviders(identityProviders) - - return nil -} - -func (a *Auth) setCachedIdentityProviders(identityProviders []model.IdentityProvider) { - a.identityProvidersLock.Lock() - defer a.identityProvidersLock.Unlock() - - a.cachedIdentityProviders = &syncmap.Map{} - validate := validator.New() - - for _, idPr := range identityProviders { - err := validate.Struct(idPr) - if err == nil { - a.cachedIdentityProviders.Store(idPr.ID, idPr) - } else { - a.logger.Errorf("failed to validate and cache identity provider with id %s: %s", idPr.ID, err.Error()) - } - } -} - -func (a *Auth) getCachedIdentityProviderConfig(id string, appTypeID string) (*model.IdentityProviderConfig, error) { - a.identityProvidersLock.RLock() - defer a.identityProvidersLock.RUnlock() - - errArgs := &logutils.FieldArgs{"id": id, "app_type_id": appTypeID} - - item, _ := a.cachedIdentityProviders.Load(id) - if item != nil { - identityProvider, ok := item.(model.IdentityProvider) - if !ok { - return nil, errors.ErrorAction(logutils.ActionCast, model.TypeIdentityProvider, errArgs) - } - //find the identity provider config - for _, idPrConfig := range identityProvider.Configs { - if idPrConfig.AppTypeID == appTypeID { - return &idPrConfig, nil - } - } - return nil, errors.ErrorData(logutils.StatusMissing, model.TypeIdentityProviderConfig, errArgs) - } - return nil, errors.ErrorData(logutils.StatusMissing, model.TypeOrganization, errArgs) -} - func (a *Auth) cacheAPIKeys() error { apiKeys, err := a.storage.LoadAPIKeys() if err != nil { @@ -2587,11 +2494,6 @@ type StorageListener struct { storage.DefaultListenerImpl } -// OnIdentityProvidersUpdated notifies that identity providers have been updated -func (al *StorageListener) OnIdentityProvidersUpdated() { - al.auth.cacheIdentityProviders() -} - // OnAPIKeysUpdated notifies api keys have been updated func (al *StorageListener) OnAPIKeysUpdated() { al.auth.cacheAPIKeys() diff --git a/core/auth/auth_type_oidc.go b/core/auth/auth_type_oidc.go index 764e0d15b..ac8ceda8f 100644 --- a/core/auth/auth_type_oidc.go +++ b/core/auth/auth_type_oidc.go @@ -105,7 +105,7 @@ func oidcRefreshParamsFromMap(val map[string]interface{}) (*oidcRefreshParams, e return &oidcRefreshParams{RefreshToken: refreshToken, RedirectURI: redirectURI}, nil } -func (a *oidcAuthImpl) externalLogin(authType model.AuthType, appType model.ApplicationType, appOrg model.ApplicationOrganization, creds string, params string, l *logs.Log) (*model.ExternalSystemUser, map[string]interface{}, error) { +func (a *oidcAuthImpl) externalLogin(appType model.ApplicationType, appOrg model.ApplicationOrganization, creds string, params string, l *logs.Log) (*model.ExternalSystemUser, map[string]interface{}, error) { var loginParams oidcLoginParams err := json.Unmarshal([]byte(params), &loginParams) if err != nil { @@ -117,7 +117,7 @@ func (a *oidcAuthImpl) externalLogin(authType model.AuthType, appType model.Appl return nil, nil, errors.WrapErrorAction(logutils.ActionValidate, typeOidcLoginParams, nil, err) } - oidcConfig, err := a.getOidcAuthConfig(authType, appType) + oidcConfig, err := a.getOidcAuthConfig(appOrg, appType) if err != nil { return nil, nil, errors.WrapErrorAction(logutils.ActionGet, typeOidcAuthConfig, nil, err) } @@ -127,7 +127,7 @@ func (a *oidcAuthImpl) externalLogin(authType model.AuthType, appType model.Appl return nil, nil, errors.WrapErrorAction(logutils.ActionParse, "oidc login creds", nil, err) } - externalUser, parameters, err := a.newToken(parsedCreds.Query().Get("code"), authType, appType, appOrg, &loginParams, oidcConfig, l) + externalUser, parameters, err := a.newToken(parsedCreds.Query().Get("code"), appType, appOrg, &loginParams, oidcConfig, l) if err != nil { return nil, nil, err } @@ -136,22 +136,22 @@ func (a *oidcAuthImpl) externalLogin(authType model.AuthType, appType model.Appl } // refresh must be implemented for OIDC auth -func (a *oidcAuthImpl) refresh(params map[string]interface{}, authType model.AuthType, appType model.ApplicationType, appOrg model.ApplicationOrganization, l *logs.Log) (*model.ExternalSystemUser, map[string]interface{}, error) { +func (a *oidcAuthImpl) refresh(params map[string]interface{}, appType model.ApplicationType, appOrg model.ApplicationOrganization, l *logs.Log) (*model.ExternalSystemUser, map[string]interface{}, error) { refreshParams, err := oidcRefreshParamsFromMap(params) if err != nil { return nil, nil, errors.WrapErrorAction(logutils.ActionParse, typeAuthRefreshParams, nil, err) } - oidcConfig, err := a.getOidcAuthConfig(authType, appType) + oidcConfig, err := a.getOidcAuthConfig(appOrg, appType) if err != nil { return nil, nil, errors.WrapErrorAction(logutils.ActionGet, typeOidcAuthConfig, nil, err) } - return a.refreshToken(authType, appType, appOrg, refreshParams, oidcConfig, l) + return a.refreshToken(appType, appOrg, refreshParams, oidcConfig, l) } -func (a *oidcAuthImpl) getLoginURL(authType model.AuthType, appType model.ApplicationType, redirectURI string, l *logs.Log) (string, map[string]interface{}, error) { - oidcConfig, err := a.getOidcAuthConfig(authType, appType) +func (a *oidcAuthImpl) getLoginURL(appType model.ApplicationType, appOrg model.ApplicationOrganization, redirectURI string, l *logs.Log) (string, map[string]interface{}, error) { + oidcConfig, err := a.getOidcAuthConfig(appOrg, appType) if err != nil { return "", nil, errors.WrapErrorAction(logutils.ActionGet, typeOidcAuthConfig, nil, err) } @@ -199,15 +199,7 @@ func (a *oidcAuthImpl) getLoginURL(authType model.AuthType, appType model.Applic return authURL + "?" + query.Encode(), responseParams, nil } -func (a *oidcAuthImpl) checkToken(idToken string, authType model.AuthType, appType model.ApplicationType, oidcConfig *oidcAuthConfig, l *logs.Log) (string, error) { - var err error - if oidcConfig == nil { - oidcConfig, err = a.getOidcAuthConfig(authType, appType) - if err != nil { - return "", errors.WrapErrorAction(logutils.ActionGet, typeOidcAuthConfig, nil, err) - } - } - +func (a *oidcAuthImpl) checkToken(idToken string, appType model.ApplicationType, oidcConfig *oidcAuthConfig, l *logs.Log) (string, error) { oidcProvider := oidcConfig.Host oidcClientID := oidcConfig.ClientID @@ -235,7 +227,7 @@ func (a *oidcAuthImpl) checkToken(idToken string, authType model.AuthType, appTy return sub, nil } -func (a *oidcAuthImpl) newToken(code string, authType model.AuthType, appType model.ApplicationType, appOrg model.ApplicationOrganization, params *oidcLoginParams, oidcConfig *oidcAuthConfig, l *logs.Log) (*model.ExternalSystemUser, map[string]interface{}, error) { +func (a *oidcAuthImpl) newToken(code string, appType model.ApplicationType, appOrg model.ApplicationOrganization, params *oidcLoginParams, oidcConfig *oidcAuthConfig, l *logs.Log) (*model.ExternalSystemUser, map[string]interface{}, error) { bodyData := map[string]string{ "code": code, "grant_type": "authorization_code", @@ -246,10 +238,10 @@ func (a *oidcAuthImpl) newToken(code string, authType model.AuthType, appType mo bodyData["code_verifier"] = params.CodeVerifier } - return a.loadOidcTokensAndInfo(bodyData, oidcConfig, authType, appType, appOrg, params.RedirectURI, l) + return a.loadOidcTokensAndInfo(bodyData, oidcConfig, appType, appOrg, params.RedirectURI, l) } -func (a *oidcAuthImpl) refreshToken(authType model.AuthType, appType model.ApplicationType, appOrg model.ApplicationOrganization, +func (a *oidcAuthImpl) refreshToken(appType model.ApplicationType, appOrg model.ApplicationOrganization, params *oidcRefreshParams, oidcConfig *oidcAuthConfig, l *logs.Log) (*model.ExternalSystemUser, map[string]interface{}, error) { if !oidcConfig.UseRefresh { return nil, nil, errors.Newf("refresh tokens not enabled for org_id=%s, app_id=%s", @@ -263,17 +255,17 @@ func (a *oidcAuthImpl) refreshToken(authType model.AuthType, appType model.Appli "client_id": oidcConfig.ClientID, } - return a.loadOidcTokensAndInfo(bodyData, oidcConfig, authType, appType, appOrg, params.RedirectURI, l) + return a.loadOidcTokensAndInfo(bodyData, oidcConfig, appType, appOrg, params.RedirectURI, l) } -func (a *oidcAuthImpl) loadOidcTokensAndInfo(bodyData map[string]string, oidcConfig *oidcAuthConfig, authType model.AuthType, appType model.ApplicationType, +func (a *oidcAuthImpl) loadOidcTokensAndInfo(bodyData map[string]string, oidcConfig *oidcAuthConfig, appType model.ApplicationType, appOrg model.ApplicationOrganization, redirectURI string, l *logs.Log) (*model.ExternalSystemUser, map[string]interface{}, error) { token, err := a.loadOidcTokenWithParams(bodyData, oidcConfig) if err != nil { return nil, nil, errors.WrapErrorAction(logutils.ActionGet, typeOidcToken, nil, err) } - sub, err := a.checkToken(token.IDToken, authType, appType, oidcConfig, l) + sub, err := a.checkToken(token.IDToken, appType, oidcConfig, l) if err != nil { return nil, nil, errors.WrapErrorAction(logutils.ActionValidate, typeOidcToken, nil, err) } @@ -298,10 +290,9 @@ func (a *oidcAuthImpl) loadOidcTokensAndInfo(bodyData map[string]string, oidcCon return nil, nil, errors.Newf("mismatching user info sub %s and id token sub %s", userClaimsSub, sub) } - identityProviderID, _ := authType.Params["identity_provider"].(string) - identityProviderSetting := appOrg.FindIdentityProviderSetting(identityProviderID) - if identityProviderSetting == nil { - return nil, nil, errors.ErrorData(logutils.StatusMissing, model.TypeIdentityProviderConfig, &logutils.FieldArgs{"app_org": appOrg.ID, "identity_provider_id": identityProviderID}) + authTypeConfig := appOrg.GetAuthTypeConfig(a.authType) + if authTypeConfig == nil { + return nil, nil, errors.ErrorData(logutils.StatusMissing, model.TypeAuthTypeConfig, &logutils.FieldArgs{"app_org_id": appOrg.ID, "auth_type": a.authType}) } //identifier @@ -462,39 +453,62 @@ func (a *oidcAuthImpl) loadOidcUserInfo(token *oidcToken, url string) ([]byte, e return body, nil } -func (a *oidcAuthImpl) getOidcAuthConfig(authType model.AuthType, appType model.ApplicationType) (*oidcAuthConfig, error) { - errFields := &logutils.FieldArgs{"auth_type_id": authType.ID, "app_type_id": appType} +func (a *oidcAuthImpl) getOidcAuthConfig(appOrg model.ApplicationOrganization, appType model.ApplicationType) (*oidcAuthConfig, error) { + errFields := &logutils.FieldArgs{"app_org_id": appOrg.ID, "auth_type": a.authType, "app_type_id": appType.ID} - identityProviderID, ok := authType.Params["identity_provider"].(string) - if !ok { - return nil, errors.ErrorData(logutils.StatusInvalid, "identity provider", errFields) - } - appTypeID := appType.ID - authConfig, err := a.auth.getCachedIdentityProviderConfig(identityProviderID, appTypeID) - if err != nil { - return nil, errors.WrapErrorAction(logutils.ActionFind, model.TypeIdentityProviderConfig, errFields, err) + appTypeAuthConfig := appOrg.GetAppTypeAuthConfig(a.authType, appType.ID) + if appTypeAuthConfig == nil { + return nil, errors.ErrorData(logutils.StatusMissing, model.TypeApplicationTypeAuthConfig, errFields) } - configBytes, err := json.Marshal(authConfig.Config) + configBytes, err := json.Marshal(appTypeAuthConfig) if err != nil { - return nil, errors.WrapErrorAction(logutils.ActionMarshal, model.TypeIdentityProviderConfig, errFields, err) + return nil, errors.WrapErrorAction(logutils.ActionMarshal, model.TypeApplicationTypeAuthConfig, errFields, err) } var oidcConfig oidcAuthConfig err = json.Unmarshal(configBytes, &oidcConfig) if err != nil { - return nil, errors.WrapErrorAction(logutils.ActionUnmarshal, model.TypeIdentityProviderConfig, errFields, err) + return nil, errors.WrapErrorAction(logutils.ActionUnmarshal, model.TypeApplicationTypeAuthConfig, errFields, err) } validate := validator.New() err = validate.Struct(oidcConfig) if err != nil { - return nil, errors.WrapErrorAction(logutils.ActionValidate, model.TypeIdentityProviderConfig, errFields, err) + return nil, errors.WrapErrorAction(logutils.ActionValidate, model.TypeApplicationTypeAuthConfig, errFields, err) } return &oidcConfig, nil } +func (a *oidcAuthImpl) getOidcIdentityProviderConfig(appOrg model.ApplicationOrganization) (*model.IdentityProviderSetting, error) { + errFields := &logutils.FieldArgs{"app_org_id": appOrg.ID, "auth_type": a.authType} + + authTypeConfig := appOrg.GetAuthTypeConfig(a.authType) + if authTypeConfig == nil { + return nil, errors.ErrorData(logutils.StatusMissing, model.TypeAuthTypeConfig, errFields) + } + + configBytes, err := json.Marshal(authTypeConfig) + if err != nil { + return nil, errors.WrapErrorAction(logutils.ActionMarshal, model.TypeAuthTypeConfig, errFields, err) + } + + var idpSettings model.IdentityProviderSetting + err = json.Unmarshal(configBytes, &idpSettings) + if err != nil { + return nil, errors.WrapErrorAction(logutils.ActionUnmarshal, model.TypeAuthTypeConfig, errFields, err) + } + + validate := validator.New() + err = validate.Struct(idpSettings) + if err != nil { + return nil, errors.WrapErrorAction(logutils.ActionValidate, model.TypeIdentityProviderSettings, errFields, err) + } + + return &idpSettings, nil +} + // --- Helper functions --- // generatePkceChallenge generates and returns a PKCE code challenge and verifier diff --git a/core/auth/interfaces.go b/core/auth/interfaces.go index 7283acad5..f73156b6c 100644 --- a/core/auth/interfaces.go +++ b/core/auth/interfaces.go @@ -31,13 +31,13 @@ type authType interface { // Returns: // message (string): Success message if verification is required. If verification is not required, return "" // credentialValue (map): Credential value - signUp(authType model.AuthType, appOrg model.ApplicationOrganization, creds string, params string, newCredentialID string, l *logs.Log) (string, map[string]interface{}, error) + signUp(appOrg model.ApplicationOrganization, creds string, params string, newCredentialID string, l *logs.Log) (string, map[string]interface{}, error) //signUpAdmin signs up a new admin user // Returns: // password (string): newly generated password // credentialValue (map): Credential value - signUpAdmin(authType model.AuthType, appOrg model.ApplicationOrganization, identifier string, password string, newCredentialID string) (map[string]interface{}, map[string]interface{}, error) + signUpAdmin(appOrg model.ApplicationOrganization, identifier string, password string, newCredentialID string) (map[string]interface{}, map[string]interface{}, error) //verifies credential (checks the verification code generated on email signup for email auth type) // Returns: @@ -77,11 +77,11 @@ type authType interface { // these are the different identity providers - illinois_oidc etc type externalAuthType interface { //getLoginUrl retrieves and pre-formats a login url and params for the SSO provider - getLoginURL(authType model.AuthType, appType model.ApplicationType, redirectURI string, l *logs.Log) (string, map[string]interface{}, error) + getLoginURL(appType model.ApplicationType, appOrg model.ApplicationOrganization, redirectURI string, l *logs.Log) (string, map[string]interface{}, error) //externalLogin logins in the external system and provides the authenticated user - externalLogin(authType model.AuthType, appType model.ApplicationType, appOrg model.ApplicationOrganization, creds string, params string, l *logs.Log) (*model.ExternalSystemUser, map[string]interface{}, error) + externalLogin(appType model.ApplicationType, appOrg model.ApplicationOrganization, creds string, params string, l *logs.Log) (*model.ExternalSystemUser, map[string]interface{}, error) //refresh refreshes tokens - refresh(params map[string]interface{}, authType model.AuthType, appType model.ApplicationType, appOrg model.ApplicationOrganization, l *logs.Log) (*model.ExternalSystemUser, map[string]interface{}, error) + refresh(params map[string]interface{}, appType model.ApplicationType, appOrg model.ApplicationOrganization, l *logs.Log) (*model.ExternalSystemUser, map[string]interface{}, error) } // anonymousAuthType is the interface for authentication for auth types which are anonymous @@ -383,7 +383,7 @@ type APIs interface { UnlinkAccountAuthType(accountID string, authenticationType string, appTypeIdentifier string, identifier string, l *logs.Log) (*model.Account, error) //InitializeSystemAccount initializes the first system account - InitializeSystemAccount(context storage.TransactionContext, authType model.AuthType, appOrg model.ApplicationOrganization, allSystemPermission string, email string, password string, l *logs.Log) (string, error) + InitializeSystemAccount(context storage.TransactionContext, appOrg model.ApplicationOrganization, allSystemPermission string, email string, password string, l *logs.Log) (string, error) //GrantAccountPermissions grants new permissions to an account after validating the assigner has required permissions GrantAccountPermissions(context storage.TransactionContext, account *model.Account, permissionNames []string, assignerPermissions []string) error @@ -446,9 +446,6 @@ type Storage interface { PerformTransaction(func(context storage.TransactionContext) error) error - //AuthTypes - FindAuthType(codeOrID string) (*model.AuthType, error) - //LoginsSessions InsertLoginSession(context storage.TransactionContext, session model.LoginSession) error FindLoginSessions(context storage.TransactionContext, identifier string) ([]model.LoginSession, error) @@ -466,7 +463,7 @@ type Storage interface { /// //Accounts - FindAccount(context storage.TransactionContext, appOrgID string, authTypeID string, accountAuthTypeIdentifier string) (*model.Account, error) + // FindAccount(context storage.TransactionContext, appOrgID string, authType string, accountAuthTypeIdentifier string) (*model.Account, error) FindAccountByID(context storage.TransactionContext, id string) (*model.Account, error) InsertAccount(context storage.TransactionContext, account model.Account) (*model.Account, error) SaveAccount(context storage.TransactionContext, account *model.Account) error @@ -474,7 +471,7 @@ type Storage interface { //Profiles UpdateProfile(context storage.TransactionContext, profile model.Profile) error - FindProfiles(appID string, authTypeID string, accountAuthTypeIdentifier string) ([]model.Profile, error) + // FindProfiles(appID string, authType string, accountAuthTypeIdentifier string) ([]model.Profile, error) //ServiceAccounts FindServiceAccount(context storage.TransactionContext, accountID string, appID string, orgID string) (*model.ServiceAccount, error) @@ -526,9 +523,6 @@ type Storage interface { SaveServiceReg(reg *model.ServiceReg) error DeleteServiceReg(serviceID string) error - //IdentityProviders - LoadIdentityProviders() ([]model.IdentityProvider, error) - //ServiceAuthorizations FindServiceAuthorization(userID string, orgID string) (*model.ServiceAuthorization, error) SaveServiceAuthorization(authorization *model.ServiceAuthorization) error diff --git a/core/interfaces.go b/core/interfaces.go index b15e9f8be..7627b67a3 100644 --- a/core/interfaces.go +++ b/core/interfaces.go @@ -113,10 +113,6 @@ type System interface { SysCreateAppConfig(appTypeID string, orgID *string, data map[string]interface{}, versionNumbers model.VersionNumbers) (*model.ApplicationConfig, error) SysUpdateAppConfig(id string, appTypeID string, orgID *string, data map[string]interface{}, versionNumbers model.VersionNumbers) error SysDeleteAppConfig(id string) error - - SysCreateAuthTypes(code string, description string, isExternal bool, isAnonymous bool, useCredentials bool, ignoreMFA bool, params map[string]interface{}) (*model.AuthType, error) - SysGetAuthTypes() ([]model.AuthType, error) - SysUpdateAuthTypes(ID string, code string, description string, isExternal bool, isAnonymous bool, useCredentials bool, ignoreMFA bool, params map[string]interface{}) error } // Storage is used by core to storage data - DB storage adapter, file storage adapter etc @@ -125,8 +121,6 @@ type Storage interface { PerformTransaction(func(context storage.TransactionContext) error) error - FindAuthType(codeOrID string) (*model.AuthType, error) - FindAccountByID(context storage.TransactionContext, id string) (*model.Account, error) FindAccounts(limit int, offset int, appID string, orgID string, accountID *string, firstName *string, lastName *string, authType *string, authTypeIdentifier *string, hasPermissions *bool, permissions []string, roleIDs []string, groupIDs []string) ([]model.Account, error) @@ -190,10 +184,6 @@ type Storage interface { FindApplication(ID string) (*model.Application, error) FindApplications() ([]model.Application, error) - InsertAuthType(context storage.TransactionContext, authType model.AuthType) (*model.AuthType, error) - FindAuthTypes() ([]model.AuthType, error) - UpdateAuthTypes(ID string, code string, description string, isExternal bool, isAnonymous bool, useCredentials bool, ignoreMFA bool, params map[string]interface{}) error - FindApplicationType(id string) (*model.ApplicationType, error) FindAppConfigs(appTypeIdentifier string, appOrgID *string, versionNumbers *model.VersionNumbers) ([]model.ApplicationConfig, error) @@ -205,7 +195,8 @@ type Storage interface { FindApplicationsOrganizationsByOrgID(orgID string) ([]model.ApplicationOrganization, error) FindApplicationOrganization(appID string, orgID string) (*model.ApplicationOrganization, error) - InsertApplicationOrganization(context storage.TransactionContext, applicationOrganization model.ApplicationOrganization) (*model.ApplicationOrganization, error) + InsertApplicationOrganization(context storage.TransactionContext, applicationOrganization model.ApplicationOrganization) error + UpdateApplicationOrganization(context storage.TransactionContext, applicationOrganization model.ApplicationOrganization) error InsertAPIKey(context storage.TransactionContext, apiKey model.APIKey) (*model.APIKey, error) } diff --git a/core/model/application.go b/core/model/application.go index df89189f3..008177d29 100644 --- a/core/model/application.go +++ b/core/model/application.go @@ -40,6 +40,12 @@ const ( TypeApplicationOrganization logutils.MessageDataType = "application organization" //TypeApplicationType ... TypeApplicationType logutils.MessageDataType = "application type" + //TypeAuthTypeConfig ... + TypeAuthTypeConfig logutils.MessageDataType = "auth type config" + //TypeApplicationTypeAuthConfig ... + TypeApplicationTypeAuthConfig logutils.MessageDataType = "application type auth config" + //TypeIdentityProviderSettings ... + TypeIdentityProviderSettings logutils.MessageDataType = "identity provider settings" //TypeApplicationTypeVersionList ... TypeApplicationTypeVersionList logutils.MessageDataType = "application type supported version list" //TypeApplicationUserRelations ... @@ -251,9 +257,7 @@ type ApplicationOrganization struct { ServicesIDs []string //which services are used for this app/org - IdentityProvidersSettings []IdentityProviderSetting - - SupportedAuthTypes []AuthTypesSupport //supported auth types for this organization in this application + AuthTypes map[string]SupportedAuthType //supported auth types for this organization in this application LoginsSessionsSetting LoginsSessionsSetting @@ -261,28 +265,33 @@ type ApplicationOrganization struct { DateUpdated *time.Time } -// FindIdentityProviderSetting finds the identity provider setting for the application -func (ao ApplicationOrganization) FindIdentityProviderSetting(identityProviderID string) *IdentityProviderSetting { - for _, idPrSetting := range ao.IdentityProvidersSettings { - if idPrSetting.IdentityProviderID == identityProviderID { - return &idPrSetting - } +// GetAuthTypeConfig finds the configuration for the given auth type +func (ao ApplicationOrganization) GetAuthTypeConfig(authType string) map[string]interface{} { + supportedType, exists := ao.AuthTypes[authType] + if !exists { + return nil } - return nil + return supportedType.Configs } -// IsAuthTypeSupported checks if an auth type is supported for application type -func (ao ApplicationOrganization) IsAuthTypeSupported(appType ApplicationType, authType AuthType) bool { - for _, sat := range ao.SupportedAuthTypes { - if sat.AppTypeID == appType.ID { - for _, at := range sat.SupportedAuthTypes { - if at.AuthTypeID == authType.ID { - return true - } - } - } +// GetAppTypeConfig finds the app type auth configuration for the given auth type and app type ID +func (ao ApplicationOrganization) GetAppTypeAuthConfig(authType string, appTypeID string) map[string]interface{} { + supportedType, exists := ao.AuthTypes[authType] + if !exists { + return nil } - return false + + appTypeConfig, exists := supportedType.AppTypeConfigs[appTypeID] + if !exists { + return nil + } + return appTypeConfig +} + +// IsAuthTypeSupported checks if an auth type is supported for application type +func (ao ApplicationOrganization) IsAuthTypeSupported(authType string) bool { + _, supported := ao.AuthTypes[authType] + return supported } // IdentityProviderSetting represents identity provider setting for an organization in an application @@ -296,8 +305,6 @@ func (ao ApplicationOrganization) IsAuthTypeSupported(appType ApplicationType, a // for the UIUC application the Illinois group "urn:mace:uiuc.edu:urbana:authman:app-rokwire-service-policy-rokwire groups access" is mapped to an application group called "groups access" // for the Safer Illinois application the Illinois group "urn:mace:uiuc.edu:urbana:authman:app-rokwire-service-policy-rokwire health test verify" is mapped to an application group called "tests verifiers" type IdentityProviderSetting struct { - IdentityProviderID string `bson:"identity_provider_id"` - UserIdentifierField string `bson:"user_identifier_field"` ExternalIDFields map[string]string `bson:"external_id_fields"` @@ -354,14 +361,10 @@ type ApplicationType struct { Application Application } -// AuthTypesSupport represents supported auth types for an organization in an application type with configs/params -type AuthTypesSupport struct { - AppTypeID string `bson:"app_type_id"` - - SupportedAuthTypes []struct { - AuthTypeID string `bson:"auth_type_id"` - Params map[string]interface{} `bson:"params"` - } `bson:"supported_auth_types"` +// SupportedAuthType represents a supported auth type for an application organization with configs +type SupportedAuthType struct { + Configs map[string]interface{} `bson:"configs,omitempty"` + AppTypeConfigs map[string]map[string]interface{} `bson:"app_type_configs,omitempty"` } // ApplicationConfig represents app configs diff --git a/core/model/auth.go b/core/model/auth.go index 9aeaa99a6..1030d2aa4 100644 --- a/core/model/auth.go +++ b/core/model/auth.go @@ -37,12 +37,6 @@ const ( //TypeLoginSession auth type type TypeLoginSession logutils.MessageDataType = "login session" - //TypeAuthType auth type type - TypeAuthType logutils.MessageDataType = "auth type" - //TypeIdentityProvider identity provider type - TypeIdentityProvider logutils.MessageDataType = "identity provider" - //TypeIdentityProviderConfig identity provider config type - TypeIdentityProviderConfig logutils.MessageDataType = "identity provider config" //TypeUserAuth user auth type TypeUserAuth logutils.MessageDataType = "user auth" //TypeAuthCred auth cred type @@ -83,9 +77,8 @@ const ( type LoginSession struct { ID string - AppOrg ApplicationOrganization - AuthType AuthType - AppType ApplicationType + AppOrg ApplicationOrganization + AppType ApplicationType Anonymous bool @@ -229,27 +222,16 @@ type APIKey struct { // AuthType represents authentication type entity // // The system supports different authentication types - username, email, phone, identity providers ones etc -type AuthType struct { - ID string `bson:"_id"` - Code string `bson:"code"` //username or email or phone or illinois_oidc etc - Description string `bson:"description"` - IsExternal bool `bson:"is_external"` //says if the users source is external - identity providers - IsAnonymous bool `bson:"is_anonymous"` //says if the auth type results in anonymous users - UseCredentials bool `bson:"use_credentials"` //says if the auth type uses credentials - IgnoreMFA bool `bson:"ignore_mfa"` //says if login using this auth type may bypass account MFA - Params map[string]interface{} `bson:"params"` -} - -// IdentityProvider represents identity provider entity -// -// The system can integrate different identity providers - facebook, google, illinois etc -type IdentityProvider struct { - ID string `bson:"_id"` - Name string `bson:"name"` - Type string `bson:"type"` - - Configs []IdentityProviderConfig `bson:"configs"` -} +// type AuthType struct { +// ID string `bson:"_id"` +// Code string `bson:"code"` //username or email or phone or illinois_oidc etc +// Description string `bson:"description"` +// IsExternal bool `bson:"is_external"` //says if the users source is external - identity providers +// IsAnonymous bool `bson:"is_anonymous"` //says if the auth type results in anonymous users +// UseCredentials bool `bson:"use_credentials"` //says if the auth type uses credentials +// IgnoreMFA bool `bson:"ignore_mfa"` //says if login using this auth type may bypass account MFA +// Params map[string]interface{} `bson:"params"` +// } // IdentityProviderConfig represents identity provider config for an application type type IdentityProviderConfig struct { diff --git a/core/model/user.go b/core/model/user.go index 749eb6096..3591d2498 100644 --- a/core/model/user.go +++ b/core/model/user.go @@ -88,15 +88,15 @@ func (a Account) GetAccountAuthTypeByID(ID string) *AccountAuthType { } // GetAccountAuthType finds account auth type -func (a Account) GetAccountAuthType(authTypeID string, identifier string) *AccountAuthType { - for _, aat := range a.AuthTypes { - if aat.AuthType.ID == authTypeID && aat.Identifier == identifier { - aat.Account = a - return &aat - } - } - return nil -} +// func (a Account) GetAccountAuthType(authType string, identifier string) *AccountAuthType { +// for _, aat := range a.AuthTypes { +// if aat.AuthType == authType && aat.Identifier == identifier { +// aat.Account = a +// return &aat +// } +// } +// return nil +// } // SortAccountAuthTypes sorts account auth types by matching the given uid func (a Account) SortAccountAuthTypes(uid string) { @@ -345,9 +345,8 @@ func AccountGroupsFromAppOrgGroups(items []AppOrgGroup, active bool, adminSet bo type AccountAuthType struct { ID string - AuthType AuthType //one of the supported auth type - Account Account - + Account Account + AuthType string //one of the supported auth type Identifier string Params map[string]interface{} @@ -379,7 +378,6 @@ func (aat *AccountAuthType) SetUnverified(value bool) { type Credential struct { ID string - AuthType AuthType AccountsAuthTypes []AccountAuthType //one credential can be used for more than one account auth type Verified bool Value map[string]interface{} //credential value diff --git a/driven/storage/adapter.go b/driven/storage/adapter.go index b56c1cfdc..c2c8eb2c8 100644 --- a/driven/storage/adapter.go +++ b/driven/storage/adapter.go @@ -49,9 +49,6 @@ type Adapter struct { cachedApplications *syncmap.Map applicationsLock *sync.RWMutex - cachedAuthTypes *syncmap.Map - authTypesLock *sync.RWMutex - cachedApplicationsOrganizations *syncmap.Map //cache applications organizations applicationsOrganizationsLock *sync.RWMutex @@ -89,12 +86,6 @@ func (sa *Adapter) Start() error { return errors.WrapErrorAction(logutils.ActionCache, model.TypeApplication, nil, err) } - //cache the auth types - err = sa.cacheAuthTypes() - if err != nil { - return errors.WrapErrorAction(logutils.ActionCache, model.TypeAuthType, nil, err) - } - //cache the application organization err = sa.cacheApplicationsOrganizations() if err != nil { @@ -409,86 +400,6 @@ func (sa *Adapter) getCachedApplicationType(id string) (*model.Application, *mod return nil, nil, errors.ErrorData(logutils.StatusMissing, model.TypeApplicationType, &logutils.FieldArgs{"id": id}) } -// cacheAuthTypes caches the auth types -func (sa *Adapter) cacheAuthTypes() error { - sa.logger.Info("cacheAuthTypes..") - - authTypes, err := sa.loadAuthTypes() - if err != nil { - return errors.WrapErrorAction(logutils.ActionFind, model.TypeAuthType, nil, err) - } - sa.setCachedAuthTypes(authTypes) - - return nil -} - -func (sa *Adapter) setCachedAuthTypes(authProviders []model.AuthType) { - sa.authTypesLock.Lock() - defer sa.authTypesLock.Unlock() - - sa.cachedAuthTypes = &syncmap.Map{} - validate := validator.New() - - for _, authType := range authProviders { - err := validate.Struct(authType) - if err == nil { - //we will get it by id and code as well - sa.cachedAuthTypes.Store(authType.ID, authType) - sa.cachedAuthTypes.Store(authType.Code, authType) - } else { - sa.logger.Errorf("failed to validate and cache auth type with code %s: %s", authType.Code, err.Error()) - } - } -} - -func (sa *Adapter) getCachedAuthType(key string) (*model.AuthType, error) { - sa.authTypesLock.RLock() - defer sa.authTypesLock.RUnlock() - - errArgs := &logutils.FieldArgs{"code or id": key} - - item, _ := sa.cachedAuthTypes.Load(key) - if item != nil { - authType, ok := item.(model.AuthType) - if !ok { - return nil, errors.ErrorAction(logutils.ActionCast, model.TypeAuthType, errArgs) - } - return &authType, nil - } - return nil, nil -} - -func (sa *Adapter) getCachedAuthTypes() ([]model.AuthType, error) { - sa.authTypesLock.RLock() - defer sa.authTypesLock.RUnlock() - - var err error - authTypeList := make([]model.AuthType, 0) - idsFound := make([]string, 0) - sa.cachedAuthTypes.Range(func(key, item interface{}) bool { - errArgs := &logutils.FieldArgs{"code or id": key} - if item == nil { - err = errors.ErrorData(logutils.StatusInvalid, model.TypeAuthType, errArgs) - return false - } - - authType, ok := item.(model.AuthType) - if !ok { - err = errors.ErrorAction(logutils.ActionCast, model.TypeAuthType, errArgs) - return false - } - - if !utils.Contains(idsFound, authType.ID) { - authTypeList = append(authTypeList, authType) - idsFound = append(idsFound, authType.ID) - } - - return true - }) - - return authTypeList, err -} - // cacheApplicationsOrganizations caches the applications organizations func (sa *Adapter) cacheApplicationsOrganizations() error { sa.logger.Info("cacheApplicationsOrganizations..") @@ -696,31 +607,6 @@ func (sa *Adapter) getCachedApplicationConfigByID(id string) (*model.Application return nil, errors.ErrorData(logutils.StatusMissing, model.TypeApplicationConfig, errArgs) } -// loadAuthTypes loads all auth types -func (sa *Adapter) loadAuthTypes() ([]model.AuthType, error) { - filter := bson.D{} - var result []model.AuthType - err := sa.db.authTypes.Find(filter, &result, nil) - if err != nil { - return nil, errors.WrapErrorAction(logutils.ActionFind, model.TypeAuthType, nil, err) - } - if len(result) == 0 { - return nil, errors.WrapErrorData(logutils.StatusMissing, model.TypeAuthType, nil, err) - } - - return result, nil -} - -// FindAuthType finds auth type by id or code -func (sa *Adapter) FindAuthType(codeOrID string) (*model.AuthType, error) { - return sa.getCachedAuthType(codeOrID) -} - -// FindAuthTypes finds all auth types -func (sa *Adapter) FindAuthTypes() ([]model.AuthType, error) { - return sa.getCachedAuthTypes() -} - // InsertLoginSession inserts login session func (sa *Adapter) InsertLoginSession(context TransactionContext, session model.LoginSession) error { storageLoginSession := loginSessionToStorage(session) @@ -753,15 +639,6 @@ func (sa *Adapter) FindLoginSessions(context TransactionContext, identifier stri sessions := make([]model.LoginSession, len(loginSessions)) for i, session := range loginSessions { - //auth type - from cache - authType, err := sa.getCachedAuthType(session.AuthTypeCode) - if err != nil { - return nil, errors.WrapErrorAction(logutils.ActionFind, model.TypeAuthType, &logutils.FieldArgs{"code": session.AuthTypeCode}, err) - } - if authType == nil { - return nil, errors.ErrorData(logutils.StatusMissing, model.TypeAuthType, &logutils.FieldArgs{"code": session.AuthTypeCode}) - } - //application organization - from cache appOrg, err := sa.getCachedApplicationOrganization(session.AppID, session.OrgID) if err != nil { @@ -771,7 +648,7 @@ func (sa *Adapter) FindLoginSessions(context TransactionContext, identifier stri return nil, errors.ErrorData(logutils.StatusMissing, model.TypeApplicationOrganization, &logutils.FieldArgs{"app_id": session.AppID, "org_id": session.OrgID}) } - sessions[i] = loginSessionFromStorage(session, *authType, account, *appOrg) + sessions[i] = loginSessionFromStorage(session, account, *appOrg) } return sessions, nil @@ -894,15 +771,6 @@ func (sa *Adapter) buildLoginSession(ls *loginSession) (*model.LoginSession, err } } - //auth type - from cache - authType, err := sa.getCachedAuthType(ls.AuthTypeCode) - if err != nil { - return nil, errors.WrapErrorAction(logutils.ActionFind, model.TypeAuthType, &logutils.FieldArgs{"code": ls.AuthTypeCode}, err) - } - if authType == nil { - return nil, errors.ErrorData(logutils.StatusMissing, model.TypeAuthType, &logutils.FieldArgs{"code": ls.AuthTypeCode}) - } - //application organization - from cache appOrg, err := sa.getCachedApplicationOrganization(ls.AppID, ls.OrgID) if err != nil { @@ -912,7 +780,7 @@ func (sa *Adapter) buildLoginSession(ls *loginSession) (*model.LoginSession, err return nil, errors.ErrorData(logutils.StatusMissing, model.TypeApplicationOrganization, &logutils.FieldArgs{"app_id": ls.AppID, "org_id": ls.OrgID}) } - modelLoginSession := loginSessionFromStorage(*ls, *authType, account, *appOrg) + modelLoginSession := loginSessionFromStorage(*ls, account, *appOrg) return &modelLoginSession, nil } @@ -1042,31 +910,22 @@ func (sa *Adapter) FindSessionsLazy(appID string, orgID string) ([]model.LoginSe sessions := make([]model.LoginSession, len(loginSessions)) for i, session := range loginSessions { - //auth type - from cache - authType, err := sa.getCachedAuthType(session.AuthTypeCode) - if err != nil { - return nil, errors.WrapErrorAction(logutils.ActionFind, model.TypeAuthType, &logutils.FieldArgs{"code": session.AuthTypeCode}, err) - } - if authType == nil { - return nil, errors.ErrorData(logutils.StatusMissing, model.TypeAuthType, &logutils.FieldArgs{"code": session.AuthTypeCode}) - } - //application organization - from cache appOrg, err := sa.getCachedApplicationOrganization(session.AppID, session.OrgID) if err != nil { return nil, errors.WrapErrorAction(logutils.ActionFind, model.TypeApplicationOrganization, &logutils.FieldArgs{"app_id": session.AppID, "org_id": session.OrgID}, err) } - sessions[i] = loginSessionFromStorage(session, *authType, nil, *appOrg) + sessions[i] = loginSessionFromStorage(session, nil, *appOrg) } return sessions, nil } // FindAccount finds an account for app, org, auth type and account auth type identifier -func (sa *Adapter) FindAccount(context TransactionContext, appOrgID string, authTypeID string, accountAuthTypeIdentifier string) (*model.Account, error) { +func (sa *Adapter) FindAccount(context TransactionContext, appOrgID string, authType string, accountAuthTypeIdentifier string) (*model.Account, error) { filter := bson.D{primitive.E{Key: "app_org_id", Value: appOrgID}, - primitive.E{Key: "auth_types.auth_type_id", Value: authTypeID}, + primitive.E{Key: "auth_types.auth_type_code", Value: authType}, primitive.E{Key: "auth_types.identifier", Value: accountAuthTypeIdentifier}} var accounts []account err := sa.db.accounts.FindWithContext(context, filter, &accounts, nil) @@ -1875,7 +1734,7 @@ func (sa *Adapter) DeleteAccountAuthType(context TransactionContext, item model. filter := bson.M{"_id": item.Account.ID} update := bson.D{ primitive.E{Key: "$pull", Value: bson.D{ - primitive.E{Key: "auth_types", Value: bson.M{"auth_type_code": item.AuthType.Code, "identifier": item.Identifier}}, + primitive.E{Key: "auth_types", Value: bson.M{"auth_type_code": item.AuthType, "identifier": item.Identifier}}, }}, } @@ -2595,22 +2454,6 @@ func (sa *Adapter) DeleteAPIKey(ID string) error { return nil } -// LoadIdentityProviders finds all identity providers documents in the DB -func (sa *Adapter) LoadIdentityProviders() ([]model.IdentityProvider, error) { - filter := bson.D{} - var result []model.IdentityProvider - err := sa.db.identityProviders.Find(filter, &result, nil) - if err != nil { - return nil, errors.WrapErrorAction(logutils.ActionFind, model.TypeIdentityProvider, nil, err) - } - if len(result) == 0 { - return nil, errors.WrapErrorData(logutils.StatusMissing, model.TypeIdentityProvider, nil, err) - } - - return result, nil - -} - // UpdateProfile updates a profile func (sa *Adapter) UpdateProfile(context TransactionContext, profile model.Profile) error { filter := bson.D{primitive.E{Key: "profile.id", Value: profile.ID}} @@ -2642,15 +2485,16 @@ func (sa *Adapter) UpdateProfile(context TransactionContext, profile model.Profi } // FindProfiles finds profiles by app id, authtype id and account auth type identifier -func (sa *Adapter) FindProfiles(appID string, authTypeID string, accountAuthTypeIdentifier string) ([]model.Profile, error) { +func (sa *Adapter) FindProfiles(appID string, authType string, accountAuthTypeIdentifier string) ([]model.Profile, error) { pipeline := []bson.M{ + {"$match": bson.M{"auth_types.auth_type_code": authType, "auth_types.identifier": accountAuthTypeIdentifier}}, {"$lookup": bson.M{ "from": "applications_organizations", "localField": "app_org_id", "foreignField": "_id", "as": "app_org", }}, - {"$match": bson.M{"app_org.app_id": appID, "auth_types.auth_type_id": authTypeID, "auth_types.identifier": accountAuthTypeIdentifier}}, + {"$match": bson.M{"app_org.app_id": appID}}, } var accounts []account err := sa.db.accounts.Aggregate(pipeline, &accounts, nil) @@ -3032,15 +2876,36 @@ func (sa *Adapter) FindApplicationsOrganizationsByOrgID(orgID string) ([]model.A } // InsertApplicationOrganization inserts an application organization -func (sa *Adapter) InsertApplicationOrganization(context TransactionContext, applicationOrganization model.ApplicationOrganization) (*model.ApplicationOrganization, error) { - appOrg := applicationOrganizationToStorage(applicationOrganization) +func (sa *Adapter) InsertApplicationOrganization(context TransactionContext, appOrg model.ApplicationOrganization) error { + stgAppOrg := applicationOrganizationToStorage(appOrg) - _, err := sa.db.applicationsOrganizations.InsertOneWithContext(context, appOrg) + _, err := sa.db.applicationsOrganizations.InsertOneWithContext(context, stgAppOrg) if err != nil { - return nil, errors.WrapErrorAction(logutils.ActionInsert, model.TypeApplicationOrganization, nil, err) + return errors.WrapErrorAction(logutils.ActionInsert, model.TypeApplicationOrganization, nil, err) } - return &applicationOrganization, nil + return nil +} + +// UpdateApplicationOrganization updates an application organization +func (sa *Adapter) UpdateApplicationOrganization(context TransactionContext, appOrg model.ApplicationOrganization) error { + filter := bson.D{primitive.E{Key: "app_id", Value: appOrg.Application.ID}, primitive.E{Key: "org_id", Value: appOrg.Organization.ID}} + update := bson.D{primitive.E{Key: "$set", Value: bson.D{ + primitive.E{Key: "services_ids", Value: appOrg.ServicesIDs}, + primitive.E{Key: "auth_types", Value: appOrg.AuthTypes}, + primitive.E{Key: "logins_sessions_settings", Value: appOrg.LoginsSessionsSetting}, + primitive.E{Key: "date_updated", Value: appOrg.DateUpdated}, + }}} + + res, err := sa.db.applicationsOrganizations.UpdateOneWithContext(context, filter, update, nil) + if err != nil { + return errors.WrapErrorAction(logutils.ActionInsert, model.TypeApplicationOrganization, nil, err) + } + if res.ModifiedCount != 1 { + return errors.ErrorAction(logutils.ActionUpdate, model.TypeApplicationOrganization, &logutils.FieldArgs{"id": appOrg.ID, "modified": res.ModifiedCount, "expected": 1}) + } + + return nil } // FindDevice finds a device by device id and account id @@ -3090,46 +2955,6 @@ func (sa *Adapter) InsertDevice(context TransactionContext, device model.Device) return &device, nil } -// InsertAuthType inserts an auth type -func (sa *Adapter) InsertAuthType(context TransactionContext, authType model.AuthType) (*model.AuthType, error) { - _, err := sa.db.authTypes.InsertOneWithContext(context, authType) - if err != nil { - return nil, errors.WrapErrorAction(logutils.ActionInsert, model.TypeAuthType, nil, err) - } - - return &authType, nil -} - -// UpdateAuthTypes updates an auth type -func (sa *Adapter) UpdateAuthTypes(ID string, code string, description string, isExternal bool, isAnonymous bool, - useCredentials bool, ignoreMFA bool, params map[string]interface{}) error { - - now := time.Now() - updateAuthTypeFilter := bson.D{primitive.E{Key: "_id", Value: ID}} - updateAuthType := bson.D{ - primitive.E{Key: "$set", Value: bson.D{ - primitive.E{Key: "code", Value: code}, - primitive.E{Key: "description", Value: description}, - primitive.E{Key: "is_external", Value: isExternal}, - primitive.E{Key: "is_anonymous", Value: isAnonymous}, - primitive.E{Key: "use_credentials", Value: useCredentials}, - primitive.E{Key: "ignore_mfa", Value: ignoreMFA}, - primitive.E{Key: "params", Value: params}, - primitive.E{Key: "date_updated", Value: now}, - }}, - } - - result, err := sa.db.authTypes.UpdateOne(updateAuthTypeFilter, updateAuthType, nil) - if err != nil { - return errors.WrapErrorAction(logutils.ActionUpdate, model.TypeAuthType, &logutils.FieldArgs{"id": ID}, err) - } - if result.MatchedCount == 0 { - return errors.WrapErrorData(logutils.StatusMissing, model.TypeAuthType, &logutils.FieldArgs{"id": ID}, err) - } - - return nil -} - // ============================== ServiceRegs ============================== // loadServiceRegs fetches all service registration records @@ -3308,9 +3133,6 @@ func NewStorageAdapter(mongoDBAuth string, mongoDBName string, mongoTimeout stri cachedApplications := &syncmap.Map{} applicationsLock := &sync.RWMutex{} - cachedAuthTypes := &syncmap.Map{} - authTypesLock := &sync.RWMutex{} - cachedApplicationsOrganizations := &syncmap.Map{} applicationsOrganizationsLock := &sync.RWMutex{} @@ -3318,11 +3140,9 @@ func NewStorageAdapter(mongoDBAuth string, mongoDBName string, mongoTimeout stri applicationConfigsLock := &sync.RWMutex{} db := &database{mongoDBAuth: mongoDBAuth, mongoDBName: mongoDBName, mongoTimeout: timeout, logger: logger} - return &Adapter{db: db, logger: logger, cachedServiceRegs: cachedServiceRegs, serviceRegsLock: serviceRegsLock, - cachedOrganizations: cachedOrganizations, organizationsLock: organizationsLock, - cachedApplications: cachedApplications, applicationsLock: applicationsLock, - cachedAuthTypes: cachedAuthTypes, authTypesLock: authTypesLock, - cachedApplicationsOrganizations: cachedApplicationsOrganizations, applicationsOrganizationsLock: applicationsOrganizationsLock, cachedApplicationConfigs: cachedApplicationConfigs, applicationConfigsLock: applicationConfigsLock} + return &Adapter{db: db, logger: logger, cachedServiceRegs: cachedServiceRegs, serviceRegsLock: serviceRegsLock, cachedOrganizations: cachedOrganizations, + organizationsLock: organizationsLock, cachedApplications: cachedApplications, applicationsLock: applicationsLock, cachedApplicationsOrganizations: cachedApplicationsOrganizations, + applicationsOrganizationsLock: applicationsOrganizationsLock, cachedApplicationConfigs: cachedApplicationConfigs, applicationConfigsLock: applicationConfigsLock} } type storageListener struct { @@ -3330,26 +3150,21 @@ type storageListener struct { DefaultListenerImpl } -func (sl *storageListener) OnAuthTypesUpdated() { - sl.adapter.cacheAuthTypes() -} - func (sl *storageListener) OnServiceRegsUpdated() { sl.adapter.cacheServiceRegs() } func (sl *storageListener) OnOrganizationsUpdated() { sl.adapter.cacheOrganizations() + sl.adapter.cacheApplicationsOrganizations() } func (sl *storageListener) OnApplicationsUpdated() { sl.adapter.cacheApplications() - sl.adapter.cacheOrganizations() + sl.adapter.cacheApplicationsOrganizations() } func (sl *storageListener) OnApplicationsOrganizationsUpdated() { - sl.adapter.cacheApplications() - sl.adapter.cacheOrganizations() sl.adapter.cacheApplicationsOrganizations() } @@ -3360,8 +3175,6 @@ func (sl *storageListener) OnApplicationConfigsUpdated() { // Listener represents storage listener type Listener interface { OnAPIKeysUpdated() - OnAuthTypesUpdated() - OnIdentityProvidersUpdated() OnServiceRegsUpdated() OnOrganizationsUpdated() OnApplicationsUpdated() @@ -3375,12 +3188,6 @@ type DefaultListenerImpl struct{} // OnAPIKeysUpdated notifies api keys have been updated func (d *DefaultListenerImpl) OnAPIKeysUpdated() {} -// OnAuthTypesUpdated notifies auth types have been updated -func (d *DefaultListenerImpl) OnAuthTypesUpdated() {} - -// OnIdentityProvidersUpdated notifies identity providers have been updated -func (d *DefaultListenerImpl) OnIdentityProvidersUpdated() {} - // OnServiceRegsUpdated notifies services regs have been updated func (d *DefaultListenerImpl) OnServiceRegsUpdated() {} diff --git a/driven/storage/conversions_application.go b/driven/storage/conversions_application.go index bae2f185f..8fa0f1bd1 100644 --- a/driven/storage/conversions_application.go +++ b/driven/storage/conversions_application.go @@ -252,14 +252,12 @@ func organizationToStorage(item *model.Organization) *organization { // ApplicationOrganization func applicationOrganizationToStorage(item model.ApplicationOrganization) applicationOrganization { return applicationOrganization{ID: item.ID, AppID: item.Application.ID, OrgID: item.Organization.ID, - ServicesIDs: item.ServicesIDs, IdentityProvidersSettings: item.IdentityProvidersSettings, - SupportedAuthTypes: item.SupportedAuthTypes, DateCreated: item.DateCreated, DateUpdated: item.DateUpdated} + ServicesIDs: item.ServicesIDs, AuthTypes: item.AuthTypes, DateCreated: item.DateCreated, DateUpdated: item.DateUpdated} } func applicationOrganizationFromStorage(item applicationOrganization, application model.Application, organization model.Organization) model.ApplicationOrganization { return model.ApplicationOrganization{ID: item.ID, Application: application, Organization: organization, - ServicesIDs: item.ServicesIDs, IdentityProvidersSettings: item.IdentityProvidersSettings, - SupportedAuthTypes: item.SupportedAuthTypes, LoginsSessionsSetting: item.LoginsSessionsSetting, + ServicesIDs: item.ServicesIDs, AuthTypes: item.AuthTypes, LoginsSessionsSetting: item.LoginsSessionsSetting, DateCreated: item.DateCreated, DateUpdated: item.DateUpdated} } diff --git a/driven/storage/conversions_auth.go b/driven/storage/conversions_auth.go index b3b9f7aff..c32761772 100644 --- a/driven/storage/conversions_auth.go +++ b/driven/storage/conversions_auth.go @@ -22,8 +22,7 @@ import ( ) // LoginSession -func loginSessionFromStorage(item loginSession, authType model.AuthType, account *model.Account, - appOrg model.ApplicationOrganization) model.LoginSession { +func loginSessionFromStorage(item loginSession, account *model.Account, appOrg model.ApplicationOrganization) model.LoginSession { id := item.ID appType := model.ApplicationType{ID: item.AppTypeID, Identifier: item.AppTypeIdentifier} @@ -60,10 +59,9 @@ func loginSessionFromStorage(item loginSession, authType model.AuthType, account dateUpdated := item.DateUpdated dateCreated := item.DateCreated - return model.LoginSession{ID: id, AppOrg: appOrg, AuthType: authType, AppType: appType, - Anonymous: anonymous, Identifier: identifier, ExternalIDs: externalIDs, AccountAuthType: accountAuthType, - Device: device, IPAddress: idAddress, AccessToken: accessToken, RefreshTokens: refreshTokens, Params: params, - State: state, StateExpires: stateExpires, MfaAttempts: mfaAttempts, + return model.LoginSession{ID: id, AppOrg: appOrg, AppType: appType, Anonymous: anonymous, Identifier: identifier, + ExternalIDs: externalIDs, AccountAuthType: accountAuthType, Device: device, IPAddress: idAddress, AccessToken: accessToken, + RefreshTokens: refreshTokens, Params: params, State: state, StateExpires: stateExpires, MfaAttempts: mfaAttempts, DateRefreshed: dateRefreshed, DateUpdated: dateUpdated, DateCreated: dateCreated} } @@ -73,8 +71,6 @@ func loginSessionToStorage(item model.LoginSession) *loginSession { appID := item.AppOrg.Application.ID orgID := item.AppOrg.Organization.ID - authTypeCode := item.AuthType.Code - appTypeID := item.AppType.ID appTypeIdentifier := item.AppType.Identifier @@ -111,12 +107,10 @@ func loginSessionToStorage(item model.LoginSession) *loginSession { dateUpdated := item.DateUpdated dateCreated := item.DateCreated - return &loginSession{ID: id, AppID: appID, OrgID: orgID, AuthTypeCode: authTypeCode, - AppTypeID: appTypeID, AppTypeIdentifier: appTypeIdentifier, Anonymous: anonymous, + return &loginSession{ID: id, AppID: appID, OrgID: orgID, AppTypeID: appTypeID, AppTypeIdentifier: appTypeIdentifier, Anonymous: anonymous, Identifier: identifier, ExternalIDs: externalIDs, AccountAuthTypeID: accountAuthTypeID, AccountAuthTypeIdentifier: accountAuthTypeIdentifier, - DeviceID: deviceID, IPAddress: ipAddress, AccessToken: accessToken, RefreshTokens: refreshTokens, - Params: params, State: state, StateExpires: stateExpires, MfaAttempts: mfaAttempts, - DateRefreshed: dateRefreshed, DateUpdated: dateUpdated, DateCreated: dateCreated} + DeviceID: deviceID, IPAddress: ipAddress, AccessToken: accessToken, RefreshTokens: refreshTokens, Params: params, State: state, + StateExpires: stateExpires, MfaAttempts: mfaAttempts, DateRefreshed: dateRefreshed, DateUpdated: dateUpdated, DateCreated: dateCreated} } // ServiceAccount diff --git a/driven/storage/conversions_user.go b/driven/storage/conversions_user.go index 7141299ae..cca789cb3 100644 --- a/driven/storage/conversions_user.go +++ b/driven/storage/conversions_user.go @@ -96,7 +96,6 @@ func accountDeviceToStorage(item model.Device) userDevice { // AccountAuthType func accountAuthTypeFromStorage(item accountAuthType) model.AccountAuthType { id := item.ID - authType := model.AuthType{ID: item.AuthTypeID, Code: item.AuthTypeCode} identifier := item.Identifier params := item.Params var credential *model.Credential @@ -104,7 +103,7 @@ func accountAuthTypeFromStorage(item accountAuthType) model.AccountAuthType { credential = &model.Credential{ID: *item.CredentialID} } active := item.Active - return model.AccountAuthType{ID: id, AuthType: authType, Identifier: identifier, Params: params, Credential: credential, + return model.AccountAuthType{ID: id, AuthType: item.AuthTypeCode, Identifier: identifier, Params: params, Credential: credential, Active: active, Unverified: item.Unverified, Linked: item.Linked, DateCreated: item.DateCreated, DateUpdated: item.DateUpdated} } @@ -125,8 +124,8 @@ func accountAuthTypeToStorage(item model.AccountAuthType) accountAuthType { if item.Credential != nil { credentialID = &item.Credential.ID } - return accountAuthType{ID: item.ID, AuthTypeID: item.AuthType.ID, AuthTypeCode: item.AuthType.Code, Identifier: item.Identifier, - Params: item.Params, CredentialID: credentialID, Active: item.Active, Unverified: item.Unverified, Linked: item.Linked, DateCreated: item.DateCreated, DateUpdated: item.DateUpdated} + return accountAuthType{ID: item.ID, AuthTypeCode: item.AuthType, Identifier: item.Identifier, Params: item.Params, CredentialID: credentialID, + Active: item.Active, Unverified: item.Unverified, Linked: item.Linked, DateCreated: item.DateCreated, DateUpdated: item.DateUpdated} } func accountAuthTypesToStorage(items []model.AccountAuthType) []accountAuthType { @@ -284,8 +283,7 @@ func credentialFromStorage(item credential) model.Credential { for i, id := range item.AccountsAuthTypes { accountAuthTypes[i] = model.AccountAuthType{ID: id} } - authType := model.AuthType{ID: item.AuthTypeID} - return model.Credential{ID: item.ID, AuthType: authType, AccountsAuthTypes: accountAuthTypes, Verified: item.Verified, + return model.Credential{ID: item.ID, AccountsAuthTypes: accountAuthTypes, Verified: item.Verified, Value: item.Value, DateCreated: item.DateCreated, DateUpdated: item.DateUpdated} } @@ -298,7 +296,7 @@ func credentialToStorage(item *model.Credential) *credential { for i, aat := range item.AccountsAuthTypes { accountAuthTypes[i] = aat.ID } - return &credential{ID: item.ID, AuthTypeID: item.AuthType.ID, AccountsAuthTypes: accountAuthTypes, Verified: item.Verified, + return &credential{ID: item.ID, AccountsAuthTypes: accountAuthTypes, Verified: item.Verified, Value: item.Value, DateCreated: item.DateCreated, DateUpdated: item.DateUpdated} } diff --git a/driven/storage/database.go b/driven/storage/database.go index ce118a88a..8732b4cdc 100644 --- a/driven/storage/database.go +++ b/driven/storage/database.go @@ -36,8 +36,6 @@ type database struct { dbClient *mongo.Client apiKeys *collectionWrapper - authTypes *collectionWrapper - identityProviders *collectionWrapper accounts *collectionWrapper devices *collectionWrapper credentials *collectionWrapper @@ -80,18 +78,6 @@ func (m *database) start() error { //apply checks db := client.Database(m.mongoDBName) - authTypes := &collectionWrapper{database: m, coll: db.Collection("auth_types")} - err = m.applyAuthTypesChecks(authTypes) - if err != nil { - return err - } - - identityProviders := &collectionWrapper{database: m, coll: db.Collection("identity_providers")} - err = m.applyIdentityProvidersChecks(identityProviders) - if err != nil { - return err - } - accounts := &collectionWrapper{database: m, coll: db.Collection("accounts")} err = m.applyAccountsChecks(accounts) if err != nil { @@ -192,8 +178,6 @@ func (m *database) start() error { m.db = db m.dbClient = client - m.authTypes = authTypes - m.identityProviders = identityProviders m.accounts = accounts m.devices = devices m.credentials = credentials @@ -212,8 +196,6 @@ func (m *database) start() error { m.permissions = permissions go m.apiKeys.Watch(nil, m.logger) - go m.authTypes.Watch(nil, m.logger) - go m.identityProviders.Watch(nil, m.logger) go m.serviceRegs.Watch(nil, m.logger) go m.organizations.Watch(nil, m.logger) go m.applications.Watch(nil, m.logger) @@ -225,20 +207,6 @@ func (m *database) start() error { return nil } -func (m *database) applyAuthTypesChecks(authenticationTypes *collectionWrapper) error { - m.logger.Info("apply auth types checks.....") - - m.logger.Info("auth types check passed") - return nil -} - -func (m *database) applyIdentityProvidersChecks(identityProviders *collectionWrapper) error { - m.logger.Info("apply identity providers checks.....") - - m.logger.Info("identity providers check passed") - return nil -} - func (m *database) applyAccountsChecks(accounts *collectionWrapper) error { m.logger.Info("apply accounts checks.....") @@ -280,12 +248,6 @@ func (m *database) applyDevicesChecks(devices *collectionWrapper) error { func (m *database) applyCredentialChecks(credentials *collectionWrapper) error { m.logger.Info("apply credentials checks.....") - // Add user_auth_type_id index - err := credentials.AddIndex(bson.D{primitive.E{Key: "user_auth_type_id", Value: 1}}, false) - if err != nil { - return err - } - m.logger.Info("credentials check passed") return nil } @@ -420,7 +382,7 @@ func (m *database) applyApplicationsChecks(applications *collectionWrapper) erro func (m *database) applyApplicationsOrganizationsChecks(applicationsOrganizations *collectionWrapper) error { m.logger.Info("apply applications organizations checks.....") - //add compound unique index - application + auth type + auth type identifier + //add compound unique index - application + organization err := applicationsOrganizations.AddIndex(bson.D{primitive.E{Key: "app_id", Value: 1}, primitive.E{Key: "org_id", Value: 1}}, true) @@ -542,18 +504,6 @@ func (m *database) onDataChanged(changeDoc map[string]interface{}) { for _, listener := range m.listeners { go listener.OnAPIKeysUpdated() } - case "auth_types": - m.logger.Info("auth_types collection changed") - - for _, listener := range m.listeners { - go listener.OnAuthTypesUpdated() - } - case "identity_providers": - m.logger.Info("identity_providers collection changed") - - for _, listener := range m.listeners { - go listener.OnIdentityProvidersUpdated() - } case "service_regs": m.logger.Info("service_regs collection changed") diff --git a/driven/storage/model_application.go b/driven/storage/model_application.go index e5eeadeb4..cbc283c20 100644 --- a/driven/storage/model_application.go +++ b/driven/storage/model_application.go @@ -82,9 +82,7 @@ type applicationOrganization struct { ServicesIDs []string `bson:"services_ids"` - IdentityProvidersSettings []model.IdentityProviderSetting `bson:"identity_providers_settings"` - - SupportedAuthTypes []model.AuthTypesSupport `bson:"supported_auth_types"` + AuthTypes map[string]model.SupportedAuthType `bson:"auth_types"` LoginsSessionsSetting model.LoginsSessionsSetting `bson:"logins_sessions_settings"` diff --git a/driven/storage/model_auth.go b/driven/storage/model_auth.go index c7ef90957..81ed0cfb0 100644 --- a/driven/storage/model_auth.go +++ b/driven/storage/model_auth.go @@ -25,8 +25,6 @@ type loginSession struct { AppID string `bson:"app_id"` OrgID string `bson:"org_id"` - AuthTypeCode string `bson:"auth_type_code"` - AppTypeID string `bson:"app_type_id"` AppTypeIdentifier string `bson:"app_type_identifier"` diff --git a/driven/storage/model_user.go b/driven/storage/model_user.go index 4af353836..39d3926ff 100644 --- a/driven/storage/model_user.go +++ b/driven/storage/model_user.go @@ -61,7 +61,6 @@ type accountGroup struct { type accountAuthType struct { ID string `bson:"id"` - AuthTypeID string `bson:"auth_type_id"` AuthTypeCode string `bson:"auth_type_code"` Identifier string `bson:"identifier"` Params map[string]interface{} `bson:"params"` @@ -120,7 +119,6 @@ type device struct { type credential struct { ID string `bson:"_id"` - AuthTypeID string `bson:"auth_type_id"` AccountsAuthTypes []string `bson:"account_auth_types"` Verified bool `bson:"verified"` Value map[string]interface{} `bson:"value"` diff --git a/driver/web/adapter.go b/driver/web/adapter.go index 9297dec0d..4e219fb16 100644 --- a/driver/web/adapter.go +++ b/driver/web/adapter.go @@ -241,10 +241,6 @@ func (we Adapter) Start() { systemSubrouter.HandleFunc("/api-keys", we.wrapFunc(we.systemApisHandler.createAPIKey, we.auth.system.permissions)).Methods("POST") systemSubrouter.HandleFunc("/api-keys", we.wrapFunc(we.systemApisHandler.updateAPIKey, we.auth.system.permissions)).Methods("PUT") systemSubrouter.HandleFunc("/api-keys", we.wrapFunc(we.systemApisHandler.deleteAPIKey, we.auth.system.permissions)).Methods("DELETE") - - systemSubrouter.HandleFunc("/auth-types", we.wrapFunc(we.systemApisHandler.createAuthTypes, we.auth.system.permissions)).Methods("POST") - systemSubrouter.HandleFunc("/auth-types", we.wrapFunc(we.systemApisHandler.getAuthTypes, we.auth.system.permissions)).Methods("GET") - systemSubrouter.HandleFunc("/auth-types/{id}", we.wrapFunc(we.systemApisHandler.updateAuthTypes, we.auth.system.permissions)).Methods("PUT") /// err := http.ListenAndServe(":"+we.port, router) diff --git a/driver/web/apis_system.go b/driver/web/apis_system.go index 713f56141..9cf1f86be 100644 --- a/driver/web/apis_system.go +++ b/driver/web/apis_system.go @@ -882,86 +882,6 @@ func (h SystemApisHandler) deleteApplicationConfig(l *logs.Log, r *http.Request, return l.HttpResponseSuccess() } -// createAuthTypes creates auth-type -func (h SystemApisHandler) createAuthTypes(l *logs.Log, r *http.Request, claims *tokenauth.Claims) logs.HttpResponse { - - data, err := ioutil.ReadAll(r.Body) - if err != nil { - return l.HttpResponseErrorAction(logutils.ActionRead, logutils.TypeRequestBody, nil, err, http.StatusBadRequest, false) - } - - var requestData Def.SystemReqCreateAuthType - err = json.Unmarshal(data, &requestData) - if err != nil { - return l.HttpResponseErrorAction(logutils.ActionUnmarshal, model.TypeOrganization, nil, err, http.StatusBadRequest, true) - } - - code := requestData.Code - description := requestData.Description - isExternal := requestData.IsExternal - isAnonymous := requestData.IsAnonymous - useCredentials := requestData.UseCredentials - ignoreMFA := requestData.IgnoreMfa - params := requestData.Params - - _, err = h.coreAPIs.System.SysCreateAuthTypes(code, description, isExternal, isAnonymous, useCredentials, ignoreMFA, params.AdditionalProperties) - if err != nil { - return l.HttpResponseErrorAction(logutils.ActionCreate, model.TypeAuthType, nil, err, http.StatusInternalServerError, true) - } - - return l.HttpResponseSuccess() -} - -// getAuthTypes gets auth-types -func (h SystemApisHandler) getAuthTypes(l *logs.Log, r *http.Request, claims *tokenauth.Claims) logs.HttpResponse { - authTypes, err := h.coreAPIs.System.SysGetAuthTypes() - if err != nil { - return l.HttpResponseErrorAction(logutils.ActionGet, model.TypeOrganization, nil, err, http.StatusInternalServerError, true) - } - - response := authTypesToDef(authTypes) - - data, err := json.Marshal(response) - if err != nil { - return l.HttpResponseErrorAction(logutils.ActionMarshal, model.TypeOrganization, nil, err, http.StatusInternalServerError, false) - } - return l.HttpResponseSuccessJSON(data) -} - -// updateAuthTypes updates auth type -func (h SystemApisHandler) updateAuthTypes(l *logs.Log, r *http.Request, claims *tokenauth.Claims) logs.HttpResponse { - rParams := mux.Vars(r) - ID := rParams["id"] - if len(ID) <= 0 { - return l.HttpResponseErrorData(logutils.StatusMissing, logutils.TypeQueryParam, logutils.StringArgs("id"), nil, http.StatusBadRequest, false) - } - - data, err := ioutil.ReadAll(r.Body) - if err != nil { - return l.HttpResponseErrorData(logutils.StatusInvalid, logutils.TypeRequestBody, nil, err, http.StatusBadRequest, false) - } - var requestData Def.SystemReqUpdateAuthType - err = json.Unmarshal(data, &requestData) - if err != nil { - return l.HttpResponseErrorAction(logutils.ActionUnmarshal, model.TypeOrganization, nil, err, http.StatusBadRequest, true) - } - - code := requestData.Code - description := requestData.Description - isExternal := requestData.IsExternal - isAnonymous := requestData.IsAnonymous - useCredentials := requestData.UseCredentials - ignoreMFA := requestData.IgnoreMfa - params := requestData.Params - - err = h.coreAPIs.System.SysUpdateAuthTypes(ID, code, description, isExternal, isAnonymous, useCredentials, ignoreMFA, params.AdditionalProperties) - if err != nil { - return l.HttpResponseErrorAction(logutils.ActionUpdate, model.TypeAuthType, nil, err, http.StatusInternalServerError, true) - } - - return l.HttpResponseSuccess() -} - // NewSystemApisHandler creates new system Handler instance func NewSystemApisHandler(coreAPIs *core.APIs) SystemApisHandler { return SystemApisHandler{coreAPIs: coreAPIs} diff --git a/driver/web/conversions_auth.go b/driver/web/conversions_auth.go index 425097a36..16309e41b 100644 --- a/driver/web/conversions_auth.go +++ b/driver/web/conversions_auth.go @@ -36,7 +36,7 @@ func loginSessionToDef(item model.LoginSession) Def.SharedResLoginSession { appTypeID := item.AppType.ID appTypeIdentifier := item.AppType.Identifier - authTypeCode := item.AuthType.Code + authTypeCode := item.AccountAuthType.AuthType deviceID := item.Device.ID refreshTokensCount := len(item.RefreshTokens) stateExpires := utils.FormatTime(item.StateExpires) @@ -387,22 +387,3 @@ func jsonWebKeySetDef(items *model.JSONWebKeySet) *Def.JWKS { } return &Def.JWKS{Keys: out} } - -// AuthType -func authTypeToDef(item *model.AuthType) *Def.AuthTypeFields { - if item == nil { - return nil - } - - return &Def.AuthTypeFields{Id: &item.ID, Code: &item.Code, Description: &item.Description, - IsExternal: &item.IsExternal, IsAnonymous: &item.IsAnonymous, UseCredentials: &item.UseCredentials, - IgnoreMfa: &item.IgnoreMFA, Params: &Def.AuthTypeFields_Params{AdditionalProperties: item.Params}} -} - -func authTypesToDef(items []model.AuthType) []Def.AuthTypeFields { - result := make([]Def.AuthTypeFields, len(items)) - for i, item := range items { - result[i] = *authTypeToDef(&item) - } - return result -} diff --git a/driver/web/conversions_user.go b/driver/web/conversions_user.go index 8144ab700..0a5fc4157 100644 --- a/driver/web/conversions_user.go +++ b/driver/web/conversions_user.go @@ -94,7 +94,7 @@ func accountAuthTypeToDef(item model.AccountAuthType) Def.AccountAuthTypeFields params := &Def.AccountAuthTypeFields_Params{} params.AdditionalProperties = item.Params - return Def.AccountAuthTypeFields{Id: &item.ID, Code: &item.AuthType.Code, Identifier: &item.Identifier, Active: &item.Active, Unverified: &item.Unverified, Params: params} + return Def.AccountAuthTypeFields{Id: &item.ID, Code: &item.AuthType, Identifier: &item.Identifier, Active: &item.Active, Unverified: &item.Unverified, Params: params} } func accountAuthTypesToDef(items []model.AccountAuthType) []Def.AccountAuthTypeFields { diff --git a/driver/web/docs/gen/def.yaml b/driver/web/docs/gen/def.yaml index da6736bb1..66d9689fd 100644 --- a/driver/web/docs/gen/def.yaml +++ b/driver/web/docs/gen/def.yaml @@ -4400,103 +4400,6 @@ paths: description: Unauthorized '500': description: Internal error - /system/auth-types: - get: - tags: - - System - summary: Get auth types - description: | - Gets auth types - - **Auth:** Requires system access token with `get_auth-types`, `update_auth-types`, or `all_auth-types` permission - security: - - bearerAuth: [] - responses: - '200': - description: Successful operation - content: - application/json: - schema: - type: array - items: - $ref: '#/components/schemas/AuthTypeFields' - '400': - description: Bad request - '401': - description: Unauthorized - '500': - description: Internal error - post: - tags: - - System - summary: Create auth type - description: | - Creates auth type - - **Auth:** Requires system access token with `update_auth-types` or `all_auth-types` permission - security: - - bearerAuth: [] - requestBody: - description: creates one auth-type - content: - application/json: - schema: - $ref: '#/components/schemas/_system_req_create_auth_type' - required: true - responses: - '200': - description: Success - content: - text/plain: - schema: - type: string - example: Success - '400': - description: Bad request - '401': - description: Unauthorized - '500': - description: Internal error - '/system/auth-types/{id}': - put: - tags: - - System - summary: Update auth type by ID - description: | - Updates auth type with the provided ID - - **Auth:** Requires system access token with `update_auth-types` or `all_auth-types` permission - security: - - bearerAuth: [] - parameters: - - name: id - in: path - description: ID of the auth type that needs to be updated - required: true - schema: - type: string - requestBody: - description: update one auth type - content: - application/json: - schema: - $ref: '#/components/schemas/_system_req_update_auth_type' - required: true - responses: - '200': - description: Success - content: - text/plain: - schema: - type: string - items: - $ref: '#/components/schemas/AuthTypeFields' - '400': - description: Bad request - '401': - description: Unauthorized - '500': - description: Internal error /ui/credential/reset: get: tags: @@ -4808,8 +4711,6 @@ components: $ref: '#/components/schemas/LoginSessionFields' app_org: $ref: '#/components/schemas/ApplicationOrganization' - auth_type: - $ref: '#/components/schemas/AuthType' app_type: $ref: '#/components/schemas/ApplicationType' account_auth_type: @@ -4852,36 +4753,6 @@ components: nullable: true date_created: type: string - AuthType: - type: object - properties: - fields: - $ref: '#/components/schemas/AuthTypeFields' - AuthTypeFields: - type: object - properties: - id: - type: string - code: - type: string - description: username or email or phone or illinois_oidc etc - description: - type: string - is_external: - type: boolean - description: says if the users source is external - identity providers - is_anonymous: - type: boolean - description: says if the auth type results in anonymous users - use_credentials: - type: boolean - description: says if the auth type uses credentials - ignore_mfa: - type: boolean - description: says if login using this auth type may bypass account MFA - params: - type: object - additionalProperties: true Credential: type: object properties: @@ -5248,8 +5119,6 @@ components: properties: fields: $ref: '#/components/schemas/AccountAuthTypeFields' - auth_type: - $ref: '#/components/schemas/AuthType' account: $ref: '#/components/schemas/Account' credential: diff --git a/driver/web/docs/gen/gen_types.go b/driver/web/docs/gen/gen_types.go index 41f46d89f..953b042f9 100644 --- a/driver/web/docs/gen/gen_types.go +++ b/driver/web/docs/gen/gen_types.go @@ -248,7 +248,6 @@ type Account struct { // AccountAuthType defines model for AccountAuthType. type AccountAuthType struct { Account *Account `json:"account,omitempty"` - AuthType *AuthType `json:"auth_type,omitempty"` Credential *Credential `json:"credential,omitempty"` Fields *AccountAuthTypeFields `json:"fields,omitempty"` } @@ -362,38 +361,6 @@ type AuthServiceReg struct { ServiceId string `json:"service_id"` } -// AuthType defines model for AuthType. -type AuthType struct { - Fields *AuthTypeFields `json:"fields,omitempty"` -} - -// AuthTypeFields defines model for AuthTypeFields. -type AuthTypeFields struct { - - // username or email or phone or illinois_oidc etc - Code *string `json:"code,omitempty"` - Description *string `json:"description,omitempty"` - Id *string `json:"id,omitempty"` - - // says if login using this auth type may bypass account MFA - IgnoreMfa *bool `json:"ignore_mfa,omitempty"` - - // says if the auth type results in anonymous users - IsAnonymous *bool `json:"is_anonymous,omitempty"` - - // says if the users source is external - identity providers - IsExternal *bool `json:"is_external,omitempty"` - Params *AuthTypeFields_Params `json:"params,omitempty"` - - // says if the auth type uses credentials - UseCredentials *bool `json:"use_credentials,omitempty"` -} - -// AuthTypeFields_Params defines model for AuthTypeFields.Params. -type AuthTypeFields_Params struct { - AdditionalProperties map[string]interface{} `json:"-"` -} - // Credential defines model for Credential. type Credential struct { AccountsAuthTypes *[]AccountAuthType `json:"accounts_auth_types,omitempty"` @@ -1111,22 +1078,6 @@ type SystemReqCreateApplicationConfigRequest struct { Version string `json:"version"` } -// SystemReqCreateAuthType defines model for _system_req_create_auth_type. -type SystemReqCreateAuthType struct { - Code string `json:"code"` - Description string `json:"description"` - IgnoreMfa bool `json:"ignore_mfa"` - IsAnonymous bool `json:"is_anonymous"` - IsExternal bool `json:"is_external"` - Params *SystemReqCreateAuthType_Params `json:"params,omitempty"` - UseCredentials bool `json:"use_credentials"` -} - -// SystemReqCreateAuthType_Params defines model for SystemReqCreateAuthType.Params. -type SystemReqCreateAuthType_Params struct { - AdditionalProperties map[string]interface{} `json:"-"` -} - // SystemReqCreateServiceAccount defines model for _system_req_create_service-account. type SystemReqCreateServiceAccount struct { AccountId *string `json:"account_id,omitempty"` @@ -1159,22 +1110,6 @@ type SystemReqUpdateOrganization struct { // SystemReqUpdateOrganizationType defines model for SystemReqUpdateOrganization.Type. type SystemReqUpdateOrganizationType string -// SystemReqUpdateAuthType defines model for _system_req_update_auth_type. -type SystemReqUpdateAuthType struct { - Code string `json:"code"` - Description string `json:"description"` - IgnoreMfa bool `json:"ignore_mfa"` - IsAnonymous bool `json:"is_anonymous"` - IsExternal bool `json:"is_external"` - Params *SystemReqUpdateAuthType_Params `json:"params,omitempty"` - UseCredentials bool `json:"use_credentials"` -} - -// SystemReqUpdateAuthType_Params defines model for SystemReqUpdateAuthType.Params. -type SystemReqUpdateAuthType_Params struct { - AdditionalProperties map[string]interface{} `json:"-"` -} - // SystemReqUpdateServiceAccount defines model for _system_req_update_service-account. type SystemReqUpdateServiceAccount struct { Name string `json:"name"` @@ -1512,12 +1447,6 @@ type PutSystemApplicationConfigsIdJSONBody SystemReqCreateApplicationConfigReque // PostSystemApplicationsJSONBody defines parameters for PostSystemApplications. type PostSystemApplicationsJSONBody SystemReqCreateApplication -// PostSystemAuthTypesJSONBody defines parameters for PostSystemAuthTypes. -type PostSystemAuthTypesJSONBody SystemReqCreateAuthType - -// PutSystemAuthTypesIdJSONBody defines parameters for PutSystemAuthTypesId. -type PutSystemAuthTypesIdJSONBody SystemReqUpdateAuthType - // PostSystemGlobalConfigJSONBody defines parameters for PostSystemGlobalConfig. type PostSystemGlobalConfigJSONBody GlobalConfig @@ -1821,12 +1750,6 @@ type PutSystemApplicationConfigsIdJSONRequestBody PutSystemApplicationConfigsIdJ // PostSystemApplicationsJSONRequestBody defines body for PostSystemApplications for application/json ContentType. type PostSystemApplicationsJSONRequestBody PostSystemApplicationsJSONBody -// PostSystemAuthTypesJSONRequestBody defines body for PostSystemAuthTypes for application/json ContentType. -type PostSystemAuthTypesJSONRequestBody PostSystemAuthTypesJSONBody - -// PutSystemAuthTypesIdJSONRequestBody defines body for PutSystemAuthTypesId for application/json ContentType. -type PutSystemAuthTypesIdJSONRequestBody PutSystemAuthTypesIdJSONBody - // PostSystemGlobalConfigJSONRequestBody defines body for PostSystemGlobalConfig for application/json ContentType. type PostSystemGlobalConfigJSONRequestBody PostSystemGlobalConfigJSONBody @@ -1921,162 +1844,3 @@ func (a AccountAuthTypeFields_Params) MarshalJSON() ([]byte, error) { } return json.Marshal(object) } - -// Getter for additional properties for AuthTypeFields_Params. Returns the specified -// element and whether it was found -func (a AuthTypeFields_Params) Get(fieldName string) (value interface{}, found bool) { - if a.AdditionalProperties != nil { - value, found = a.AdditionalProperties[fieldName] - } - return -} - -// Setter for additional properties for AuthTypeFields_Params -func (a *AuthTypeFields_Params) Set(fieldName string, value interface{}) { - if a.AdditionalProperties == nil { - a.AdditionalProperties = make(map[string]interface{}) - } - a.AdditionalProperties[fieldName] = value -} - -// Override default JSON handling for AuthTypeFields_Params to handle AdditionalProperties -func (a *AuthTypeFields_Params) UnmarshalJSON(b []byte) error { - object := make(map[string]json.RawMessage) - err := json.Unmarshal(b, &object) - if err != nil { - return err - } - - if len(object) != 0 { - a.AdditionalProperties = make(map[string]interface{}) - for fieldName, fieldBuf := range object { - var fieldVal interface{} - err := json.Unmarshal(fieldBuf, &fieldVal) - if err != nil { - return errors.Wrap(err, fmt.Sprintf("error unmarshaling field %s", fieldName)) - } - a.AdditionalProperties[fieldName] = fieldVal - } - } - return nil -} - -// Override default JSON handling for AuthTypeFields_Params to handle AdditionalProperties -func (a AuthTypeFields_Params) MarshalJSON() ([]byte, error) { - var err error - object := make(map[string]json.RawMessage) - - for fieldName, field := range a.AdditionalProperties { - object[fieldName], err = json.Marshal(field) - if err != nil { - return nil, errors.Wrap(err, fmt.Sprintf("error marshaling '%s'", fieldName)) - } - } - return json.Marshal(object) -} - -// Getter for additional properties for SystemReqCreateAuthType_Params. Returns the specified -// element and whether it was found -func (a SystemReqCreateAuthType_Params) Get(fieldName string) (value interface{}, found bool) { - if a.AdditionalProperties != nil { - value, found = a.AdditionalProperties[fieldName] - } - return -} - -// Setter for additional properties for SystemReqCreateAuthType_Params -func (a *SystemReqCreateAuthType_Params) Set(fieldName string, value interface{}) { - if a.AdditionalProperties == nil { - a.AdditionalProperties = make(map[string]interface{}) - } - a.AdditionalProperties[fieldName] = value -} - -// Override default JSON handling for SystemReqCreateAuthType_Params to handle AdditionalProperties -func (a *SystemReqCreateAuthType_Params) UnmarshalJSON(b []byte) error { - object := make(map[string]json.RawMessage) - err := json.Unmarshal(b, &object) - if err != nil { - return err - } - - if len(object) != 0 { - a.AdditionalProperties = make(map[string]interface{}) - for fieldName, fieldBuf := range object { - var fieldVal interface{} - err := json.Unmarshal(fieldBuf, &fieldVal) - if err != nil { - return errors.Wrap(err, fmt.Sprintf("error unmarshaling field %s", fieldName)) - } - a.AdditionalProperties[fieldName] = fieldVal - } - } - return nil -} - -// Override default JSON handling for SystemReqCreateAuthType_Params to handle AdditionalProperties -func (a SystemReqCreateAuthType_Params) MarshalJSON() ([]byte, error) { - var err error - object := make(map[string]json.RawMessage) - - for fieldName, field := range a.AdditionalProperties { - object[fieldName], err = json.Marshal(field) - if err != nil { - return nil, errors.Wrap(err, fmt.Sprintf("error marshaling '%s'", fieldName)) - } - } - return json.Marshal(object) -} - -// Getter for additional properties for SystemReqUpdateAuthType_Params. Returns the specified -// element and whether it was found -func (a SystemReqUpdateAuthType_Params) Get(fieldName string) (value interface{}, found bool) { - if a.AdditionalProperties != nil { - value, found = a.AdditionalProperties[fieldName] - } - return -} - -// Setter for additional properties for SystemReqUpdateAuthType_Params -func (a *SystemReqUpdateAuthType_Params) Set(fieldName string, value interface{}) { - if a.AdditionalProperties == nil { - a.AdditionalProperties = make(map[string]interface{}) - } - a.AdditionalProperties[fieldName] = value -} - -// Override default JSON handling for SystemReqUpdateAuthType_Params to handle AdditionalProperties -func (a *SystemReqUpdateAuthType_Params) UnmarshalJSON(b []byte) error { - object := make(map[string]json.RawMessage) - err := json.Unmarshal(b, &object) - if err != nil { - return err - } - - if len(object) != 0 { - a.AdditionalProperties = make(map[string]interface{}) - for fieldName, fieldBuf := range object { - var fieldVal interface{} - err := json.Unmarshal(fieldBuf, &fieldVal) - if err != nil { - return errors.Wrap(err, fmt.Sprintf("error unmarshaling field %s", fieldName)) - } - a.AdditionalProperties[fieldName] = fieldVal - } - } - return nil -} - -// Override default JSON handling for SystemReqUpdateAuthType_Params to handle AdditionalProperties -func (a SystemReqUpdateAuthType_Params) MarshalJSON() ([]byte, error) { - var err error - object := make(map[string]json.RawMessage) - - for fieldName, field := range a.AdditionalProperties { - object[fieldName], err = json.Marshal(field) - if err != nil { - return nil, errors.Wrap(err, fmt.Sprintf("error marshaling '%s'", fieldName)) - } - } - return json.Marshal(object) -} diff --git a/driver/web/docs/index.yaml b/driver/web/docs/index.yaml index 72309e97e..53915e32f 100644 --- a/driver/web/docs/index.yaml +++ b/driver/web/docs/index.yaml @@ -185,10 +185,6 @@ paths: $ref: "./resources/system/application-configsId.yaml" /system/api-keys: $ref: "./resources/system/api-keys.yaml" - /system/auth-types: - $ref: "./resources/system/auth-types.yaml" - /system/auth-types/{id}: - $ref: "./resources/system/auth-typesID.yaml" #ui /ui/credential/reset: diff --git a/driver/web/docs/resources/system/auth-types.yaml b/driver/web/docs/resources/system/auth-types.yaml deleted file mode 100644 index ad077cc9b..000000000 --- a/driver/web/docs/resources/system/auth-types.yaml +++ /dev/null @@ -1,56 +0,0 @@ - get: - tags: - - System - summary: Get auth types - description: | - Gets auth types - - **Auth:** Requires system access token with `get_auth-types`, `update_auth-types`, or `all_auth-types` permission - security: - - bearerAuth: [] - responses: - 200: - description: Successful operation - content: - application/json: - schema: - type: array - items: - $ref: "../../schemas/auth/AuthTypeFields.yaml" - 400: - description: Bad request - 401: - description: Unauthorized - 500: - description: Internal error - post: - tags: - - System - summary: Create auth type - description: | - Creates auth type - - **Auth:** Requires system access token with `update_auth-types` or `all_auth-types` permission - security: - - bearerAuth: [] - requestBody: - description: creates one auth-type - content: - application/json: - schema: - $ref: "../../schemas/apis/system/auth-types/request/Request.yaml" - required: true - responses: - 200: - description: Success - content: - text/plain: - schema: - type: string - example: Success - 400: - description: Bad request - 401: - description: Unauthorized - 500: - description: Internal error \ No newline at end of file diff --git a/driver/web/docs/resources/system/auth-typesID.yaml b/driver/web/docs/resources/system/auth-typesID.yaml deleted file mode 100644 index 15717912b..000000000 --- a/driver/web/docs/resources/system/auth-typesID.yaml +++ /dev/null @@ -1,39 +0,0 @@ - put: - tags: - - System - summary: Update auth type by ID - description: | - Updates auth type with the provided ID - - **Auth:** Requires system access token with `update_auth-types` or `all_auth-types` permission - security: - - bearerAuth: [] - parameters: - - name: id - in: path - description: ID of the auth type that needs to be updated - required: true - schema: - type: string - requestBody: - description: update one auth type - content: - application/json: - schema: - $ref: "../../schemas/apis/system/auth-typesID/request/Request.yaml" - required: true - responses: - 200: - description: Success - content: - text/plain: - schema: - type: string - items: - $ref: "../../schemas/auth/AuthTypeFields.yaml" - 400: - description: Bad request - 401: - description: Unauthorized - 500: - description: Internal error \ No newline at end of file diff --git a/driver/web/docs/schemas/auth/AuthType.yaml b/driver/web/docs/schemas/auth/AuthType.yaml deleted file mode 100644 index 44462e428..000000000 --- a/driver/web/docs/schemas/auth/AuthType.yaml +++ /dev/null @@ -1,4 +0,0 @@ -type: object -properties: - fields: - $ref: "./AuthTypeFields.yaml" \ No newline at end of file diff --git a/driver/web/docs/schemas/auth/AuthTypeFields.yaml b/driver/web/docs/schemas/auth/AuthTypeFields.yaml deleted file mode 100644 index 2413b486e..000000000 --- a/driver/web/docs/schemas/auth/AuthTypeFields.yaml +++ /dev/null @@ -1,24 +0,0 @@ -type: object -properties: - id: - type: string - code: - type: string - description: "username or email or phone or illinois_oidc etc" - description: - type: string - is_external: - type: boolean - description: "says if the users source is external - identity providers" - is_anonymous: - type: boolean - description: "says if the auth type results in anonymous users" - use_credentials: - type: boolean - description: "says if the auth type uses credentials" - ignore_mfa: - type: boolean - description: "says if login using this auth type may bypass account MFA" - params: - type: object - additionalProperties: true \ No newline at end of file diff --git a/driver/web/docs/schemas/auth/LoginSession.yaml b/driver/web/docs/schemas/auth/LoginSession.yaml index 720cdf1da..e4ac5009a 100644 --- a/driver/web/docs/schemas/auth/LoginSession.yaml +++ b/driver/web/docs/schemas/auth/LoginSession.yaml @@ -4,8 +4,6 @@ properties: $ref: "./LoginSessionFields.yaml" app_org: $ref: "../application/ApplicationOrganization.yaml" - auth_type: - $ref: "./AuthType.yaml" app_type: $ref: "../application/ApplicationType.yaml" account_auth_type: diff --git a/driver/web/docs/schemas/index.yaml b/driver/web/docs/schemas/index.yaml index 068626bef..393a12a53 100644 --- a/driver/web/docs/schemas/index.yaml +++ b/driver/web/docs/schemas/index.yaml @@ -35,10 +35,6 @@ LoginSession: $ref: "./auth/LoginSession.yaml" LoginSessionFields: $ref: "./auth/LoginSessionFields.yaml" -AuthType: - $ref: "./auth/AuthType.yaml" -AuthTypeFields: - $ref: "./auth/AuthTypeFields.yaml" Credential: $ref: "./auth/Credential.yaml" CredentialFields: diff --git a/driver/web/docs/schemas/user/AccountAuthType.yaml b/driver/web/docs/schemas/user/AccountAuthType.yaml index 18ff10ec4..84b8fdc18 100644 --- a/driver/web/docs/schemas/user/AccountAuthType.yaml +++ b/driver/web/docs/schemas/user/AccountAuthType.yaml @@ -2,8 +2,6 @@ type: object properties: fields: $ref: "./AccountAuthTypeFields.yaml" - auth_type: - $ref: "../auth/AuthType.yaml" account: $ref: "./Account.yaml" credential: