コード例 #1
0
async def main():
    """Provide the program's entry point when directly executed."""
    requestor = asyncprawcore.Requestor("asyncprawcore_script_auth_example")

    try:
        authenticator = asyncprawcore.TrustedAuthenticator(
            requestor,
            os.environ["asyncprawcore_CLIENT_ID"],
            os.environ["asyncprawcore_CLIENT_SECRET"],
        )
        authorizer = asyncprawcore.ScriptAuthorizer(
            authenticator,
            os.environ["asyncprawcore_USERNAME"],
            os.environ["asyncprawcore_PASSWORD"],
        )
        await authorizer.refresh()

        async with asyncprawcore.session(authorizer) as session:
            data = await session.request("GET", "/api/v1/me/friends")

        for friend in data["data"]["children"]:
            print(friend["name"])

        return 0
    finally:
        await requestor.close()
コード例 #2
0
async def main():
    """Provide the program's entry point when directly executed."""
    if len(sys.argv) != 2:
        print(f"Usage: {sys.argv[0]} USERNAME")
        return 1

    requestor = asyncprawcore.Requestor("asyncprawcore_read_only_example")
    try:
        authenticator = asyncprawcore.TrustedAuthenticator(
            requestor,
            os.environ["asyncprawcore_CLIENT_ID"],
            os.environ["asyncprawcore_CLIENT_SECRET"],
        )
        authorizer = asyncprawcore.ReadOnlyAuthorizer(authenticator)
        await authorizer.refresh()

        user = sys.argv[1]
        async with asyncprawcore.session(authorizer) as session:
            data = await session.request("GET",
                                         f"/api/v1/user/{user}/trophies")

        for trophy in data["data"]["trophies"]:
            description = trophy["data"]["description"]
            print(
                f"{trophy['data']['name']}{(f' ({description})' if description else '')}"
            )

        return 0
    finally:
        await requestor.close()
コード例 #3
0
    def __init__(self):
        requestor = asyncprawcore.requestor.Requestor(
            "asyncprawcore:test (by /u/Lil_SpazJoekp)")

        super(InvalidAuthorizer, self).__init__(
            asyncprawcore.TrustedAuthenticator(requestor, CLIENT_ID,
                                               CLIENT_SECRET))
コード例 #4
0
async def script_authorizer():
    requestor = asyncprawcore.requestor.Requestor(
        "asyncprawcore:test (by /u/Lil_SpazJoekp)")
    authenticator = asyncprawcore.TrustedAuthenticator(requestor, CLIENT_ID,
                                                       CLIENT_SECRET)
    authorizer = asyncprawcore.ScriptAuthorizer(authenticator, USERNAME,
                                                PASSWORD, two_factor_callback)
    await authorizer.refresh()
    return authorizer
コード例 #5
0
async def readonly_authorizer(refresh=True, requestor=None):
    requestor = requestor or asyncprawcore.requestor.Requestor(
        "asyncprawcore:test (by /u/Lil_SpazJoekp)")
    authenticator = asyncprawcore.TrustedAuthenticator(requestor, CLIENT_ID,
                                                       CLIENT_SECRET)
    authorizer = asyncprawcore.ReadOnlyAuthorizer(authenticator)
    if refresh:
        await authorizer.refresh()
    return authorizer
コード例 #6
0
async def client_authorizer():
    requestor = asyncprawcore.requestor.Requestor(
        "asyncprawcore:test (by /u/Lil_SpazJoekp)")

    authenticator = asyncprawcore.TrustedAuthenticator(requestor, CLIENT_ID,
                                                       CLIENT_SECRET)
    authorizer = asyncprawcore.Authorizer(authenticator,
                                          refresh_token=REFRESH_TOKEN)
    await authorizer.refresh()
    return authorizer
コード例 #7
0
 def test_authorize_url__fail_without_redirect_uri(self):
     authenticator = asyncprawcore.TrustedAuthenticator(
         self.requestor, CLIENT_ID, CLIENT_SECRET)
     self.assertRaises(
         asyncprawcore.InvalidInvocation,
         authenticator.authorize_url,
         "permanent",
         ["identity"],
         "...",
     )
コード例 #8
0
 async def test_authorize_url(self):
     authenticator = asyncprawcore.TrustedAuthenticator(
         self.requestor, CLIENT_ID, CLIENT_SECRET, REDIRECT_URI)
     url = authenticator.authorize_url("permanent", ["identity", "read"],
                                       "a_state")
     self.assertIn(f"client_id={CLIENT_ID}", url)
     self.assertIn("duration=permanent", url)
     self.assertIn("response_type=code", url)
     self.assertIn("scope=identity+read", url)
     self.assertIn("state=a_state", url)
コード例 #9
0
 def test_authorize_url__fail_with_implicit(self):
     authenticator = asyncprawcore.TrustedAuthenticator(
         self.requestor, CLIENT_ID, CLIENT_SECRET, REDIRECT_URI)
     self.assertRaises(
         asyncprawcore.InvalidInvocation,
         authenticator.authorize_url,
         "temporary",
         ["identity", "read"],
         "a_state",
         implicit=True,
     )
コード例 #10
0
async def main():
    """Provide the program's entry point when directly executed."""
    if len(sys.argv) != 2:
        print(f"Usage: {sys.argv[0]} USERNAME")
        return 1

    caching_requestor = asyncprawcore.Requestor(
        "asyncprawcore_device_id_auth_example", session=CachingSession())
    try:
        authenticator = asyncprawcore.TrustedAuthenticator(
            caching_requestor,
            os.environ["asyncprawcore_CLIENT_ID"],
            os.environ["asyncprawcore_CLIENT_SECRET"],
        )
        authorizer = asyncprawcore.ReadOnlyAuthorizer(authenticator)
        await authorizer.refresh()

        user = sys.argv[1]

        async with asyncprawcore.session(authorizer) as session:
            data1 = await session.request("GET",
                                          f"/api/v1/user/{user}/trophies")

        async with asyncprawcore.session(authorizer) as session:
            data2 = await session.request("GET",
                                          f"/api/v1/user/{user}/trophies")

        for trophy in data1["data"]["trophies"]:
            description = trophy["data"]["description"]
            print(
                "Original:",
                trophy["data"]["name"] +
                (f" ({description})" if description else ""),
            )

        for trophy in data2["data"]["trophies"]:
            description = trophy["data"]["description"]
            print(
                "Cached:",
                trophy["data"]["name"] +
                (f" ({description})" if description else ""),
            )
        print(
            "----\nCached == Original:",
            data2["data"]["trophies"] == data2["data"]["trophies"],
        )
    finally:
        await caching_requestor.close()
コード例 #11
0
async def main():
    """Provide the program's entry point when directly executed."""
    if len(sys.argv) < 2:
        print(f"Usage: {sys.argv[0]} SCOPE...")
        return 1

    requestor = asyncprawcore.Requestor("asyncprawcore_refresh_token_example")
    try:
        authenticator = asyncprawcore.TrustedAuthenticator(
            requestor,
            os.environ["ASYNCPRAWCORE_CLIENT_ID"],
            os.environ["ASYNCPRAWCORE_CLIENT_SECRET"],
            os.environ["ASYNCPRAWCORE_REDIRECT_URI"],
        )

        state = str(random.randint(0, 65000))
        url = authenticator.authorize_url("permanent", sys.argv[1:], state)
        print(url)

        client = receive_connection()
        data = client.recv(1024).decode("utf-8")
        param_tokens = data.split(" ", 2)[1].split("?", 1)[1].split("&")
        params = {
            key: value
            for (key, value) in [token.split("=") for token in param_tokens]
        }

        if state != params["state"]:
            send_message(
                client,
                f"State mismatch. Expected: {state} Received: {params['state']}",
            )
            return 1
        elif "error" in params:
            send_message(client, params["error"])
            return 1

        authorizer = asyncprawcore.Authorizer(authenticator)
        await authorizer.authorize(params["code"])

        send_message(client, f"Refresh token: {authorizer.refresh_token}")
        return 0
    finally:
        await requestor.close()
コード例 #12
0
 async def test_initialize__with_trusted_authenticator(self):
     authenticator = asyncprawcore.TrustedAuthenticator(None, None, None)
     with self.assertRaises(asyncprawcore.InvalidInvocation):
         asyncprawcore.DeviceIDAuthorizer(authenticator)
コード例 #13
0
 async def setUp(self):
     self.requestor = Requestor("asyncprawcore:test (by /u/Lil_SpazJoekp)")
     self.authentication = asyncprawcore.TrustedAuthenticator(
         self.requestor, CLIENT_ID, CLIENT_SECRET)
コード例 #14
0
 async def test_revoke_token__with_refresh_token_hint(self):
     authenticator = asyncprawcore.TrustedAuthenticator(
         self.requestor, CLIENT_ID, CLIENT_SECRET)
     with VCR.use_cassette(
             "TrustedAuthenticator_revoke_token__with_refresh_token_hint"):
         await authenticator.revoke_token("dummy token", "refresh_token")