コード例 #1
0
async def injector(cleandir, ports, generate_config):
    drive_creds = Creds(FakeTime(), "test_client_id", None, "test_access_token", "test_refresh_token")
    with open(os.path.join(cleandir, "secrets.yaml"), "w") as f:
        f.write("for_unit_tests: \"password value\"\n")

    with open(os.path.join(cleandir, "credentials.dat"), "w") as f:
        f.write(json.dumps(drive_creds.serialize()))

    return Injector([BaseModule(), TestModule(generate_config, ports)])
コード例 #2
0
async def test_token_extra_server(reader: ReaderHelper, coord: Coordinator, ha, drive: DriveSource, restarter, time):
    update = {
        "config": {
            "expose_extra_server": True
        },
        "snapshot_folder": "unused"
    }
    assert await reader.postjson("saveconfig", json=update) == {'message': 'Settings saved', "reload_page": False}
    await restarter.waitForRestart()
    creds = Creds(time, "id", time.now(), "token", "refresh")
    serialized = str(base64.b64encode(json.dumps(creds.serialize()).encode("utf-8")), "utf-8")
    await reader.get("token?creds={0}&host={1}".format(quote(serialized), quote(reader.getUrl(False))), ingress=False)
    assert drive.drivebackend.creds.access_token == 'token'
コード例 #3
0
 def tryLoadCredentials(self):
     if os.path.isfile(self.config.get(Setting.CREDENTIALS_FILE_PATH)):
         try:
             with open(self.config.get(Setting.CREDENTIALS_FILE_PATH)) as f:
                 self.creds = Creds.load(self.time, json.load(f))
             return
         except Exception:
             pass
コード例 #4
0
async def test_token_extra_server(reader: ReaderHelper, coord: Coordinator, ha,
                                  drive: DriveSource, restarter, time):
    update = {
        "config": {
            "expose_extra_server": True
        },
        "snapshot_folder": "unused"
    }
    assert await reader.postjson("saveconfig", json=update) == {
        'message': 'Settings saved'
    }
    await restarter.waitForRestart()
    creds = Creds(time, "id", time.now(), "token", "refresh")
    resp = await reader.get("token?creds=" +
                            quote(json.dumps(creds.serialize())),
                            ingress=False)
    assert "window.location.assign(\"/\")" in resp
コード例 #5
0
 def saveCredentials(self, creds: Creds):
     if not creds:
         if os.path.exists(self.config.get(Setting.CREDENTIALS_FILE_PATH)):
             os.remove(self.config.get(Setting.CREDENTIALS_FILE_PATH))
             self.creds = None
         return
     with open(self.config.get(Setting.CREDENTIALS_FILE_PATH), "w") as f:
         json.dump(creds.serialize(), f)
     self.tryLoadCredentials()
コード例 #6
0
async def injector(cleandir, server_url, ui_port, ingress_port):
    drive_creds = Creds(FakeTime(), "test_client_id", None,
                        "test_access_token", "test_refresh_token")
    with open(os.path.join(cleandir, "secrets.yaml"), "w") as f:
        f.write("for_unit_tests: \"password value\"\n")

    with open(os.path.join(cleandir, "credentials.dat"), "w") as f:
        f.write(json.dumps(drive_creds.serialize()))

    config = Config.withOverrides({
        Setting.DRIVE_URL: server_url,
        Setting.HASSIO_URL: server_url + "/",
        Setting.HOME_ASSISTANT_URL: server_url + "/homeassistant/api/",
        Setting.AUTHENTICATE_URL: server_url + "/drive/authorize",
        Setting.DRIVE_REFRESH_URL: server_url + "/oauth2/v4/token",
        Setting.DRIVE_AUTHORIZE_URL: server_url + "/o/oauth2/v2/auth",
        Setting.DRIVE_TOKEN_URL: server_url + "/token",
        Setting.REFRESH_URL: server_url + "/drive/refresh",
        Setting.ERROR_REPORT_URL: server_url + "/logerror",
        Setting.HASSIO_TOKEN: "test_header",
        Setting.SECRETS_FILE_PATH: "secrets.yaml",
        Setting.CREDENTIALS_FILE_PATH: "credentials.dat",
        Setting.FOLDER_FILE_PATH: "folder.dat",
        Setting.RETAINED_FILE_PATH: "retained.json",
        Setting.ID_FILE_PATH: "id.json",
        Setting.INGRESS_TOKEN_FILE_PATH: "ingress.dat",
        Setting.DEFAULT_DRIVE_CLIENT_ID: "test_client_id",
        Setting.DEFAULT_DRIVE_CLIENT_SECRET: "test_client_secret",
        Setting.BACKUP_DIRECTORY_PATH: cleandir,
        Setting.PORT: ui_port,
        Setting.INGRESS_PORT: ingress_port
    })

    # PROBLEM: Something in uploading snapshot chunks hangs between the client and server, so his keeps tests from
    # taking waaaaaaaay too long.  Remove this line and the @pytest.mark.flaky annotations once the problem is identified.
    config.override(Setting.GOOGLE_DRIVE_TIMEOUT_SECONDS, 5)

    # logging.getLogger('injector').setLevel(logging.DEBUG)
    return Injector([
        BaseModule(config),
        TestModule(cleandir, server_url, ui_port, ingress_port)
    ])
コード例 #7
0
 async def token(self, request: Request) -> None:
     if 'creds' in request.query:
         self._global_info.setIngoreErrorsForNow(True)
         self._coord.saveCreds(Creds.load(
             self._time, json.loads(request.query['creds'])))
     try:
         if request.url.port != self.config.get(Setting.PORT):
             return await self.redirect(self._ha_source.getAddonUrl())
     except:  # noqa: E722
         # eat the error
         pass
     return await self.redirect("/")
コード例 #8
0
    async def token(self, request: Request) -> None:
        self._global_info.setIngoreErrorsForNow(True)
        creds_deserialized = json.loads(str(base64.b64decode(request.query.get('creds').encode("utf-8")), 'utf-8'))
        creds = Creds.load(self._time, creds_deserialized)
        self._coord.saveCreds(creds)

        # Build the redirect url
        if 'host' in request.query:
            redirect = request.query.get('host')
        else:
            redirect = self._ha_source.getAddonUrl()
        if MIME_JSON in request.headers[hdrs.ACCEPT]:
            return web.json_response({'redirect': str(redirect)})
        else:
            raise HTTPSeeOther(redirect)
コード例 #9
0
 def getDriveCreds(self, time: Time) -> Creds:
     return Creds(time, "test_client_id", time.now(), "test_access_token", "test_refresh_token", "test_client_secret")
コード例 #10
0
 def creds(self):
     return Creds(self._time,
                  id=self.config.get(Setting.DEFAULT_DRIVE_CLIENT_ID),
                  expiration=self._time.now() + timedelta(hours=1),
                  access_token=self._auth_token,
                  refresh_token=self._refresh_token)
コード例 #11
0
 def getCurrentCreds(self):
     return Creds(self._time,
                  id=self.config.get(Setting.DEFAULT_DRIVE_CLIENT_ID),
                  expiration=self._time.now() + timedelta(hours=1),
                  access_token=self.getSetting("drive_auth_token"),
                  refresh_token=self.getSetting("drive_refresh_token"))