def patch(self, dto): assert 'headers' == ApiKeyManager.getJwtHeaders().get('some'), f"headers == {ApiKeyManager.getJwtHeaders().get('some')} should be equals. Headers: {ApiKeyManager.getJwtHeaders()}" headers={'some': 'other headers'} data = {'some': 'other data'} return { 'accessToken': ApiKeyManager.patchAccessToken(newContextList=['TEST_API_KEY', 'TEST_API_KEY_REFRESH'], headers=headers, data=data) }, HttpStatus.OK
def addFlaskApiResources( apiInstance, appInstance, controllerList, schedulerList, serviceList, clientList, repositoryList, validatorList, mapperList, helperList, converterList ) : addResourceAttibutes(apiInstance) addRepositoryTo(apiInstance, repositoryList) addSchedulerListTo(apiInstance, schedulerList) addClientListTo(apiInstance, clientList) addServiceListTo(apiInstance, serviceList) addControllerListTo(apiInstance, controllerList) addValidatorListTo(apiInstance, validatorList) addMapperListTo(apiInstance, mapperList) addHelperListTo(apiInstance, helperList) addConverterListTo(apiInstance, converterList) SqlAlchemyProxy.initialize(apiInstance, appInstance) SchedulerManager.initialize(apiInstance, appInstance) SecurityManager.initialize(apiInstance, appInstance) ApiKeyManager.initialize(apiInstance, appInstance) SessionManager.initialize(apiInstance, appInstance) OpenApiManager.addSwagger(apiInstance, appInstance)
def initialize( rootName, refferenceModel, staticPackage = 'static', viewsPackage = 'views' ) : app = Flask( rootName, static_folder = staticPackage, template_folder = viewsPackage ) api = Api(app) api.app = app api.app.api = api api.cors = CORS(app) api.cors.api = api addGlobalsTo(api) OpenApiManager.newDocumentation(api, app) SqlAlchemyProxy.addResource(api, app, baseModel=refferenceModel, echo=False) SchedulerManager.addResource(api, app) SessionManager.addResource(api, app) ApiKeyManager.addResource(api, app) SecurityManager.addResource(api, app) addFlaskApiResources(*[api, app, *[getResourceList(api, resourceType) for resourceType in FlaskManager.KW_RESOURCE_LIST]]) SessionManager.onHttpRequestCompletion(api, app) ApiKeyManager.onHttpRequestCompletion(api, app) SecurityManager.onHttpRequestCompletion(api, app) SchedulerManager.onHttpRequestCompletion(api, app) SqlAlchemyProxy.onHttpRequestCompletion(api, app) return app
def get(self): # print(ApiKeyManager.getCurrentApiKey()) assert 'other headers' == ApiKeyManager.getJwtHeaders().get('some'), f"other headers == {ApiKeyManager.getJwtHeaders().get('some')} should be equals. Headers: {ApiKeyManager.getJwtHeaders()}" return { 'secured': 'information', 'after': 'refresh', 'currentUser': ApiKeyManager.getCurrentApiKey() }, HttpStatus.OK
def apiKeyManager_worksProperly(): # arrange SECRET = 'abcd' SESSION_DURATION = 10 + 360 ALGORITHM = 'HS256' HEADER_NAME = 'Context' HEADER_TYPE = 'ApiKey ' IDENTITY = RandomHelper.string(minimum=100, maximum=150) CONTEXT = 'ABCD' CONTEXT_LIST = [CONTEXT] DATA = {'personal': 'data'} deltaMinutes = DateTimeHelper.timeDelta(minutes=SESSION_DURATION) apiKeyManager = ApiKeyManager.JwtManager(SECRET, ALGORITHM, HEADER_NAME, HEADER_TYPE) timeNow = DateTimeHelper.dateTimeNow() payload = { JwtConstant.KW_IAT: timeNow, JwtConstant.KW_NFB: timeNow, JwtConstant.KW_JTI: f"{int(f'{time.time()}'.replace('.', ''))+int(f'{time.time()}'.replace('.', ''))}", JwtConstant.KW_EXPIRATION: timeNow + deltaMinutes, JwtConstant.KW_IDENTITY: IDENTITY, JwtConstant.KW_FRESH: False, JwtConstant.KW_TYPE: JwtConstant.ACCESS_VALUE_TYPE, JwtConstant.KW_CLAIMS: { JwtConstant.KW_CONTEXT: CONTEXT_LIST, JwtConstant.KW_DATA: DATA } } # act totalRuns = 10000 lines = 3 initTime = time.time() for i in range(totalRuns): encodedPayload = apiKeyManager.encode(payload) decodedPayload = apiKeyManager.decode(encodedPayload) accessException = TestHelper.getRaisedException( apiKeyManager.validateAccessApiKey, rawJwt=decodedPayload) refreshException = TestHelper.getRaisedException( apiKeyManager.validateRefreshApiKey, rawJwt=decodedPayload) endTime = time.time() - initTime # assert assert lines * .0001 > endTime / totalRuns, (lines * .0001, endTime / totalRuns) assert ObjectHelper.equals(payload, decodedPayload), (payload, decodedPayload) assert ObjectHelper.isNone(accessException), accessException assert ObjectHelper.isNotNone(refreshException), refreshException assert ObjectHelper.equals( GlobalException.__name__, type(refreshException).__name__), (GlobalException.__name__, type(refreshException).__name__, refreshException) assert ObjectHelper.equals(401, refreshException.status) assert ObjectHelper.equals('Invalid apiKey', refreshException.message) assert ObjectHelper.equals( 'Refresh apiKey should have type refresh, but it is access', refreshException.logMessage)
def runApi(*args, api=None, **kwargs): if ObjectHelper.isNone(api): api = FlaskUtil.getApi() muteLogs(api) if 'host' not in kwargs and api.host: kwargs['host'] = api.host if not 'localhost' == api.host else '0.0.0.0' if 'port' not in kwargs and api.port: kwargs['port'] = api.port apiUrl = getApiUrl(api) documentationUrl = OpenApiManager.getDocumentationUrl(api) healthCheckUrl = f'{documentationUrl[:-len(OpenApiManager.DOCUMENTATION_ENDPOINT)]}{HealthCheckConstant.URI}' log.success(runApi, f'Api will run at {apiUrl}') log.success(runApi, f'Health check will be available at {healthCheckUrl}') log.success(runApi, f'Documentation will be available at {documentationUrl}') api.app.run(*args, **kwargs) SessionManager.onShutdown(api, api.app) ApiKeyManager.onShutdown(api, api.app) SecurityManager.onShutdown(api, api.app) SchedulerManager.onShutdown(api, api.app) SqlAlchemyProxy.onShutdown(api, api.app) log.success(runApi, f'{api.globals.apiName} successfully shutdown')
def handleLockedByApiKeyControllerMethod( args, kwargs, contentType, resourceInstance, resourceInstanceMethod, contextRequired, apiKeyRequired, requestHeaderClass, requestParamClass, requestClass, logRequest, muteStacktraceOnBusinessRuleException): contextList = ApiKeyManager.getContext() if not any(apiKey in set(contextList) for apiKey in apiKeyRequired): raise GlobalException( message='ApiKey not allowed', logMessage= f'''ApiKey {contextList} trying to access denied resourse. Allowed apiKeys {apiKeyRequired}''', status=HttpStatus.FORBIDDEN) elif ObjectHelper.isNotEmptyCollection(contextRequired): return handleSessionedControllerMethod( args, kwargs, contentType, resourceInstance, resourceInstanceMethod, contextRequired, requestHeaderClass, requestParamClass, requestClass, logRequest, muteStacktraceOnBusinessRuleException) return handleControllerMethod(args, kwargs, contentType, resourceInstance, resourceInstanceMethod, requestHeaderClass, requestParamClass, requestClass, logRequest, muteStacktraceOnBusinessRuleException)
def put(self, dto): ApiKeyManager.addAccessTokenToBlackList() return {'message': 'ApiKey closed'}, HttpStatus.ACCEPTED
def post(self, dto): headers={'some': 'headers'} data = {'some': 'data'} return { 'accessToken': ApiKeyManager.createAccessToken(dto['id'], ['TEST_API_KEY'], deltaMinutes=VALID_TOKEN_MINUTES_DURATION, headers=headers, data=data) }, HttpStatus.OK
def get(self): return { 'secured': 'information', 'currentUser': ApiKeyManager.getCurrentApiKey() }, HttpStatus.OK