Exemple #1
0
    def setUp(self):
        self.tokenService = TokenService(testing="http://localhost:3000")

        self.url1 = "https://10.14.29.60/owncloud/index.php/apps/oauth2/authorize?response_type=code&client_id={}&redirect_uri={}".format(
            1, "http://localhost:8080")
        self.url2 = "http://zenodo.org/oauth/authorize?response_type=code&client_id={}&redirect_uri={}".format(
            2, "http://localhost:8080")

        self.servicename1 = "owncloud-local"
        self.servicename2 = "sandbox.zenodo.org"

        self.user1 = User("user")
        self.user2 = User("user_refresh")

        self.service1 = OAuth2Service(
            servicename=self.servicename1,
            implements=["fileStorage"],
            authorize_url=self.url1,
            refresh_url=
            "https://10.14.29.60/owncloud/index.php/apps/oauth2/api/v1/token",
            client_id="ABC",
            client_secret="XYZ",
        )

        self.service2 = OAuth2Service(
            servicename=self.servicename2,
            implements=["metadata"],
            authorize_url=self.url2,
            refresh_url="https://sandbox.zenodo.org/oauth/token",
            client_id="DEF",
            client_secret="UVW",
        )

        self.token1 = Token(self.user1, self.service1, "ABC")
        self.token2 = OAuth2Token(self.user1, self.service2, "ABC", "XYZ")
    def test_service_trailing_slash(self):
        # check if root dir is valid
        svc1 = OAuth2Service(
            "MusterService",
            ["fileStorage"],
            FileTransferMode.active,
            FileTransferArchive.none,
            "http://localhost:5001",
            "http://localhost:5001/oauth/refresh",
            "ABC",
            "XYZ",
        )
        self.assertIsInstance(svc1, OAuth2Service)

        svc2 = OAuth2Service(
            "MusterService",
            ["fileStorage"],
            FileTransferMode.active,
            FileTransferArchive.none,
            "http://localhost:5001/",
            "http://localhost:5001/oauth/refresh/",
            "ABC",
            "XYZ",
        )
        self.assertIsInstance(svc2, OAuth2Service)

        # check if they are equal
        self.assertEqual(svc1,
                         svc2,
                         msg=f"Service1: {svc1}\n Service2: {svc2}")
    def setUp(self):
        self.user1 = User("Max Mustermann")
        self.user2 = User("12345")

        self.service1 = LoginService("MusterService", ["fileStorage"])
        self.service2 = LoginService("BetonService", ["fileStorage"])

        self.token1 = Token(self.user1, self.service1, "ABC")
        self.token2 = Token(self.user1, self.service2, "DEF")

        self.oauthservice1 = OAuth2Service(
            "MusterService",
            ["fileStorage"],
            FileTransferMode.active,
            FileTransferArchive.none,
            "http://localhost/oauth/authorize",
            "http://localhost/oauth/token",
            "MNO",
            "UVW",
        )
        self.oauthservice2 = OAuth2Service(
            "BetonService",
            ["fileStorage"],
            FileTransferMode.active,
            FileTransferArchive.none,
            "http://owncloud/oauth/authorize",
            "http://owncloud/oauth/token",
            "UVP",
            "OMN",
        )

        self.oauthtoken1 = OAuth2Token(self.user1, self.oauthservice1, "ABC",
                                       "XYZ")
        self.oauthtoken2 = OAuth2Token(self.user1, self.oauthservice2, "DEF",
                                       "UVW")
    def test_service_equal(self):
        # check if they are equal
        svc1 = OAuth2Service(
            "MusterService",
            ["fileStorage"],
            FileTransferMode.active,
            FileTransferArchive.none,
            "http://localhost:5001",
            "http://localhost:5001/oauth/refresh",
            "ABC",
            "XYZ",
        )
        svc2 = OAuth2Service(
            "MusterService",
            ["fileStorage"],
            FileTransferMode.active,
            FileTransferArchive.none,
            "http://localhost:5001",
            "http://localhost:5001/oauth/refresh",
            "ABC",
            "XYZ",
        )
        self.assertEqual(svc1,
                         svc2,
                         msg=f"Service1: {svc1}\n Service2: {svc2}")

        svc2 = OAuth2Service(
            "musterservice",
            ["fileStorage"],
            FileTransferMode.active,
            FileTransferArchive.none,
            "http://localhost:5001",
            "http://localhost:5001/oauth/refresh",
            "ABC",
            "XYZ",
        )
        self.assertEqual(svc1,
                         svc2,
                         msg=f"Service1: {svc1}\n Service2: {svc2}")

        svc2 = OAuth2Service(
            "musterService",
            ["fileStorage"],
            FileTransferMode.active,
            FileTransferArchive.none,
            "http://localhost:5001",
            "http://localhost:5001/oauth/refresh",
            "ABC",
            "XYZ",
        )
        self.assertEqual(svc1,
                         svc2,
                         msg=f"Service1: {svc1}\n Service2: {svc2}")
 def test_service_no_protocoll(self):
     # no protocoll
     with self.assertRaises(ValueError):
         OAuth2Service(
             "MusterService",
             ["fileStorage"],
             FileTransferMode.active,
             FileTransferArchive.none,
             "localhost",
             "http://localhost:5001/oauth/refresh",
             "ABC",
             "XYZ",
         )
         OAuth2Service(
             "MusterService",
             ["fileStorage"],
             FileTransferMode.active,
             FileTransferArchive.none,
             "localhost:5001",
             "http://localhost:5001/oauth/authorize",
             "ABC",
             "XYZ",
         )
         OAuth2Service(
             "MusterService",
             ["fileStorage"],
             FileTransferMode.active,
             FileTransferArchive.none,
             "localhost:5001/oauth/authorize",
             "http://localhost:5001/oauth/refresh",
             "ABC",
             "XYZ",
         )
         OAuth2Service(
             "MusterService",
             ["fileStorage"],
             FileTransferMode.active,
             FileTransferArchive.none,
             "http://localhost:5001",
             "localhost:5001/oauth/refresh",
             "ABC",
             "XYZ",
         )
         OAuth2Service(
             "MusterService",
             ["fileStorage"],
             FileTransferMode.active,
             FileTransferArchive.none,
             "http://localhost:5001",
             "localhost:5001/oauth/authorize",
             "ABC",
             "XYZ",
         )
Exemple #6
0
        def setUp(self):

            Util.monkeypatch()
            self.empty_storage = Storage(**get_opts())

            self.user1 = User("Max Mustermann")
            self.user2 = User("Mimi Mimikri")

            self.service1 = LoginService(servicename="MusterService",
                                         implements=["metadata"])
            self.service2 = LoginService(servicename="FahrService",
                                         implements=["metadata"])
            self.oauthservice1 = OAuth2Service(
                servicename="BetonService",
                implements=["metadata"],
                authorize_url="http://localhost/oauth/authorize",
                refresh_url="http://localhost/oauth/token",
                client_id="MNO",
                client_secret="UVW",
            )
            self.oauthservice2 = OAuth2Service(
                servicename="FlugService",
                implements=["metadata"],
                authorize_url="http://localhost21/oauth/authorize",
                refresh_url="http://localhost21/oauth/token",
                client_id="XCA",
                client_secret="BCXY",
            )

            self.empty_storage.addService(self.service1)
            self.empty_storage.addService(self.oauthservice1)
            self.empty_storage.addService(self.oauthservice2)

            self.token1 = Token(self.user1, self.service1, "ABC")
            self.token_like_token1 = Token(self.user1, self.service1, "DEF")
            self.token2 = Token(self.user1, self.oauthservice1, "XYZ")
            self.token3 = Token(self.user2, self.service2, "XASD")
            self.token4 = Token(self.user2, self.service1, "IOAJSD")

            self.oauthtoken1 = OAuth2Token(self.user1, self.oauthservice1,
                                           "ABC", "X_ABC")
            self.oauthtoken_like_token1 = OAuth2Token(self.user1,
                                                      self.oauthservice1,
                                                      "ABC", "X_DEF")
            self.oauthtoken2 = OAuth2Token(self.user1, self.oauthservice1,
                                           "XYZ", "X_XYZ")

            self.oauthtoken3 = OAuth2Token(self.user1, self.oauthservice2,
                                           "XYZ", "X_XYZ")
    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)
Exemple #8
0
 def setUp(self):
     self.user1 = User("MaxMustermann")
     self.service1 = OAuth2Service(
         servicename="TestService",
         implements=["metadata"],
         authorize_url="http://localhost/oauth/authorize",
         refresh_url="http://localhost/oauth/token",
         client_id="MNO",
         client_secret="UVW")
     self.token1 = OAuth2Token(self.user1, self.service1, "ABC", "X_ABC")
Exemple #9
0
    def setUp(self):
        global pact
        pact = Consumer('UseCaseMetadataProject').has_pact_with(
            Provider('PortMetadata'), port=3000)

        self.app = create_app()
        self.client = self.app.test_client()

        self.user1 = User("MaxMustermann")
        self.service1 = OAuth2Service(
            servicename="TestService",
            implements=["metadata"],
            authorize_url="http://localhost/oauth/authorize",
            refresh_url="http://localhost/oauth/token",
            client_id="MNO",
            client_secret="UVW")
        self.token1 = OAuth2Token(self.user1, self.service1, "ABC", "X_ABC")
    def test_service_check_raises(self):
        svc1 = OAuth2Service(
            "MusterService",
            ["fileStorage"],
            FileTransferMode.active,
            FileTransferArchive.none,
            "http://localhost:5001",
            "http://localhost:5001/oauth/refresh",
            "ABC",
            "XYZ",
        )

        from RDS import User, Token, OAuth2Token

        with self.assertRaises(ValueError):
            svc1.refresh(Token(User("Max Mustermann"), svc1, "ABC"))
            svc1.refresh("asd")
            svc1.refresh(123)
Exemple #11
0
    def test_redirect(self):
        code = "XYZABC"
        user = User("user")
        service = OAuth2Service(
            servicename="port-local",
            implements=["metadata"],
            authorize_url=f"{Util.tokenService.address}/oauth/authorize",
            refresh_url=f"{Util.tokenService.address}/oauth/token",
            client_id="ABC",
            client_secret="XYZ",
        )

        body = {
            "access_token":
            "1vtnuo1NkIsbndAjVnhl7y0wJha59JyaAiFIVQDvcBY2uvKmj5EPBEhss0pauzdQ",
            "token_type":
            "Bearer",
            "expires_in":
            3600,
            "refresh_token":
            "7y0wJuvKmj5E1vjVnhlPBEhha59JyaAiFIVQDvcBY2ss0pauzdQtnuo1NkIsbndA",
            "user_id":
            user.username,
            "message_url":
            "https://www.example.org/owncloud/index.php/apps/oauth2/authorization-successful",
        }

        # test returned state jwt object
        pact.given("An oauthservice was registered.").upon_receiving(
            "A request to get this oauthservice.").with_request(
                "GET", f"/service/{service.servicename}").will_respond_with(
                    200, body=service.to_json())

        with pact:
            response = self.client.get(
                f"/port-service/service/{service.servicename}")
        self.assertEqual(response.status_code,
                         200,
                         msg=response.get_data(as_text=True))

        # ignore signature
        resp_state = jwt.decode(response.json["jwt"],
                                "secret",
                                algorithms="HS256",
                                options={"verify_signature": False})
        logger.info(resp_state)

        self.assertEqual(resp_state["servicename"], service.servicename)
        self.assertEqual(resp_state["authorize_url"], service.authorize_url)

        date = resp_state["date"]

        # following request should not be needed a new pact, because its cached and date shuld be the same.
        response = self.client.get(
            f"/port-service/service/{service.servicename}")
        self.assertEqual(response.status_code,
                         200,
                         msg=response.get_data(as_text=True))

        # ignore signature
        resp_state = jwt.decode(response.json["jwt"],
                                "secret",
                                algorithms="HS256",
                                options={"verify_signature": False})
        logger.info(resp_state)

        self.assertEqual(resp_state["servicename"], service.servicename)
        self.assertEqual(resp_state["authorize_url"], service.authorize_url)

        key = Util.tokenService.secret

        data = {
            "servicename": service.servicename,
            "authorize_url": service.authorize_url,
            "date": str(datetime.datetime.now()),
        }
        import base64
        import json

        stateReal = jwt.encode(data, key, algorithm="HS256")
        state = base64.b64encode(
            json.dumps({
                "jwt": stateReal,
                "user": user.username
            }).encode("utf-8"))

        pluginDict = {
            "servicename": service.servicename,
            "state": stateReal,
            "userId": user.username,
            "code": code,
        }
        jwtEncode = jwt.encode(pluginDict,
                               service.client_secret,
                               algorithm="HS256")

        # 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"/oauth/token").will_respond_with(200,
                                                                  body=body)

        # currently not needed
        # expected = OAuth2Token(user, service, body["access_token"], body["refresh_token"], datetime.datetime.now(
        # ) + datetime.timedelta(seconds=body["expires_in"]))

        # need pact for save the access and refresh token in Token Storage
        pact.given(
            "No token was registered for not registered user").upon_receiving(
                "A request to add an oauthtoken.").with_request(
                    "POST", f"/user/{user.username}/token").will_respond_with(
                        201, body={"success": True})

        with pact:
            response = self.client.post("/port-service/exchange",
                                        json={"jwt": jwtEncode})

        self.assertEqual(response.status_code, 204, msg=response.get_data())
Exemple #12
0
    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)
Exemple #13
0
    owncloud_installation_url
)
owncloud_oauth_id = os.getenv("OWNCLOUD_OAUTH_CLIENT_ID", "XY")
owncloud_oauth_secret = os.getenv("OWNCLOUD_OAUTH_CLIENT_SECRET", "ABC")

owncloud_oauth_authorize = "{}/index.php/apps/oauth2/authorize%3Fredirect_uri={}&response_type=code&client_id={}".format(
    owncloud_installation_url, owncloud_redirect_uri, owncloud_oauth_id
)

service = OAuth2Service(
    servicename="port-owncloud",
    implements=["fileStorage"],
    fileTransferMode=FileTransferMode.active,
    fileTransferArchive=FileTransferArchive.none,
    authorize_url=owncloud_oauth_authorize,
    refresh_url=owncloud_oauth_token_url,
    client_id=owncloud_oauth_id,
    client_secret=owncloud_oauth_secret,
    description={"en": "ownCloud is a suite of client–server software for creating and using file hosting services.",
                 "de": "ownCloud ist eine Suite von Client-Server-Software zur Erstellung und Nutzung von File-Hosting-Diensten."},
    displayName="ownCloud",
    infoUrl="https://owncloud.com/",
    helpUrl="https://owncloud.com/docs-guides/",
    icon="./owncloud.svg"
)
Util.register_service(service)

# set the WSGI application callable to allow using uWSGI:
# uwsgi --http :8080 -w app
app.run(port=8080, server="gevent")
Exemple #14
0
zenodo_address = os.getenv("ZENODO_ADDRESS", "https://sandbox.zenodo.org")
zenodo_oauth_token_url = "{}/oauth/token".format(zenodo_address)
zenodo_oauth_id = os.getenv("ZENODO_OAUTH_CLIENT_ID", "XY")
zenodo_oauth_secret = os.getenv("ZENODO_OAUTH_CLIENT_SECRET", "ABC")

zenodo_oauth_authorize = "{}/oauth/authorize%3Fredirect_uri={}&response_type=code&scope%3Ddeposit%3Awrite%20deposit%3Aactions&client_id={}".format(
    zenodo_address, redirect_uri, zenodo_oauth_id
)

service = OAuth2Service(
    servicename="port-zenodo",
    implements=["metadata"],
    fileTransferMode=FileTransferMode.active,
    fileTransferArchive=FileTransferArchive.zip,
    authorize_url=zenodo_oauth_authorize,
    refresh_url=zenodo_oauth_token_url,
    client_id=zenodo_oauth_id,
    client_secret=zenodo_oauth_secret,
    description={"en": "Zenodo is a general-purpose open-access repository developed under the European OpenAIRE program and operated by CERN. It allows researchers to deposit and publish data sets, research software, reports, and any other research related digital artifacts.",
                 "de": "Zenodo ist ein universelles Open-Access-Repository, das im Rahmen des europäischen OpenAIRE-Programms entwickelt und vom CERN betrieben wird. Es ermöglicht Forschern, Datensätze, Forschungssoftware, Berichte und alle anderen forschungsbezogenen digitalen Artefakte zu hinterlegen und zu veröffentlichen."},
    displayName="Zenodo",
    infoUrl="https://about.zenodo.org/",
    helpUrl="https://help.zenodo.org/",
    icon="./zenodo.svg"
)
Util.register_service(service)

# set the WSGI application callable to allow using uWSGI:
# uwsgi --http :8080 -w app
app.run(port=8080, server='gevent')
    def test_service(self):
        with self.assertRaises(ValueError):
            LoginService("", [], FileTransferMode.active,
                         FileTransferArchive.none, "", "")

        with self.assertRaises(ValueError):
            LoginService("Service", [], 3, "", False, False)

        with self.assertRaises(ValueError):
            LoginService("Service", ["not_working"], FileTransferMode.active,
                         FileTransferArchive.none, False, False)

        with self.assertRaises(ValueError):
            LoginService("Service")

        LoginService("Service", ["fileStorage"])
        LoginService("Service", ["fileStorage"], FileTransferMode.active)
        LoginService("Service", ["fileStorage"], FileTransferMode.active,
                     FileTransferArchive.none)
        LoginService("Service", ["fileStorage"], FileTransferMode.active,
                     FileTransferArchive.none, False)
        LoginService("Service", ["fileStorage"], FileTransferMode.active,
                     FileTransferArchive.none, True, False)
        LoginService("Service", ["fileStorage"], FileTransferMode.active,
                     FileTransferArchive.none, False, False)

        with self.assertRaises(ValueError):
            OAuth2Service("", ["fileStorage"], FileTransferMode.active,
                          FileTransferArchive.none, "", "", "", "")
            with self.assertRaises(ValueError):
                OAuth2Service("MusterService", ["fileStorage"],
                              FileTransferMode.active,
                              FileTransferArchive.none, "", "", "", "")
            with self.assertRaises(ValueError):
                OAuth2Service("", ["fileStorage"], FileTransferMode.active,
                              FileTransferArchive.none,
                              "http://localhost:5001/oauth/authorize", "", "",
                              "")
            with self.assertRaises(ValueError):
                OAuth2Service("", ["fileStorage"], FileTransferMode.active,
                              FileTransferArchive.none, "",
                              "http://localhost:5001/oauth/refresh", "", "")
            with self.assertRaises(ValueError):
                OAuth2Service("", ["fileStorage"], FileTransferMode.active,
                              FileTransferArchive.none, "", "", "ABC", "")
            with self.assertRaises(ValueError):
                OAuth2Service("", ["fileStorage"], FileTransferMode.active,
                              FileTransferArchive.none, "", "", "", "XYZ")
            with self.assertRaises(ValueError):
                OAuth2Service("MusterService", ["fileStorage"],
                              FileTransferMode.active,
                              FileTransferArchive.none,
                              "http://localhost:5001/oauth/authorize", "", "",
                              "")
            with self.assertRaises(ValueError):
                OAuth2Service("MusterService", ["fileStorage"],
                              FileTransferMode.active,
                              FileTransferArchive.none, "",
                              "http://localhost:5001/oauth/refresh", "", "")
            with self.assertRaises(ValueError):
                OAuth2Service("MusterService", ["fileStorage"],
                              FileTransferMode.active,
                              FileTransferArchive.none, "", "", "ABC", "")
            with self.assertRaises(ValueError):
                OAuth2Service("MusterService", ["fileStorage"],
                              FileTransferMode.active,
                              FileTransferArchive.none, "", "", "", "XYZ")
            with self.assertRaises(ValueError):
                OAuth2Service("MusterService", ["fileStorage"],
                              FileTransferMode.active,
                              FileTransferArchive.none,
                              "http://localhost:5001/oauth/refresh", "", "",
                              "")
            with self.assertRaises(ValueError):
                OAuth2Service(
                    "MusterService",
                    ["fileStorage"],
                    FileTransferMode.active,
                    FileTransferArchive.none,
                    "http://localhost:5001/oauth/authorize",
                    "http://localhost:5001/oauth/refresh",
                    "",
                    "",
                )

            # same input for authorize and refresh
            with self.assertRaises(ValueError):
                OAuth2Service(
                    "MusterService",
                    ["fileStorage"],
                    FileTransferMode.active,
                    FileTransferArchive.none,
                    "",
                    "http://localhost:5001/oauth/authorize",
                    "http://localhost:5001/oauth/refresh",
                    "",
                    "",
                )
    def test_owncloud(self):

        # prepare service
        storage = Storage()

        redirect = "https://10.14.29.60/owncloud/index.php/apps/rds/oauth"
        owncloud = OAuth2Service(
            servicename="owncloud-local",
            implements=["metadata"],
            authorize_url=
            "https://10.14.29.60/owncloud/index.php/apps/oauth2/authorize?response_type=code&client_id={}&redirect_uri={}"
            .format(os.getenv("OWNCLOUD_OAUTH_CLIENT_ID"), redirect),
            refresh_url=
            "https://10.14.29.60/owncloud/index.php/apps/oauth2/api/v1/token",
            client_id=os.getenv("OWNCLOUD_OAUTH_CLIENT_ID"),
            client_secret=os.getenv("OWNCLOUD_OAUTH_CLIENT_SECRET"),
        )

        storage.addService(owncloud)

        # prepare user, which wants to make the whole oauth workflow
        user1 = User("user")
        token1 = Token(user1, owncloud, "user")

        storage.addUser(user1)
        storage.addTokenToUser(token1, user1)

        def get_access_token(user, token):
            nonlocal owncloud, storage

            self.driver.get(owncloud.authorize_url)

            if self.driver.current_url.startswith(
                    "https://10.14.29.60/owncloud/index.php/login"):
                # it redirects to login form
                field_username = self.driver.find_element_by_xpath(
                    '//*[@id="user"]')
                field_password = self.driver.find_element_by_xpath(
                    '//*[@id="password"]')
                field_username.clear()
                field_username.send_keys(user.username)

                field_password.clear()
                field_password.send_keys(token.access_token)

                old_url = self.driver.current_url
                url = self.driver.current_url

                field_password.send_keys(Keys.RETURN)

                retry = 0
                while old_url == url and retry < 5:
                    sleep(1)
                    retry += 1
                    url = self.driver.current_url
                    logger.info("url: {}".format(url))

                if retry >= 5:
                    raise Exception("url not redirect!")

            btn = self.driver.find_element_by_xpath(
                "/html/body/div[1]/div/span/form/button")
            old_url = self.driver.current_url
            url = self.driver.current_url

            btn.click()

            retry = 0
            while old_url == url and retry < 5:
                sleep(1)
                retry += 1
                url = self.driver.current_url
                logger.info("url: {}".format(url))

            if retry >= 5:
                raise Exception("url not redirect!")

            self.driver.delete_all_cookies()  # remove all cookies

            from urllib.parse import urlparse, parse_qs

            query = urlparse(url).query
            logger.info("query: {}".format(query))

            parse = parse_qs(query)
            logger.info("parse: {}".format(parse))

            code = parse["code"]

            data = {
                "grant_type": "authorization_code",
                "code": code,
                "redirect_uri": redirect,
            }

            req = requests.post(
                owncloud.refresh_url,
                data=data,
                auth=(owncloud.client_id, owncloud.client_secret),
                verify=False,
            ).json()
            oauthtoken = OAuth2Token(
                user,
                token.service,
                req["access_token"],
                req["refresh_token"],
                datetime.now() + timedelta(seconds=req["expires_in"]),
            )
            return oauthtoken

        oauthtoken1 = get_access_token(user1, token1)
        storage.addTokenToUser(oauthtoken1, user1, Force=True)

        ######## test a refresh token #######
        # prepare user, which wants to get a refresh token

        oauthuser2 = User("user_refresh")

        # check if there is already a file, which has an oauth2token to reuse it.
        oauthtoken2 = None
        filepath = "https://zivgitlab.uni-muenster.de/{}/{}/-/jobs/artifacts/{}/raw/{}/user_refresh.token?job_token={}&job={}".format(
            os.getenv("CI_PROJECT_NAMESPACE"),
            os.getenv("CI_PROJECT_NAME"),
            os.getenv("CI_COMMIT_REF_NAME"),
            os.getenv("FOLDER"),
            os.getenv("CI_JOB_TOKEN"),
            os.getenv("CI_JOB_NAME"),
        )
        try:
            headers = {"JOB-TOKEN": os.getenv("CI_JOB_TOKEN")}
            req = requests.get(filepath, headers=headers)
            if req.status_code != 200:
                raise Exception(
                    "Artifact not found, filepath: {filepath}, headers: {headers}"
                )

            try:
                oauthtoken2 = initialize_object_from_json(req.text)
            except Exception as e:
                raise Exception(f"{str(e)} + \n req: {req.text}")
        except Exception as e:
            logger.error(e)
            logger.warning(
                "No refresh token from previous test run was found, so we collect a new one. \nFilepath: {}"
                .format(filepath))
            # initialize like user1 with password
            token2 = Token(oauthuser2, owncloud, "user_refresh")

            # generate an oauthtoken like before and overwrite oauthtoken1
            oauthtoken2 = get_access_token(oauthuser2, token2)

        storage.addUser(oauthuser2)
        storage.addTokenToUser(oauthtoken2, oauthuser2)

        # try to refresh it now
        storage.refresh_service(owncloud)
        tokens = storage.getTokens(oauthuser2)
        checkToken = tokens[0]
        self.assertEqual(checkToken, oauthtoken2)

        # safe the current oauthtoken for reuse to test refresh token after a bigger period.
        with open("user_refresh.token", "w") as f:
            f.write(json.dumps(checkToken))
    def test_zenodo(self):
        # prepare service
        storage = Storage()

        zenodo = OAuth2Service(
            servicename="sandbox.zenodo.org",
            authorize_url=
            "https://sandbox.zenodo.org/oauth/authorize?scope=deposit%3Awrite+deposit%3Aactions&state=CHANGEME&redirect_uri=http%3A%2F%2Flocalhost%3A8080&response_type=code&client_id={}"
            .format(os.getenv("ZENODO_OAUTH_CLIENT_ID")),
            refresh_url="https://sandbox.zenodo.org/oauth/token",
            client_id=os.getenv("ZENODO_OAUTH_CLIENT_ID"),
            client_secret=os.getenv("ZENODO_OAUTH_CLIENT_SECRET"),
        )

        # TODO: needs valid user in env var in gitlab
        zenodouser1 = User("USERNAME")
        zenodotoken1 = Token(zenodo.servicename, "PASSWORT")

        def get_access_token(user, token):
            nonlocal zenodo, storage

            self.driver.get(zenodo.authorize_url)

            if self.driver.current_url.startswith(
                    "https://sandbox.zenodo.org/login"):
                # it redirects to login form
                field_username = self.driver.find_element_by_xpath(
                    '//*[@id="email"]')
                field_password = self.driver.find_element_by_xpath(
                    '//*[@id="password"]')
                field_username.clear()
                field_username.send_keys(user.username)

                field_password.clear()
                field_password.send_keys(token.access_token)
                field_password.send_keys(Keys.RETURN)

            self.driver.get(zenodo.authorize_url)
            btn = self.driver.find_element_by_xpath(
                "/html/body/div[2]/div[2]/div/div/div/div/div[2]/div[2]/form/button[1]"
            )
            old_url = self.driver.current_url
            url = self.driver.current_url

            btn.click()

            retry = 0
            while old_url == url and retry < 5:
                sleep(1)
                retry += 1
                url = self.driver.current_url
                logger.info("url: {}".format(url))

            if retry >= 5:
                raise Exception("url not redirect!")

            self.driver.delete_all_cookies()  # remove all cookies

            from urllib.parse import urlparse, parse_qs

            query = urlparse(url).query
            logger.info("query: {}".format(query))

            parse = parse_qs(query)
            logger.info("parse: {}".format(parse))

            code = parse["code"]

            data = {
                "grant_type": "authorization_code",
                "code": code,
                "redirect_uri": redirect,
            }

            req = requests.post(
                zenodo.refresh_url,
                data=data,
                auth=(zenodo.client_id, zenodo.client_secret),
            ).json()
            oauthtoken = OAuth2Token(
                zenodo.servicename,
                req["access_token"],
                req["refresh_token"],
                datetime.now() + timedelta(seconds=req["expires_in"]),
            )
            return oauthtoken

        oauthtoken1 = get_access_token(zenodouser1, zenodotoken1)
        storage.addTokenToUser(oauthtoken1, zenodouser1, Force=True)