Ejemplo n.º 1
0
        def someFn(connectionContext):
            masterTenant = GetTenant(masterTenantName,
                                     connectionContext,
                                     appObj=appObj)
            self.assertEqual(masterTenant.getNumberOfAuthProviders(),
                             1,
                             msg="No internal Auth Providers found")
            singleAuthProvGUID = ""
            for guid in masterTenant.getAuthProviderGUIDList():
                singleAuthProvGUID = guid

            with self.assertRaises(Exception) as context:
                UserIDandRoles = Login(
                    appObj,
                    masterTenantName,
                    singleAuthProvGUID,
                    {
                        'username':
                        env['APIAPP_DEFAULTHOMEADMINUSERNAME'],
                        'password':
                        bytes(
                            self.
                            getDefaultHashedPasswordUsingSameMethodAsJavascriptFrontendShouldUse(
                                masterTenant.getAuthProvider(
                                    singleAuthProvGUID)
                                ['saltForPasswordHashing']), 'utf-8')
                    },
                    'invalid_identity_guid',  #requestedUserID
                    connectionContext,
                    'a',
                    'b',
                    'c')
            self.checkGotRightException(context, UnknownUserIDException)
Ejemplo n.º 2
0
 def dbfn(storeConnection):
   PreviousTenantExample = {
     'Name': 'PreviousTenantExample',
     'Description': 'Master Tenant for User Management System',
     'AllowUserCreation': False,
     'AuthProviders': {
       '6b061b3e-eaf1-4653-b60f-2880a76255f2': {
         'guid': '6b061b3e-eaf1-4653-b60f-2880a76255f2',
         'MenuText': 'Website account login',
         'IconLink': None,
         'Type': 'internal',
         'AllowUserCreation': False,
         'ConfigJSON': {
           'userSufix': '@internalDataStore'
         },
         'saltForPasswordHashing': 'JDJiJDEyJGxYdGkzMlhENkxrd1lVbkx3LjF2aC4='
       }
     }
   }
   storeConnection.saveJSONObject("tenants", PreviousTenantExample['Name'], PreviousTenantExample)
   tenantObj = GetTenant(PreviousTenantExample["Name"], storeConnection, appObj=appObj)
   self.assertNotEqual(tenantObj, None, msg="Tenant Object not found")
   for x in tenantObj.getAuthProviderGUIDList():
     authProvDict = tenantObj.getAuthProvider(x)
     self.assertEqual(authProvDict['AllowLink'], False, msg="AllowLink not defaulted properly")
     self.assertEqual(authProvDict['AllowUnlink'], False, msg="AllowUnlink not defaulted properly")
     self.assertEqual(authProvDict['LinkText'], 'Link ' + authProvDict['Type'], msg="LinkText not defaulted properly")
Ejemplo n.º 3
0
        def someFn(connectionContext):
            masterTenant = GetTenant(masterTenantName,
                                     connectionContext,
                                     appObj=appObj)
            self.assertEqual(masterTenant.getNumberOfAuthProviders(),
                             1,
                             msg="No internal Auth Providers found")
            singleAuthProvGUID = ""
            for guid in masterTenant.getAuthProviderGUIDList():
                singleAuthProvGUID = guid

            with self.assertRaises(Exception) as context:
                UserIDandRoles = Login(
                    appObj,
                    masterTenantName,
                    singleAuthProvGUID,
                    {
                        'username': env['APIAPP_DEFAULTHOMEADMINUSERNAME'] +
                        'Extra bit to make username wrong',
                        'password':
                        get_APIAPP_DEFAULTHOMEADMINPASSWORD_bytes()
                    },
                    None,  #requestedUserID
                    connectionContext,
                    'a',
                    'b',
                    'c')
            self.checkGotRightExceptionType(
                context, AuthProviders.AuthNotFoundException)
Ejemplo n.º 4
0
    def dbfn(storeConnection):
      self.Issue49_putOldStyleTenantIntoStore(storeConnection)

      jsonData, objVersion, creationDateTime, lastUpdateDateTime, _ = storeConnection.getObjectJSON("tenants",constants.masterTenantName)
      tenantObj = GetTenant(randomTenantName, storeConnection, appObj=appObj)
      #print(tenantObj.getJSONRepresenation())

      self.assertEqual(tenantObj.getJWTCollectionAllowedOriginList(), [], msg="Origin list of non-master tenant incorrect")

      jsonRep = tenantObj.getJSONRepresenation()
      expectedResult = copy.deepcopy(Issue49_PreviousTenantExample)
      expectedResult["AuthProviders"] = [{
            'guid':authProvGUID,
            'MenuText': 'Website account login',
            "StaticlyLoadedData": {},
            'IconLink': None,
            'Type': 'internal',
            'AllowUserCreation': False,
            'AllowLink': False,
            'AllowUnlink': False,
            'LinkText': 'Link Website Account',
            'ConfigJSON': "{\"userSufix\": \"@internalDataStore\"}",
            'saltForPasswordHashing': 'JDJiJDEyJGxYdGkzMlhENkxrd1lVbkx3LjF2aC4='
      }]
      expectedResult["ObjectVersion"] = 1
      expectedResult["JWTCollectionAllowedOriginList"] = []
      expectedResult["TicketOverrideURL"] = ""

      keysAddedInFutureTenantStructureUpdates = ["TenantBannerHTML", "SelectAuthMessage"]
      self.assertJSONStringsEqualWithIgnoredKeys(jsonRep,expectedResult, keysAddedInFutureTenantStructureUpdates, msg="Invalid JSON representation of Object")
Ejemplo n.º 5
0
    def dbfn(storeConnection):

      PreviousTenantExample = {
        'Name': constants.masterTenantName,
        'Description': 'Master Tenant for User Management System',
        'AllowUserCreation': False,
        'AuthProviders': {
          'd366fdd2-b40d-4c12-9d91-2e11ddf9bbe7': {
            'guid': 'd366fdd2-b40d-4c12-9d91-2e11ddf9bbe7',
            'MenuText': 'Website account login',
            'IconLink': None,
            'Type': 'internal',
            'AllowUserCreation': False,
            'AllowLink': False, 'AllowUnlink': False, 'LinkText': 'Link Website Account',
            'ConfigJSON': {'userSufix': '@internalDataStore'}, 'saltForPasswordHashing': 'JDJiJDEyJGxYdGkzMlhENkxrd1lVbkx3LjF2aC4='
          }
        }
      }
      #Save old version of tenant into datastore

      def updTenant(tenant, storeConnection):
        if tenant is None:
          raise constants.tenantDosentExistException
        return PreviousTenantExample
      storeConnection.updateJSONObject("tenants", PreviousTenantExample['Name'], updTenant, 2)

      jsonData, objVersion, creationDateTime, lastUpdateDateTime, _ = storeConnection.getObjectJSON("tenants",constants.masterTenantName)
      tenantObj = GetTenant(PreviousTenantExample["Name"], storeConnection, appObj=appObj)
      #print(tenantObj.getJSONRepresenation())

      originList = list(map(lambda x: x.strip(), TestHelperSuperClass.env['APIAPP_DEFAULTMASTERTENANTJWTCOLLECTIONALLOWEDORIGINFIELD'].split(',')))

      self.assertEqual(tenantObj.getJWTCollectionAllowedOriginList(), originList, msg="Did not default master tenant origin list to default env param")
Ejemplo n.º 6
0
        def fn(storeConnection):
            tenant = GetTenant(tenantName, storeConnection, appObj=appObj)
            CreateUser(appObj, {
                "user_unique_identifier": userID,
                "known_as": userID
            }, tenantName, "test/createLoginForTenant", storeConnection)
            ##Don't know if this is needed
            ##AddUserRole(appObj, userID, tenantName, constants.DefaultHasAccountRole, storeConnection)

            person = CreatePerson(appObj, storeConnection, None, 'a', 'b', 'c')
            authProv = tenant.getSingleAuthProviderOfType(type="internal")
            if authProv is None:
                raise Exception("No internal auth prov")
            authData = AddAuth(
                appObj=appObj,
                tenantName=tenantName,
                authProviderGUID=authProv["guid"],
                credentialDICT={
                    "username":
                    InternalAuthUsername,
                    "password":
                    getHashedPasswordUsingSameMethodAsJavascriptFrontendShouldUse(
                        username=InternalAuthUsername,
                        password=InternalAuthPassword,
                        tenantAuthProvSalt=authProv["guid"])
                },
                personGUID=person['guid'],
                storeConnection=storeConnection)
            associateUserWithPerson(appObj, userID, person['guid'],
                                    storeConnection)
            return None
Ejemplo n.º 7
0
    def createTwoUsersForOnePerson(self, userID1, userID2,
                                   InternalAuthUsername, storeConnection):
        masterTenant = GetTenant(masterTenantName,
                                 storeConnection,
                                 appObj=appObj)
        CreateUser(appObj, {
            "user_unique_identifier": userID1,
            "known_as": userID1
        }, masterTenantName, "test/createTwoUsersForOnePerson",
                   storeConnection)
        CreateUser(appObj, {
            "user_unique_identifier": userID2,
            "known_as": userID2
        }, masterTenantName, "test/createTwoUsersForOnePerson",
                   storeConnection)
        authProvGUID = list(masterTenant.getAuthProviderGUIDList())[
            0]  #Just use first configured authProvider
        person = CreatePerson(appObj, storeConnection, None, 'a', 'b', 'c')
        authData = AddAuth(
            appObj, masterTenantName, authProvGUID, {
                "username": InternalAuthUsername,
                "password": get_APIAPP_DEFAULTHOMEADMINPASSWORD_bytes()
            }, person['guid'], storeConnection)
        associateUserWithPerson(appObj, userID1, person['guid'],
                                storeConnection)
        associateUserWithPerson(appObj, userID2, person['guid'],
                                storeConnection)

        return {'authProvGUID': authProvGUID, 'person': person}
def getValidTenantObj(appObj, tenant, storeConnection, validateOrigin):
    tenantObj = GetTenant(tenant, storeConnection, appObj=appObj)
    if tenantObj is None:
        raise BadRequest('Tenant not found')
    if validateOrigin:
        originHeader = request.headers.get('Origin')
        if originHeader not in tenantObj.getJWTCollectionAllowedOriginList():
            raise Unauthorized('Invalid Origin')
    return tenantObj
    def run(self, appObj, storeConnection):
        tenantObj = GetTenant(self.tenantName, storeConnection, appObj=appObj)
        if tenantObj is None:
            raise Exception("AddInternalUserAccount: Tenant " +
                            self.tenantName + " does not exist")
        authProvDict = tenantObj.getSingleAuthProviderOfType("internal")
        if authProvDict is None:
            raise Exception(
                "AddInternalUserAccount: Tenant " + self.tenantName +
                " does not have (exactly) one internal auth provider")

        CreateUser(appObj, {
            "user_unique_identifier": self.userID,
            "known_as": self.Username
        }, self.tenantName, 'autoConfigRunner/AddInternalUserAccount',
                   storeConnection)
        person = CreatePerson(appObj, storeConnection, None, 'a', 'b', 'c')
        credentialJSON = {
            "username":
            self.Username,
            "password":
            getHashedPasswordUsingSameMethodAsJavascriptFrontendShouldUse(
                appObj, self.Username, self.Password,
                authProvDict['saltForPasswordHashing'])
        }
        GetAuthProvider(appObj=appObj,
                        tenantName=self.tenantName,
                        authProviderGUID=authProvDict['guid'],
                        storeConnection=storeConnection,
                        tenantObj=tenantObj).AddAuth(
                            appObj,
                            credentialJSON,
                            person['guid'],
                            storeConnection,
                            associatePersonWithAuthCalledWhenAuthIsCreated=
                            associatePersonWithAuthCalledWhenAuthIsCreated)

        associateUserWithPerson(appObj, self.userID, person['guid'],
                                storeConnection)

        for curTenant in self.Roles:
            for curRole in self.Roles[curTenant]:
                AddUserRole(appObj, self.userID, curTenant, curRole,
                            storeConnection)

        print("AddInternalUserAccount: Add " + self.Username + " to tenant " +
              tenantObj.getName())
        self.setPassed()
Ejemplo n.º 10
0
            def dbfn(storeConnection):
                tenant = None
                if content["mainTenant"] is not None:
                    if content["mainTenant"] != "":
                        tenant = content["mainTenant"]
                        tenantObj = GetTenant(tenant,
                                              storeConnection,
                                              appObj=appObj)
                        if tenantObj is None:
                            raise BadRequest("Invalid tenant name")
                try:

                    def someFn(connectionContext):
                        CreateUser(appObj, userData, tenant,
                                   "adminapi/users/post", connectionContext)
                        return GetUser(appObj, content["UserID"],
                                       connectionContext)

                    userObj = storeConnection.executeInsideTransaction(someFn)

                except customExceptionClass as err:
                    if (err.id == 'TryingToCreateDuplicateUserException'):
                        raise BadRequest(err.text)
                    if (err.id == 'InvalidUserIDException'):
                        raise BadRequest(err.text)
                    if (err.id == 'InvalidKnownAsException'):
                        raise BadRequest(err.text)
                    raise Exception('InternalServerError')
                except:
                    raise InternalServerError

                return userObj.getJSONRepresenation(), 201
Ejemplo n.º 11
0
        def dbChangingFn(storeConnection):
            if GetTenant(masterTenantName, storeConnection,
                         appObj=self) is None:
                print("********No master tenant found - creating********")

                def someFn(connectionContext):
                    CreateMasterTenant(self, testingMode, storeConnection)

                storeConnection.executeInsideTransaction(someFn)
 def createLDAPUser(self,
                    username,
                    storeConnection,
                    authProvGUID,
                    appObj=appObj):
     masterTenant = GetTenant(constants.masterTenantName,
                              storeConnection,
                              appObj=appObj)
     CreateUser(appObj, {
         "user_unique_identifier": username,
         "known_as": username
     }, constants.masterTenantName, "test/createLDAPUser", storeConnection)
     person = CreatePerson(appObj, storeConnection, None, 'a', 'b', 'c')
     authData = AddAuth(appObj, constants.masterTenantName, authProvGUID,
                        {"username": username}, person['guid'],
                        storeConnection)
     associateUserWithPerson(appObj, username, person['guid'],
                             storeConnection)
     return {'authProvGUID': authProvGUID, 'person': person}
 def connectedFn(storeConnection):
     authProvider = GetTenant(
         authTestStep["data"]["tenantName"],
         storeConnection,
         appObj=appObj).getSingleAuthProviderOfType("internal")
     return Login(
         appObj=appObj,
         tenantName=testStep["data"]["tenantName"],
         authProviderGUID=authProvider["guid"],
         credentialJSON={
             "username":
             testStep["data"]["Username"],
             "password":
             getHashedPasswordUsingSameMethodAsJavascriptFrontendShouldUse(
                 appObj, testStep["data"]["Username"],
                 testStep["data"]["Password"],
                 authProvider['saltForPasswordHashing'])
         },
         requestedUserID=testStep["data"]["userID"],
         storeConnection=storeConnection,
         a=None,
         b=None,
         c=None)
 def runFn(storeConnection):
     return GetTenant(testStep["data"]["tenantName"],
                      storeConnection,
                      appObj=appObj)
Ejemplo n.º 15
0
        def someFn(connectionContext):
            masterTenant = GetTenant(masterTenantName,
                                     connectionContext,
                                     appObj=appObj)
            self.assertFalse(masterTenant is None,
                             msg="Master Tenant was not created")
            self.assertEquals(masterTenant.getJSONRepresenation()['Name'],
                              masterTenantName,
                              msg="Master tenant name is wrong")
            self.assertEquals(
                masterTenant.getJSONRepresenation()['Description'],
                masterTenantDefaultDescription,
                msg="Master tenant default description wrong")
            self.assertFalse(
                masterTenant.getJSONRepresenation()['AllowUserCreation'],
                msg="Master tenant defaults to allowing user creation")

            #Check AuthProvider is correct
            expectedAuthProviderJSON = {
                "guid": "ignored",
                "MenuText": masterTenantDefaultAuthProviderMenuText,
                "IconLink": masterTenantDefaultAuthProviderMenuIconLink,
                "Type": "internal",
                "AllowUserCreation": False,
                "AllowLink": False,
                "AllowUnlink": False,
                "LinkText": constants.
                masterTenantDefaultAuthProviderMenuTextInternalAuthLinkText,
                "ConfigJSON": {
                    "userSufix": "@internalDataStore"
                }
            }
            self.assertEqual(masterTenant.getNumberOfAuthProviders(),
                             1,
                             msg="No internal Auth Providers found")
            singleAuthProvGUID = ""
            for guid in masterTenant.getAuthProviderGUIDList():
                singleAuthProvGUID = guid

            self.assertJSONStringsEqualWithIgnoredKeys(
                masterTenant.getAuthProvider(singleAuthProvGUID),
                expectedAuthProviderJSON, ['guid', 'saltForPasswordHashing'],
                msg="Internal Auth Provider default data incorrect")

            #Check initial user has been created and we could log in
            UserIDandRoles = Login(
                appObj,
                masterTenantName,
                singleAuthProvGUID,
                {
                    'username':
                    env['APIAPP_DEFAULTHOMEADMINUSERNAME'],
                    'password':
                    bytes(
                        self.
                        getDefaultHashedPasswordUsingSameMethodAsJavascriptFrontendShouldUse(
                            masterTenant.getAuthProvider(singleAuthProvGUID)
                            ['saltForPasswordHashing']), 'utf-8')
                },
                None,  #requestedUserID
                connectionContext,
                'a',
                'b',
                'c')
            #An exception is raised if the login fails
            expectedRoles = {
                "UserID":
                'somerandomguid',
                "TenantRoles": {
                    "usersystem": [
                        masterTenantDefaultSystemAdminRole,
                        constants.SecurityEndpointAccessRole,
                        DefaultHasAccountRole
                    ]
                },
                "authedPersonGuid":
                "Ignore",
                "known_as":
                env['APIAPP_DEFAULTHOMEADMINUSERNAME'],
                "other_data": {
                    "createdBy": "init/CreateMasterTenant"
                },
                "currentlyUsedAuthKey":
                "AdminTestSet@internalDataStore_`@\\/'internal"
            }
            self.assertJSONStringsEqualWithIgnoredKeys(
                self.decodeToken(UserIDandRoles['jwtData']['JWTToken']),
                expectedRoles, [
                    'currentlyUsedAuthProviderGuid', 'UserID', 'exp', 'iss',
                    'authedPersonGuid', 'associatedPersons'
                ],
                msg="Returned roles incorrect")
Ejemplo n.º 16
0
        def someFn(connectionContext):
            masterTenant = GetTenant(masterTenantName,
                                     connectionContext,
                                     appObj=appObj)
            userID = 'TestUser'
            CreateUser(appObj, {
                "user_unique_identifier": userID,
                "known_as": userID
            }, masterTenantName, 'test/CreateMasterTenant', connectionContext)

            authProvGUID = list(masterTenant.getAuthProviderGUIDList())[
                0]  #Just use first configured authProvider
            person1 = CreatePerson(appObj, connectionContext, None, 'a', 'b',
                                   'c')
            person2 = CreatePerson(appObj, connectionContext, None, 'a', 'b',
                                   'c')
            InternalAuthUsername1 = 'SomeLogin1'
            InternalAuthUsername2 = 'SomeLogin2'
            authData1 = AddAuth(
                appObj, masterTenantName, authProvGUID, {
                    "username": InternalAuthUsername1,
                    "password": get_APIAPP_DEFAULTHOMEADMINPASSWORD_bytes()
                }, person1['guid'], connectionContext)
            authData2 = AddAuth(
                appObj, masterTenantName, authProvGUID, {
                    "username": InternalAuthUsername2,
                    "password": get_APIAPP_DEFAULTHOMEADMINPASSWORD_bytes()
                }, person2['guid'], connectionContext)
            associateUserWithPerson(appObj, userID, person1['guid'],
                                    connectionContext)
            associateUserWithPerson(appObj, userID, person2['guid'],
                                    connectionContext)

            #Try and log in and make sure both people get access to the user
            UserIDandRoles = Login(
                appObj, masterTenantName, authProvGUID, {
                    'username': InternalAuthUsername1,
                    'password': get_APIAPP_DEFAULTHOMEADMINPASSWORD_bytes()
                }, None, connectionContext, 'a', 'b', 'c')
            expectedJSONResponse = {
                'TenantRoles': {
                    "usersystem": [DefaultHasAccountRole]
                },
                'UserID':
                userID,
                "exp":
                "xx",
                "iss":
                userID,
                "authedPersonGuid":
                person1['guid'],
                "known_as":
                userID,
                "other_data": {
                    "createdBy": "test/CreateMasterTenant"
                },
                "currentlyUsedAuthKey":
                InternalAuthUsername1 + "@internalDataStore_`@\\/'internal"
            }
            self.assertJSONStringsEqualWithIgnoredKeys(
                self.decodeToken(UserIDandRoles['jwtData']['JWTToken']),
                expectedJSONResponse,
                ['exp', 'associatedPersons', 'currentlyUsedAuthProviderGuid'],
                msg="Failed to login to identity 1")

            UserIDandRoles = Login(
                appObj, masterTenantName, authProvGUID, {
                    'username': InternalAuthUsername2,
                    'password': get_APIAPP_DEFAULTHOMEADMINPASSWORD_bytes()
                }, None, connectionContext, 'a', 'b', 'c')
            expectedJSONResponse['authedPersonGuid'] = person2['guid']
            expectedJSONResponse[
                'currentlyUsedAuthKey'] = InternalAuthUsername2 + "@internalDataStore_`@\\/'internal"

            self.assertJSONStringsEqualWithIgnoredKeys(
                self.decodeToken(UserIDandRoles['jwtData']['JWTToken']),
                expectedJSONResponse,
                ['exp', 'associatedPersons', 'currentlyUsedAuthProviderGuid'],
                msg="Failed to login to identity 2")
Ejemplo n.º 17
0
 def dbfn(storeConnection):
     a = GetTenant(tenantName, storeConnection, appObj=appObj)
     if a is None:
         raise NotFound('Tenant Not Found')
     return a.getJSONRepresenation()