def UpdateUser(appObj, UserID, TenantRoles, known_as, other_data, objectVersion, storeConnection): userObj = GetUser(appObj, UserID, storeConnection) if userObj is None: raise userDosentExistException if str(userObj.getObjectVersion()) != str(objectVersion): raise WrongObjectVersionException internalTenantRoles = {} for ten in TenantRoles: roles = [] for rol in ten['ThisTenantRoles']: roles.append(rol) internalTenantRoles[ten['TenantName']] = roles jsonForUser = { "UserID": UserID, "TenantRoles": internalTenantRoles, "known_as": known_as, "other_data": other_data } def updUser(user, storeConnection): if user is None: raise userNotFoundException return jsonForUser storeConnection.updateJSONObject("users", UserID, updUser, objectVersion) uObj = GetUser(appObj, UserID, storeConnection) return uObj
def dbfn(storeConnection): l = getListOfUserIDsForPersonNoTenantCheck(appObj, personGUID, storeConnection) self.assertFalse(UserID in l, msg="UserPersonLink dosen't exsit but it should (1)") userObj = GetUser(appObj, UserID, storeConnection) if userObj is None: return self.assertFalse(personGUID in userObj._associatedPersonsList, msg="UserPersonLink dosen't exsit but it should (2)")
def CreateUser(appObj, userData, mainTenant, createdBy, storeConnection): #mainTenant is validated by adminAPI #print("UpdateUser createdBy:", createdBy) UserID = userData['user_unique_identifier'] if UserID is None: raise InvalidUserIDException if UserID == '': raise InvalidUserIDException KnownAs = userData['known_as'] if KnownAs is None: raise InvalidKnownAsException if KnownAs == '': raise InvalidKnownAsException OtherData = {} if "other_data" in userData: OtherData = userData['other_data'] OtherData["createdBy"] = createdBy userObj = GetUser(appObj, UserID, storeConnection) if userObj is not None: raise TryingToCreateDuplicateUserException storeConnection.saveJSONObject( "users", UserID, { "UserID": UserID, "TenantRoles": {}, "known_as": KnownAs, "other_data": OtherData }) storeConnection.saveJSONObject(objectType_users_associatedPersons, UserID, []) if mainTenant is not None: AddUserRole(appObj, UserID, mainTenant, DefaultHasAccountRole, storeConnection)
def dbfn(storeConnection): personObj = GetPerson(appObj, content["personGUID"], storeConnection) if personObj is None: raise NotFound('Person Not Found') userObj = GetUser(appObj, userID, storeConnection) if userObj is None: raise NotFound('User Not Found') try: def someFn(connectionContext): return associateUserWithPerson(appObj, content["UserID"], content["personGUID"], connectionContext) storeConnection.executeInsideTransaction(someFn) except customExceptionClass as err: if (err.id == 'UserAlreadyAssociatedWithThisPersonException'): raise BadRequest(err.text) raise Exception('InternalServerError') except: raise InternalServerError return {"UserID": userID, "personGUID": personGUID}, 201
def DeleteUser(appObj, UserID, objectVersion, storeConnection): userObj = GetUser(appObj, UserID, storeConnection) if userObj is None: raise userDosentExistException associatedPersonList, objVersion, creationDateTime, lastUpdateDateTime, _ = storeConnection.getObjectJSON( objectType_users_associatedPersons, UserID) for personGUID in associatedPersonList: RemoveUserAssociation(appObj, UserID, personGUID, DeletePerson, storeConnection) storeConnection.removeJSONObject("users", UserID, objectVersion) storeConnection.removeJSONObject(objectType_users_associatedPersons, UserID) return userObj
def RegisterUser(appObj, tenantObj, authProvGUID, credentialDICT, createdBy, storeConnection, ticketObj, ticketTypeObj): ticketAllowsUsToCreateAUser = False if ticketObj is not None: #If the ticket was for a different tenant then the ticket type would have # come back as none and that is captured in the API code if ticketObj.getUsable(ticketTypeObj=ticketTypeObj) != "USABLE": raise ticketNotUsableException ticketAllowsUsToCreateAUser = ticketTypeObj.getAllowUserCreation() if not tenantObj.getAllowUserCreation(): if not ticketAllowsUsToCreateAUser: raise userCreationNotAllowedException authProvObj = _getAuthProvider(appObj, tenantObj.getName(), authProvGUID, storeConnection, tenantObj) if not authProvObj.getAllowUserCreation(): if not ticketAllowsUsToCreateAUser: raise userCreationNotAllowedException userData = authProvObj.getTypicalAuthData(credentialDICT) CreateUser(appObj, userData, tenantObj.getName(), createdBy, storeConnection) person = CreatePerson(appObj, storeConnection, None, 'a', 'b', 'c') authData = authProvObj.AddAuth( appObj, credentialDICT, person['guid'], storeConnection, associatePersonWithAuthCalledWhenAuthIsCreated= associatePersonWithAuthCalledWhenAuthIsCreated) associateUserWithPerson(appObj, userData['user_unique_identifier'], person['guid'], storeConnection) userObj = GetUser(appObj, userData['user_unique_identifier'], storeConnection) if ticketObj is not None: #This updates the existing userObj # and saves to the database if change was made appObj.TicketManager.executeTicketForUser( appObj=appObj, userObj=userObj, ticketObj=ticketObj, ticketTypeObj=ticketTypeObj, storeConnection=storeConnection) return userObj
def CreatePersonObjFromUserDict(appObj, PersonDict, objVersion, creationDateTime, lastUpdateDateTime, storeConnection): AssociatedUserIDs = getListOfUserIDsForPersonNoTenantCheck( appObj, PersonDict['guid'], storeConnection) ##print("AAA:", AssociatedUserIDs, ":", personGUID) AssociatedUserObjs = [] for uid in AssociatedUserIDs: AssociatedUserObjs.append(GetUser(appObj, uid, storeConnection)) authKeyDICT, objVer2, creationDateTime2, lastUpdateDateTime2, _ = storeConnection.getObjectJSON( "AuthsForEachPerson", PersonDict['guid']) authObjs = [] if authKeyDICT is not None: #there are people with no auths for authKey in authKeyDICT: authObjs.append( _getAuthInfoForKeyForPersonObj(appObj, authKey, storeConnection)) personObj = personClass(PersonDict, objVersion, creationDateTime, lastUpdateDateTime, AssociatedUserObjs, authObjs) return personObj
def Login(appObj, tenantName, authProviderGUID, credentialJSON, requestedUserID, storeConnection, a, b, c, ticketObj=None, ticketTypeObj=None): def loginTrace(*args): pass #print("Login Trace - ", args) if ticketObj is not None: loginTrace("Login With a ticket") #If the ticket was for a different tenant then the ticket type would have # come back as none and that is captured in the API code if ticketObj.getUsable(ticketTypeObj=ticketTypeObj) != "USABLE": raise ticketNotUsableException else: loginTrace("Login NO ticket") loginTrace("tenants.py Login credentialJSON:", credentialJSON) tenantObj = GetTenant(tenantName, storeConnection, appObj=appObj) if tenantObj is None: raise tenantDosentExistException loginTrace("Login trace tenant FOUND") authProvider = _getAuthProvider(appObj, tenantName, authProviderGUID, storeConnection, tenantObj) loginTrace("Login trace authProvider FOUND") authUserObj = authProvider.Auth(appObj=appObj, credentialDICT=credentialJSON, storeConnection=storeConnection, supressAutocreate=False, ticketObj=ticketObj, ticketTypeObj=ticketTypeObj) if authUserObj is None: loginTrace("Login trace NO AUTH USER") raise Exception loginTrace("Login trace USER AUTH OK") #We have authed with a single authMethod, we need to get a list of identities for that provider possibleUserIDs = getListOfUserIDsForPerson(appObj, authUserObj['personGUID'], tenantName, GetUser, storeConnection) ###print("tenants.py LOGIN possibleUserIDs:",possibleUserIDs, ":", authUserObj['personGUID']) if len(possibleUserIDs) == 0: if not tenantObj.getAllowUserCreation(): raise PersonHasNoAccessToAnyIdentitiesException if not authProvider.getAllowUserCreation(): raise PersonHasNoAccessToAnyIdentitiesException if authProvider.requireRegisterCallToAutocreateUser(): raise PersonHasNoAccessToAnyIdentitiesException #print("No possible identities returned - this means there is no has account role - we should add it") #Person may have many users, but if we can create accounts for this tenant we can add the account to all users # and give the person logging in a choice #We don't do a tenant check because all it's doing is restricting the returned users to users who already have a hasaccount role userIDList = getListOfUserIDsForPersonNoTenantCheck( appObj, authUserObj['personGUID'], storeConnection) for curUserID in userIDList: AddUserRole(appObj, curUserID, tenantName, constants.DefaultHasAccountRole, storeConnection) possibleUserIDs = getListOfUserIDsForPerson(appObj, authUserObj['personGUID'], tenantName, GetUser, storeConnection) if len(possibleUserIDs) == 0: #This should never happen as we just added the has account role raise PersonHasNoAccessToAnyIdentitiesException if requestedUserID is None: if len(possibleUserIDs) == 1: requestedUserID = possibleUserIDs[0] else: #mutiple userids supplied return { 'possibleUserIDs': possibleUserIDs, 'possibleUsers': None, 'jwtData': None, 'refresh': None, 'userGuid': None, 'authedPersonGuid': None, 'ThisTenantRoles': None, 'known_as': None, 'other_data': None, 'currentlyUsedAuthProviderGuid': None } if requestedUserID not in possibleUserIDs: print('requestedUserID:', requestedUserID) raise UnknownUserIDException userObj = GetUser(appObj, requestedUserID, storeConnection) if userObj is None: raise Exception('Error userObj not found') if ticketObj is not None: #This updates the existing userObj # and saves to the database if change was made appObj.TicketManager.executeTicketForUser( appObj=appObj, userObj=userObj, ticketObj=ticketObj, ticketTypeObj=ticketTypeObj, storeConnection=storeConnection) currentAuthUserKey = authUserObj['AuthUserKey'] authedPersonGuid = authUserObj['personGUID'] authProviderGuid = authProvider.guid resDict = getLoginResult(appObj=appObj, userObj=userObj, authedPersonGuid=authedPersonGuid, currentAuthUserKey=currentAuthUserKey, authProviderGuid=authProviderGuid, tenantName=tenantName, restrictRolesTo=[]) return resDict
def someFn(connectionContext): return GetPerson(appObj, decodedJWTToken.getPersonID(), connectionContext), GetUser( appObj, decodedJWTToken.getUserID(), connectionContext)
def dbfn(storeConnection): tenantObj = getValidTenantObj(appObj, tenant, storeConnection, validateOrigin=True) authProviderGUID = content['authProviderGUID'] UserID = None if content['UserID'] is not None: UserID = content['UserID'] ticketObj = None ticketTypeObj = None if content['ticket'] is not None: ticketObj = appObj.TicketManager.getTicketObj( ticketGUID=content['ticket'], storeConnection=storeConnection) if ticketObj is None: raise BadRequest('Invalid Ticket') ticketTypeObj = appObj.TicketManager.getTicketType( tenantName=tenant, tickettypeID=ticketObj.getDict()["typeGUID"], storeConnection=storeConnection) if ticketTypeObj is None: return BadRequest('Invalid Ticket') try: #print("APIlogin_Legacy.py login - authProviderGUID:",authProviderGUID) def someFn(connectionContext): return Login(appObj, tenant, authProviderGUID, content['credentialJSON'], UserID, connectionContext, 'a', 'b', 'c', ticketObj=ticketObj, ticketTypeObj=ticketTypeObj) loginResult = storeConnection.executeInsideTransaction( someFn) except constants.customExceptionClass as err: if (err.id == 'authFailedException'): raise Unauthorized(err.text) if (err.id == 'PersonHasNoAccessToAnyIdentitiesException'): raise Unauthorized(err.text) if (err.id == 'authProviderNotFoundException'): raise BadRequest(err.text) if (err.id == 'UnknownUserIDException'): raise BadRequest(err.text) if (err.id == 'ExternalAuthProviderNotReachableException'): print(err.text) raise Exception(err.text) if (err.id == 'ticketNotUsableException'): raise BadRequest(err.text) if (err.id == 'authNotFoundException'): raise Unauthorized(err.text) if (err.id == 'userCreationNotAllowedException'): raise Unauthorized(err.text) raise Exception('InternalServerError') except AuthProviders.CustomAuthProviderExceptionClass as err: if (err.id == 'InvalidAuthConfigException'): #import traceback #traceback.print_exc() raise Unauthorized(err.text) if (err.id == 'authNotFoundException'): raise Unauthorized(err.text) if (err.id == 'InvalidAuthCredentialsException'): raise BadRequest(err.text) if (err.id == 'MissingAuthCredentialsException'): raise BadRequest(err.text) raise Exception('InternalServerError') except AuthProviders.AuthNotFoundException as err: raise Unauthorized(err.text) except: raise InternalServerError returnDict = copy.deepcopy(loginResult) if returnDict['possibleUserIDs'] is not None: #populate possibleUsers from possibleUserIDs possibleUsers = [] for userID in returnDict['possibleUserIDs']: possibleUsers.append( GetUser( appObj, userID, storeConnection).getJSONRepresenation(tenant) ) #limit roles to only current tenant returnDict['possibleUsers'] = possibleUsers del returnDict["other_data"] return returnDict
def dbfn(storeConnection): userObj = GetUser(appObj, userID, storeConnection) if userObj is None: raise NotFound('User Not Found') return userObj.getJSONRepresenation()
def someFn(connectionContext): CreateUser(appObj, userData, tenant, "adminapi/users/post", connectionContext) return GetUser(appObj, content["UserID"], connectionContext)