コード例 #1
0
 def _makeKey(self, credentialDICT):
     if 'creds' not in credentialDICT:
         raise constants.customExceptionClass(
             'creds not in credentialDICT - this means the credentials have not been enriched',
             'InvalidAuthConfigException')
     return credentialDictGet_unique_user_id(
         credentialDICT) + constants.uniqueKeyCombinator + 'facebook'
コード例 #2
0
    def userRequestTicketReissue(self, tenantName, ticketGUID, storeConnection,
                                 appObj):
        ticketObj = self.repositoryTicket.get(id=ticketGUID,
                                              storeConnection=storeConnection)
        if ticketObj is None:
            return NotFound, 404
        ticketTypeObj = self.getTicketType(
            tenantName=tenantName,
            tickettypeID=ticketObj.getDict()["typeGUID"],
            storeConnection=storeConnection)
        if ticketTypeObj is None:
            return NotFound, 404

        if ticketObj.getUsable(ticketTypeObj=ticketTypeObj) != "EXPIRED":
            raise constants.customExceptionClass(
                text="Not possible to renew this ticket", iid="notpostorenew")

        ticketObj.setReissueRequested(appObj=appObj)
        ticketObj.save(storeConnection=storeConnection)

        return {
            "ticketType": ticketTypeObj.getDict(),
            "isUsable": ticketObj.getUsable(ticketTypeObj=ticketTypeObj),
            "expiry": ticketObj.getDict()["expiry"]
        }
コード例 #3
0
    def __init__(self, dataDict, guid, tenantName, tenantObj, appObj):
        super().__init__(dataDict, guid, tenantName, tenantObj, appObj)

        if 'clientSecretJSONFile' not in dataDict['ConfigJSON']:
            raise InvalidAuthConfigException

        #Only load the static data once
        if not self.hasStaticData():
            #print('Static data not present loading')
            staticDataValue = {
                'secretJSONDownloadedFromGoogle':
                loadStaticData(dataDict['ConfigJSON']['clientSecretJSONFile']),
                #        'flow': flow_from_clientsecrets(
                #          dataDict['ConfigJSON']['clientSecretJSONFile'],
                #          scope='https://www.googleapis.com/auth/userinfo.email',
                #          redirect_uri='https://localhost'
                #        )
                #        'flow': InstalledAppFlow.from_client_secrets_file(
                #          dataDict['ConfigJSON']['clientSecretJSONFile'],
                #          scopes=['https://www.googleapis.com/auth/userinfo.email']
                #        )
            }
            self.setStaticData(staticDataValue)
            if self.getStaticData()['secretJSONDownloadedFromGoogle'] is None:
                raise constants.customExceptionClass(
                    'loadStaticData returned None',
                    'InvalidAuthConfigException')

            if "web" not in self.getStaticData(
            )['secretJSONDownloadedFromGoogle']:
                raise constants.customExceptionClass(
                    'Google secret file invliad (missing web)',
                    'InvalidAuthConfigException')
            if "client_id" not in self.getStaticData(
            )['secretJSONDownloadedFromGoogle']["web"]:
                raise constants.customExceptionClass(
                    'Google secret file invliad (missing client_id)',
                    'InvalidAuthConfigException')
コード例 #4
0
    def _executeAuthOperation_resetPassword(self, appObj, authObj,
                                            storeConnection, operationName,
                                            operationDICT):
        if (type(operationDICT["newPassword"])) is not bytes:
            operationDICT["newPassword"] = bytes(operationDICT["newPassword"],
                                                 'utf-8')

        newHashedPassword = _INT_hashPassword(
            appObj.APIAPP_MASTERPASSWORDFORPASSHASH, appObj.bcrypt,
            operationDICT["newPassword"], authObj['AuthProviderJSON']['salt'])
        if newHashedPassword == authObj['AuthProviderJSON']['password']:
            raise constants.customExceptionClass(
                'ERROR - New password matches origional', 'authopException')

        authObj['AuthProviderJSON']['password'] = newHashedPassword
        resultValue = {}
        return resultValue, authObj
コード例 #5
0
  def linkAuth(self, appObj, authProviderObj, credentialJSON, storeConnection, associatePersonWithAuthCalledWhenAuthIsCreated):
    #Different logic if this is an existing auth vs if it is new

    authDict = None
    try:
      enrichedCredentialDICT = authProviderObj.ValaditeExternalCredentialsAndEnrichCredentialDictForAuth(credentialJSON, appObj)
      authDict, objVer, creationDateTime, lastUpdateDateTime = authProviderObj.AuthReturnAll(
        appObj, enrichedCredentialDICT, storeConnection, True,
        authTPL = None, authTPLQueried = False,
        ticketObj = None, ticketTypeObj = None
      )
    except constants.customExceptionClass as err:
      if err.id=="authNotFoundException":
        pass #Auth is not found so should be created
      elif err.id=="authFailedException":
        raise constants.customExceptionClass("Invalid credentials for auth to link with", "linkAuthFailedException")
      else:
        raise err

    if authDict is None:
      return self._linkNonExistantAuth(appObj, authProviderObj, enrichedCredentialDICT, storeConnection, associatePersonWithAuthCalledWhenAuthIsCreated=associatePersonWithAuthCalledWhenAuthIsCreated)
    else:
      return self._linkExistantAuth(appObj, authDict, authProviderObj, enrichedCredentialDICT, storeConnection)
コード例 #6
0
    def __init__(self, dataDict, guid, tenantName, tenantObj, appObj):
        super().__init__(dataDict, guid, tenantName, tenantObj, appObj)

        if 'clientSecretJSONFile' not in dataDict['ConfigJSON']:
            print('ERROR - clientSecretJSONFile not in authConfig')
            raise InvalidAuthConfigException

        #Only load the static data once
        if not self.hasStaticData():
            #print('Static data not present loading')
            staticDataValue = {
                'secretJSON':
                loadStaticData(dataDict['ConfigJSON']['clientSecretJSONFile']),
            }
            self.setStaticData(staticDataValue)
            if self.getStaticData()['secretJSON'] is None:
                raise constants.customExceptionClass(
                    'loadStaticData returned None',
                    'InvalidAuthConfigException')

            if "web" not in self.getStaticData()['secretJSON']:
                raise constants.customExceptionClass(
                    'Facebook secret file invalid (missing web)',
                    'InvalidAuthConfigException')
            if "client_id" not in self.getStaticData()['secretJSON']["web"]:
                raise constants.customExceptionClass(
                    'Facebook secret file invalid (missing client_id)',
                    'InvalidAuthConfigException')
            if "client_secret" not in self.getStaticData(
            )['secretJSON']["web"]:
                raise constants.customExceptionClass(
                    'Facebook secret file invliad (missing client_id)',
                    'InvalidAuthConfigException')
            if "redirect_uri" not in self.getStaticData()['secretJSON']["web"]:
                raise constants.customExceptionClass(
                    'Facebook secret file invalid (missing redirect_uri)',
                    'InvalidAuthConfigException')
            if "auth_uri" not in self.getStaticData()['secretJSON']["web"]:
                raise constants.customExceptionClass(
                    'Facebook secret file invalid (missing auth_uri)',
                    'InvalidAuthConfigException')
コード例 #7
0
from AuthProviders.authProviders_Internal import getHashedPasswordUsingSameMethodAsJavascriptFrontendShouldUse
from tenantObj import tenantClass
import jwt
from persons import CreatePerson
from jwtTokenGeneration import generateJWTToken
from object_store_abstraction import WrongObjectVersionException
from users import CreateUser, AddUserRole, associateUserWithPerson
from userPersonCommon import getListOfUserIDsForPerson, GetUser, getListOfUserIDsForPersonNoTenantCheck
from persons import GetPerson, associatePersonWithAuthCalledWhenAuthIsCreated

failedToCreateTenantException = Exception('Failed to create Tenant')
UserIdentityWithThisNameAlreadyExistsException = Exception(
    'User Identity With This Name Already Exists')
UserAlreadyAssociatedWithThisIdentityException = Exception(
    'User Already Associated With This Identity')
UnknownUserIDException = customExceptionClass('Unknown UserID',
                                              'UnknownUserIDException')
authProviderTypeNotFoundException = customExceptionClass(
    'Auth Provider Type not found', 'authProviderTypeNotFoundException')
ticketNotUsableException = customExceptionClass('Ticket not usable',
                                                'ticketNotUsableException')


def onAppInit(appObj):
    def getAllTenantsFn(storeConnection):
        allTenants = storeConnection.getAllRowsForObjectType(
            objectType="tenants",
            filterFN=None,
            outputFN=None,
            whereClauseText=None)

    allTenants = appObj.objectStore.executeInsideConnectionContext(
コード例 #8
0
#Factory methods for gateway interface
import json

from baseapp_for_restapi_backend_with_swagger import readFromEnviroment
from gatewayInterface_none import gatewayInterfaceClass as gi_none
from gatewayInterface_kong import gatewayInterfaceClass as gi_kong
from constants import customExceptionClass

InvalidGatewayInterfaceConfigException = customExceptionClass(
    'APIAPP_GATEWAYINTERFACECONFIG value is not valid')
InvalidGatewayInterfaceTypeSpecifiedException = customExceptionClass(
    'APIAPP_GATEWAYINTERFACECONFIG invalid Type')


def getGatewayInterface(env, appObj):
    APIAPP_GATEWAYINTERFACETYPE = readFromEnviroment(
        env, 'APIAPP_GATEWAYINTERFACECONFIG', '{"Type": "none"}', None)

    gatewayInterfaceTypeConfigDict = None
    try:
        gatewayInterfaceTypeConfigDict = json.loads(
            APIAPP_GATEWAYINTERFACETYPE)
    except Exception as err:
        print("APIAPP_GATEWAYINTERFACECONFIG has invalid JSON")
        print(err)  # for the repr
        print(str(err))  # for just the message
        print(
            err.args)  # the arguments that the exception has been called with.
        raise InvalidGatewayInterfaceConfigException

    if "Type" not in gatewayInterfaceTypeConfigDict:
コード例 #9
0
        raise getInvalidEnvVarParamaterException(envVarName=envVarName, actualValue=None, messageOverride=None)

  return valueDict

import constants
import json

import logging
import sys
import APIs

import Logic

from object_store_abstraction import createObjectStoreInstance

invalidConfigurationException = constants.customExceptionClass('Invalid Configuration')

InvalidObjectStoreConfigInvalidJSONException = constants.customExceptionClass('APIAPP_OBJECTSTORECONFIG value is not valid JSON')
InvalidRedirectPrefixException = constants.customExceptionClass('APIAPP_REDIRECTPREFIX value is not valid - can not end with slash, must start with http:// or https://')

class appObjClass(parAppObj):
  objectStore = None
  APIAPP_OBJECTSTOREDETAILLOGGING = None
  APIAPP_REDIRECTPREFIX = None
  APIAPP_URLEXPIREDAYS = None
  APIAPP_DESTWHITELIST = None
  accessControlAllowOriginObj = None

  shortUrlFunctions = None

  def setupLogging(self):
コード例 #10
0
from gatewayInterface import getGatewayInterface
import uuid
import json
from refreshTokenGeneration import RefreshTokenManager
from persons import GetPerson
from userPersonCommon import GetUser
from AuthProviders.authProviders_base import resetStaticData as authProviders_resetStaticData

import autoConfigRunner as autoConfig

import logging
import sys

from apscheduler.schedulers.background import BackgroundScheduler

invalidConfigurationException = customExceptionClass('Invalid Configuration')

InvalidObjectStoreConfigInvalidJSONException = customExceptionClass(
    'APIAPP_OBJECTSTORECONFIG value is not valid JSON')


class appObjClass(parAppObj):
    objectStore = None
    APIAPP_MASTERPASSWORDFORPASSHASH = None
    APIAPP_DEFAULTHOMEADMINUSERNAME = None
    APIAPP_DEFAULTHOMEADMINPASSWORD = None
    APIAPP_JWT_TOKEN_TIMEOUT = None
    APIAPP_REFRESH_TOKEN_TIMEOUT = None
    APIAPP_REFRESH_SESSION_TIMEOUT = None
    APIAPP_DEFAULTMASTERTENANTJWTCOLLECTIONALLOWEDORIGINFIELD = None
    APIAPP_OBJECTSTOREDETAILLOGGING = None
コード例 #11
0
from constants import customExceptionClass, DefaultHasAccountRole, objectType_users_associatedPersons

from persons import GetPerson, DeletePerson
from userPersonCommon import RemoveUserAssociation, GetUser, userDosentExistException
import copy

#users_associatedPersons 1-1 with user object, seperated out to stop ObjectVersion getting out of sync when it dosen't need to

TryingToCreateDuplicateUserException = customExceptionClass(
    'That username is already in use', 'TryingToCreateDuplicateUserException')
UserAlreadyAssociatedWithThisPersonException = customExceptionClass(
    'User Already Associated With This Person',
    'UserAlreadyAssociatedWithThisPersonException')
InvalidUserIDException = customExceptionClass('That userID is not valid',
                                              'InvalidUserIDException')
InvalidKnownAsException = customExceptionClass('That knownAs is not valid',
                                               'InvalidKnownAsException')

##Creation functions
## All the functions that sets up the user, roles and asociates the user with a person


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']
コード例 #12
0
from gatewayInterface_base import gatewayInterfaceBaseClass as base
from constants import customExceptionClass

  #  kongusername = appObj.globalParamObject.LOGINEP_LDAP_CONSUMERCLIENTID_PREFIX + username
  #  appObj.kongObj.ensureUserExistsWithACL(kongusername, ldapResult['Groups'])
  #  jwtToken = appObj.kongObj.getJWTToken(kongusername)

InvalidKongGatewayInterfaceConfigException = customExceptionClass('APIAPP_GATEWAYINTERFACECONFIG value is not valid')


class gatewayInterfaceClass(base):
  kongISS = None
  def _setup(self, config):
    if 'jwtSecret' in config:
      raise Exception("ERROR jwtSecret should not be in kong gateway options")

    #Special key for kong to use
    if 'kongISS' not in config:
      print("kongISS missing from APIAPP_GATEWAYINTERFACECONFIG")
      raise InvalidKongGatewayInterfaceConfigException
    else:
      self.kongISS = config['kongISS']

  def enrichJWTClaims(self, JWTDict):
    JWTDict['kong_iss'] = self.kongISS
    return JWTDict