Esempio n. 1
0
def script_authorizer():
    authenticator = prawcore.TrustedAuthenticator(
        REQUESTOR, CLIENT_ID, CLIENT_SECRET
    )
    authorizer = prawcore.ScriptAuthorizer(authenticator, USERNAME, PASSWORD)
    authorizer.refresh()
    return authorizer
Esempio n. 2
0
def main():
    """Provide the program's entry point when directly executed."""
    if len(sys.argv) != 2:
        print("Usage: {} USERNAME".format(sys.argv[0]))
        return 1

    authenticator = prawcore.TrustedAuthenticator(
        prawcore.Requestor("prawcore_read_only_example"),
        os.environ["PRAWCORE_CLIENT_ID"],
        os.environ["PRAWCORE_CLIENT_SECRET"],
    )
    authorizer = prawcore.ReadOnlyAuthorizer(authenticator)
    authorizer.refresh()

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

    for trophy in data["data"]["trophies"]:
        description = trophy["data"]["description"]
        print(
            trophy["data"]["name"]
            + (" ({})".format(description) if description else "")
        )

    return 0
Esempio n. 3
0
def readonly_authorizer(refresh=True):
    authenticator = prawcore.TrustedAuthenticator(REQUESTOR, CLIENT_ID,
                                                  CLIENT_SECRET)
    authorizer = prawcore.ReadOnlyAuthorizer(authenticator)
    if refresh:
        authorizer.refresh()
    return authorizer
Esempio n. 4
0
def client_authorizer():
    authenticator = prawcore.TrustedAuthenticator(
        REQUESTOR, CLIENT_ID, CLIENT_SECRET
    )
    authorizer = prawcore.Authorizer(authenticator, REFRESH_TOKEN)
    authorizer.refresh()
    return authorizer
Esempio n. 5
0
 def test_initialize__with_trusted_authenticator(self):
     authenticator = prawcore.TrustedAuthenticator(None, None, None)
     self.assertRaises(
         prawcore.InvalidInvocation,
         prawcore.DeviceIDAuthorizer,
         authenticator,
     )
Esempio n. 6
0
 def test_authorize_url__fail_with_implicit(self):
     authenticator = prawcore.TrustedAuthenticator(REQUESTOR, CLIENT_ID,
                                                   CLIENT_SECRET,
                                                   REDIRECT_URI)
     self.assertRaises(prawcore.InvalidInvocation,
                       authenticator.authorize_url,
                       'temporary', ['identity', 'read'],
                       'a_state',
                       implicit=True)
Esempio n. 7
0
 def test_authorize_url__fail_without_redirect_uri(self):
     authenticator = prawcore.TrustedAuthenticator(REQUESTOR, CLIENT_ID,
                                                   CLIENT_SECRET)
     self.assertRaises(
         prawcore.InvalidInvocation,
         authenticator.authorize_url,
         "permanent",
         ["identity"],
         "...",
     )
Esempio n. 8
0
 def test_authorize_url(self):
     authenticator = prawcore.TrustedAuthenticator(REQUESTOR, CLIENT_ID,
                                                   CLIENT_SECRET,
                                                   REDIRECT_URI)
     url = authenticator.authorize_url('permanent', ['identity', 'read'],
                                       'a_state')
     self.assertIn('client_id={}'.format(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)
Esempio n. 9
0
 def test_authorize_url(self):
     authenticator = prawcore.TrustedAuthenticator(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)
Esempio n. 10
0
 def test_authorize_url__fail_with_implicit(self):
     authenticator = prawcore.TrustedAuthenticator(REQUESTOR, CLIENT_ID,
                                                   CLIENT_SECRET,
                                                   REDIRECT_URI)
     self.assertRaises(
         prawcore.InvalidInvocation,
         authenticator.authorize_url,
         "temporary",
         ["identity", "read"],
         "a_state",
         implicit=True,
     )
Esempio n. 11
0
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 = prawcore.Requestor(
        "prawcore_device_id_auth_example", session=CachingSession()
    )
    authenticator = prawcore.TrustedAuthenticator(
        caching_requestor,
        os.environ["PRAWCORE_CLIENT_ID"],
        os.environ["PRAWCORE_CLIENT_SECRET"],
    )
    authorizer = prawcore.ReadOnlyAuthorizer(authenticator)
    authorizer.refresh()

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

    with prawcore.session(authorizer) as session:
        data2 = 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"],
    )

    return 0
Esempio n. 12
0
def main():
    """Provide the program's entry point when directly executed."""
    authenticator = prawcore.TrustedAuthenticator(
        prawcore.Requestor('prawcore_script_auth_example'),
        os.environ['PRAWCORE_CLIENT_ID'],
        os.environ['PRAWCORE_CLIENT_SECRET'])
    authorizer = prawcore.ScriptAuthorizer(authenticator,
                                           os.environ['PRAWCORE_USERNAME'],
                                           os.environ['PRAWCORE_PASSWORD'])
    authorizer.refresh()

    with prawcore.session(authorizer) as session:
        data = session.request('GET', '/api/v1/me/friends')

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

    return 0
Esempio n. 13
0
def main():
    """Provide the program's entry point when directly executed."""
    if len(sys.argv) < 2:
        print("Usage: {} SCOPE...".format(sys.argv[0]))
        return 1

    authenticator = prawcore.TrustedAuthenticator(
        prawcore.Requestor("prawcore_refresh_token_example"),
        os.environ["PRAWCORE_CLIENT_ID"],
        os.environ["PRAWCORE_CLIENT_SECRET"],
        os.environ["PRAWCORE_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,
            "State mismatch. Expected: {} Received: {}".format(
                state, params["state"]
            ),
        )
        return 1
    elif "error" in params:
        send_message(client, params["error"])
        return 1

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

    send_message(client, "Refresh token: {}".format(authorizer.refresh_token))
    return 0
def main():
    """Provide the program's entry point when directly executed."""
    authenticator = prawcore.TrustedAuthenticator(
        prawcore.Requestor("prawcore_script_auth_example"),
        os.environ["PRAWCORE_CLIENT_ID"],
        os.environ["PRAWCORE_CLIENT_SECRET"],
    )
    authorizer = prawcore.ScriptAuthorizer(
        authenticator,
        os.environ["PRAWCORE_USERNAME"],
        os.environ["PRAWCORE_PASSWORD"],
    )
    authorizer.refresh()

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

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

    return 0
Esempio n. 15
0
def main():
    """Provide the program's entry point when directly executed."""
    if len(sys.argv) != 2:
        print('Usage: {} USERNAME'.format(sys.argv[0]))
        return 1

    authenticator = prawcore.TrustedAuthenticator(
        prawcore.Requestor('prawcore_read_only_example'),
        os.environ['PRAWCORE_CLIENT_ID'],
        os.environ['PRAWCORE_CLIENT_SECRET'])
    authorizer = prawcore.ReadOnlyAuthorizer(authenticator)
    authorizer.refresh()

    user = sys.argv[1]
    with prawcore.session(authorizer) as session:
        data = session.request('GET', '/api/v1/user/{}/trophies'.format(user))

    for trophy in data['data']['trophies']:
        description = trophy['data']['description']
        print(trophy['data']['name'] +
              (' ({})'.format(description) if description else ''))

    return 0
Esempio n. 16
0
def main():
    """Provide the program's entry point when directly executed."""
    if len(sys.argv) < 2:
        print('Usage: {} SCOPE...'.format(sys.argv[0]))
        return 1

    authenticator = prawcore.TrustedAuthenticator(
        prawcore.Requestor('prawcore_refresh_token_example'),
        os.environ['PRAWCORE_CLIENT_ID'], os.environ['PRAWCORE_CLIENT_SECRET'],
        os.environ['PRAWCORE_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, 'State mismatch. Expected: {} Received: {}'.format(
                state, params['state']))
        return 1
    elif 'error' in params:
        send_message(client, params['error'])
        return 1

    authorizer = prawcore.Authorizer(authenticator)
    authorizer.authorize(params['code'])

    send_message(client, 'Refresh token: {}'.format(authorizer.refresh_token))
    return 0
Esempio n. 17
0
def main():
    """Provide the program's entry point when directly executed."""
    if len(sys.argv) != 2:
        print('Usage: {} USERNAME'.format(sys.argv[0]))
        return 1

    caching_requestor = prawcore.Requestor('prawcore_device_id_auth_example',
                                           session=CachingSession())
    authenticator = prawcore.TrustedAuthenticator(
        caching_requestor, os.environ['PRAWCORE_CLIENT_ID'],
        os.environ['PRAWCORE_CLIENT_SECRET'])
    authorizer = prawcore.ReadOnlyAuthorizer(authenticator)
    authorizer.refresh()

    user = sys.argv[1]
    with prawcore.session(authorizer) as session:
        data1 = session.request('GET', '/api/v1/user/{}/trophies'.format(user))

    with prawcore.session(authorizer) as session:
        data2 = session.request('GET', '/api/v1/user/{}/trophies'.format(user))

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

    for trophy in data2['data']['trophies']:
        description = trophy['data']['description']
        print(
            'Cached:', trophy['data']['name'] +
            (' ({})'.format(description) if description else ''))
    print('----\nCached == Original:',
          data2['data']['trophies'] == data2['data']['trophies'])

    return 0
Esempio n. 18
0
 def test_revoke_token__with_access_token_hint(self):
     authenticator = prawcore.TrustedAuthenticator(REQUESTOR, CLIENT_ID,
                                                   CLIENT_SECRET)
     with Betamax(REQUESTOR).use_cassette(
             "TrustedAuthenticator_revoke_token__with_access_token_hint"):
         authenticator.revoke_token("dummy token", "access_token")
Esempio n. 19
0
 def __init__(self):
     super(InvalidAuthorizer, self).__init__(
         prawcore.TrustedAuthenticator(REQUESTOR, CLIENT_ID, CLIENT_SECRET)
     )
Esempio n. 20
0
 def test_revoke_token__with_refresh_token_hint(self):
     authenticator = prawcore.TrustedAuthenticator(REQUESTOR, CLIENT_ID,
                                                   CLIENT_SECRET)
     with Betamax(REQUESTOR).use_cassette(
             'TrustedAuthenticator_revoke_token__with_refresh_token_hint'):
         authenticator.revoke_token('dummy token', 'refresh_token')
Esempio n. 21
0
 def setUp(self):
     self.authentication = prawcore.TrustedAuthenticator(
         REQUESTOR, CLIENT_ID, CLIENT_SECRET
     )