def setUp(self): self.service1 = BaseService("MusterService", ["fileStorage"], FileTransferMode.active, FileTransferArchive.none) self.service2 = BaseService("BetonService", ["fileStorage"], FileTransferMode.active, FileTransferArchive.none) self.service3 = BaseService("FahrService", ["fileStorage"], FileTransferMode.active, FileTransferArchive.none) self.oauthservice1 = OAuth2Service.from_service( self.service1, "http://localhost:5000/oauth/authorize", "http://localhost:5000/oauth/refresh", "ABC", "XYZ", ) self.oauthservice2 = OAuth2Service.from_service( self.service2, "http://localhost:5001/oauth/authorize", "http://localhost:5001/oauth/refresh", "DEF", "UVW", ) self.oauthservice3 = OAuth2Service.from_service( self.service3, "http://localhost:5001/api/authorize", "http://localhost:5001/api/refresh", "GHI", "MNO", )
def test_serviceprojects_add(self): proj1 = {"projectId": 0, "metadata": {}} proj2 = {"projectId": 1, "metadata": {}} userId = "admin" servicename = "port-zenodo" expected_project = proj1 pact.given("one searched token was registered.").upon_receiving( "a request to get a specific token for service from user." ).with_request( "GET", f"/user/{userId}/token/{servicename}").will_respond_with( 200, body=json.dumps( Token( User(userId), BaseService(servicename=servicename, implements=["metadata"]), "ABC"))) pact.given("service with project support").upon_receiving( "try to create a project").with_request( "POST", f"/metadata/project").will_respond_with(200, body=expected_project) with pact: code = self.client.post( "/port-service/user/{}/service/{}/projects".format( userId, servicename)).status_code self.assertEqual(code, 200) pact.given("one searched token was registered.").upon_receiving( "a request to get a specific token for service from user." ).with_request( "GET", f"/user/{userId}/token/{servicename}").will_respond_with( 200, body=json.dumps( Token( User(userId), BaseService(servicename=servicename, implements=["metadata"]), "ABC"))) pact.given("Given token to access port").upon_receiving( "invalid request").with_request( "POST", "/metadata/project").will_respond_with(500, body="") with pact: code = self.client.post( "/port-service/user/{}/service/{}/projects".format( userId, servicename)).status_code self.assertEqual(code, 500)
def test_serviceprojects_delete(self): proj1 = {"projectId": 0, "metadata": {}} userId = "admin" servicename = "port-zenodo" pact.given("one searched token was registered.").upon_receiving( "a request to get a specific token for service from user." ).with_request( "GET", f"/user/{userId}/token/{servicename}").will_respond_with( 200, body=json.dumps( Token( User(userId), BaseService(servicename=servicename, implements=["metadata"]), "ABC"))) pact.given("Given token to access port").upon_receiving( "try to delete {}".format(proj1["projectId"])).with_request( "DELETE", "/metadata/project/{}".format( proj1["projectId"])).will_respond_with(404, body="") with pact: code = self.client.delete( "/port-service/user/{}/service/{}/projects/{}".format( userId, servicename, proj1["projectId"])).status_code self.assertGreaterEqual(code, 404) pact.given("one searched token was registered.").upon_receiving( "a request to get a specific token for service from user." ).with_request( "GET", f"/user/{userId}/token/{servicename}").will_respond_with( 200, body=json.dumps( Token( User(userId), BaseService(servicename=servicename, implements=["metadata"]), "ABC"))) pact.given("Given token to access port").upon_receiving( "a call to delete {}".format(proj1["projectId"])).with_request( "DELETE", "/metadata/project/{}".format( proj1["projectId"])).will_respond_with(204, body="") with pact: code = self.client.delete( "/port-service/user/{}/service/{}/projects/{}".format( userId, servicename, proj1["projectId"])).status_code self.assertEqual(code, 204)
def test_service_give_description(self): text = "This is a test description." svc1 = BaseService("MusterService", ["fileStorage"], FileTransferMode.active, FileTransferArchive.none, text) self.assertEqual(svc1.description, text) self.assertNotEqual(svc1.description, "This is not valid.") self.assertEqual(svc1.to_dict().get("description"), text) self.assertEqual( BaseService.from_dict(svc1.to_dict()).description, text) self.assertEqual( BaseService.from_json(svc1.to_json()).description, text) svc1 = OAuth2Service("MusterService", ["fileStorage"], FileTransferMode.active, FileTransferArchive.none, "http://localhost:5001", "http://localhost:5001/oauth/refresh", "ABC", "XYZ", text) self.assertEqual(svc1.description, text) svc1 = LoginService("Service", ["fileStorage"], FileTransferMode.active, FileTransferArchive.none, False, False, text) self.assertEqual(svc1.description, text)
def get(servicename: str): servicename = servicename.lower() svc = utility.storage.getService(servicename) if svc is not None: return jsonify(svc) raise ServiceNotExistsError(BaseService(servicename=servicename))
def refreshService(self, service: Union[str, BaseService]) -> bool: try: servicename = service.servicename except: servicename = service response = requests.get( f"{self.address}/service/{servicename}", verify=(os.environ.get("VERIFY_SSL", "True") == "True"), ) if response.status_code != 200: try: raise ServiceNotFoundError(service) except: raise ServiceNotFoundError( BaseService(servicename=servicename, implements=["metadata"])) svc = Util.getServiceObject(response.json()) if not svc in self._services: self._services.append(svc) return svc
def test_compare_service(self): s1 = BaseService("MusterService", ["fileStorage"], FileTransferMode.active, FileTransferArchive.none) s2 = BaseService("MusterService", ["metadata"], FileTransferMode.passive, FileTransferArchive.zip) s3 = BaseService("FahrService", ["fileStorage"], FileTransferMode.active, FileTransferArchive.none) os1 = OAuth2Service.from_service( s1, "http://localhost:5000/oauth/authorize", "http://localhost:5000/oauth/refresh", "ABC", "XYZ", ) os2 = OAuth2Service.from_service( s2, "http://localhost:5000/oauth/authorize", "http://localhost:5000/oauth/refresh", "ABC", "XYZ", ) os3 = OAuth2Service.from_service( s3, "http://localhost123:5000/oauth/authorize", "http://localhost123:5000/oauth/refresh", "WER", "DA", ) os4 = OAuth2Service.from_service( s1, "http://localhost:5000/oauth/authorize", "http://localhost:5000/oauth/refresh", "QWE", "RTZ", ) self.assertEqual(s1, s2) self.assertNotEqual(s1, s3) self.assertFalse(s1 is s2) self.assertEqual(os1, os2) self.assertEqual(os1, os4) self.assertNotEqual(os1, os3) self.assertEqual(s1, os1)
def getInformations(self, svc: BaseService) -> dict: informations = svc.to_dict() try: del informations["client_secret"] except: pass return informations
def get(user_id, servicename): servicename = servicename.lower() if not servicename.startswith("port-"): servicename = "port-{}".format(servicename) return jsonify( Util.tokenService.getTokenForServiceFromUser( BaseService(servicename=servicename, implements=["metadata"]), User(user_id)))
def test_token_service_init(self): user1 = User("Max Mustermann") service1 = BaseService("MusterService", ["fileStorage"]) service2 = LoginService("BetonService", ["fileStorage"], userId=True, password=False) LoginToken(user1, service2, "") with self.assertRaises(ValueError): Token(user1, service1, "")
def delete(user_id, servicename): servicename = servicename.lower() if not servicename.startswith("port-"): servicename = "port-{}".format(servicename) return jsonify({ "success": Util.tokenService.removeTokenForServiceFromUser( BaseService(servicename=servicename, implements=["metadata"]), User(user_id)) })
def delete(user_id, servicename, projects_id): servicename = servicename.lower() if not servicename.startswith("port-"): servicename = "port-{}".format(servicename) if Util.tokenService.removeProjectForUserInService( User(user_id), BaseService(servicename=servicename, implements=["metadata"]), projects_id): return None, 204 abort(404)
def post(user_id, servicename): servicename = servicename.lower() if not servicename.startswith("port-"): servicename = "port-{}".format(servicename) projectId, project = Util.tokenService.createProjectForUserInService( User(user_id), BaseService(servicename=servicename, implements=["metadata"])) resp = {"projectId": str(projectId)} logger.debug("sent: {}".format(resp)) return jsonify(resp)
def getService(self, service: Union[str, BaseService]): """ Returns the service object with the given servicename. If not found, returns None This function can be used to check, if an object is already a member of the list of services. Set parameter `index` to True to get the index as the second return value in tuple. """ if not isinstance(service, (str, BaseService)): raise ValueError("given parameter not string or service.") if not isinstance(service, (BaseService)): service = BaseService(servicename=service, implements=["metadata"]) try: services = self.services _, svc = self.internal_find_service(service.servicename, services, return_object=True) return svc except: return None
def test_exchange_code(self): code = "XYZABC" service = OAuth2Service( servicename="localhost", implements=["metadata"], authorize_url=f"{self.tokenService.address}/authorize", refresh_url=f"{self.tokenService.address}/oauth2/token", client_id="ABC", client_secret="XYZ", ) with self.assertRaises(ValueError): self.tokenService.exchangeAuthCodeToAccessToken( code, BaseService(servicename="localhost", implements=["metadata"]), self.user1.username) body = { "access_token": "1vtnuo1NkIsbndAjVnhl7y0wJha59JyaAiFIVQDvcBY2uvKmj5EPBEhss0pauzdQ", "token_type": "Bearer", "expires_in": 3600, "refresh_token": "7y0wJuvKmj5E1vjVnhlPBEhha59JyaAiFIVQDvcBY2ss0pauzdQtnuo1NkIsbndA", "user_id": self.user1.username, "message_url": "https://www.example.org/owncloud/index.php/apps/oauth2/authorization-successful", } # need pact for exchange for code pact.given("Client ID and secret was registered.").upon_receiving( "A request to exchange the given auth code to get access token and refresh token." ).with_request("POST", f"/oauth2/token").will_respond_with(200, body=body) expected = OAuth2Token( self.user1, service, body["access_token"], body["refresh_token"], datetime.now() + timedelta(seconds=body["expires_in"]), ) # need pact for save the access and refresh token in Token Storage pact.given("No token was registered for user").upon_receiving( "A request to add an oauthtoken.").with_request( "POST", f"/user/{self.user1.username}/token").will_respond_with( 200, body={"success": True}) token = self.tokenService.exchangeAuthCodeToAccessToken( code, service, self.user1.username) self.assertEqual(token, expected) # test for service object # need pact for exchange for code pact.given("Client ID and secret was registered.").upon_receiving( "A request to exchange the given auth code to get access token and refresh token with service object." ).with_request("POST", f"/oauth2/token").will_respond_with(200, body=body) # need pact for save the access and refresh token in Token Storage pact.given("No token was registered for user").upon_receiving( "A request to add an oauthtoken with service object." ).with_request("POST", f"/user/{self.user1.username}/token").will_respond_with( 200, body={"success": True}) token = self.tokenService.exchangeAuthCodeToAccessToken( code, service, self.user1.username) self.assertEqual(token, expected) # test serviceNotFoundError pact.given("no oauthservice was registered.").upon_receiving( "A request to get a oauthservice.").with_request( "GET", f"/service/{service.servicename}").will_respond_with( 500, body={ "error": "ServiceNotExistsError", "http_code": 500 }) with self.assertRaises(ServiceNotFoundError): self.tokenService.exchangeAuthCodeToAccessToken( code, service.servicename, self.user1.username) self.tokenService._storage = {} # test CodeNotExchangeableError pact.given("An oauthservice was registered.").upon_receiving( "A request to get this oauthservice for exchange code." ).with_request("GET", f"/service/{service.servicename}").will_respond_with( 200, body=json.dumps(service)) # need pact for exchange for code pact.given("Client ID and secret was not registered.").upon_receiving( "A request to exchange the given auth code to get access token and refresh token." ).with_request("POST", f"/oauth2/token").will_respond_with( 500, body={"error": "Login not successful"}) with self.assertRaises(CodeNotExchangeable): self.tokenService.exchangeAuthCodeToAccessToken( code, service.servicename, self.user1.username)