Esempio n. 1
0
 def _prepare_untrusted_prawcore(self, requestor):
     authenticator = UntrustedAuthenticator(requestor,
                                            self.config.client_id,
                                            self.config.redirect_uri)
     read_only_authorizer = DeviceIDAuthorizer(authenticator)
     self._read_only_core = session(read_only_authorizer)
     if self.config.refresh_token:
         authorizer = Authorizer(authenticator, self.config.refresh_token)
         self._core = self._authorized_core = session(authorizer)
     else:
         self._core = self._read_only_core
Esempio n. 2
0
 def _prepare_untrusted_prawcore(self, requestor):
     authenticator = UntrustedAuthenticator(requestor,
                                            self.config.client_id,
                                            self.config.redirect_uri)
     read_only_authorizer = DeviceIDAuthorizer(authenticator)
     self._read_only_core = session(read_only_authorizer)
     self._prepare_common_authorizer(authenticator)
Esempio n. 3
0
    def _prepare_trusted_prawcore(self, requestor):
        authenticator = TrustedAuthenticator(requestor, self.config.client_id,
                                             self.config.client_secret,
                                             self.config.redirect_uri)
        read_only_authorizer = ReadOnlyAuthorizer(authenticator)
        self._read_only_core = session(read_only_authorizer)

        if self.config.username and self.config.password:
            script_authorizer = ScriptAuthorizer(
                authenticator, self.config.username, self.config.password)
            self._core = self._authorized_core = session(script_authorizer)
        elif self.config.refresh_token:
            authorizer = Authorizer(authenticator, self.config.refresh_token)
            self._core = self._authorized_core = session(authorizer)
        else:
            self._core = self._read_only_core
Esempio n. 4
0
    def _prepare_trusted_prawcore(self, requestor):
        authenticator = TrustedAuthenticator(requestor, self.config.client_id,
                                             self.config.client_secret,
                                             self.config.redirect_uri)
        read_only_authorizer = ReadOnlyAuthorizer(authenticator)
        self._read_only_core = session(read_only_authorizer)

        if self.config.username and self.config.password:
            script_authorizer = ScriptAuthorizer(
                authenticator, self.config.username, self.config.password)
            self._core = self._authorized_core = session(script_authorizer)
        elif self.config.refresh_token:
            authorizer = Authorizer(authenticator, self.config.refresh_token)
            self._core = self._authorized_core = session(authorizer)
        else:
            self._core = self._read_only_core
Esempio n. 5
0
    def implicit(self, access_token, expires_in, scope):
        """Set the active authorization to be an implicit authorization.

        :param access_token: The access_token obtained from Reddit's callback.
        :param expires_in: The number of seconds the ``access_token`` is valid
            for. The origin of this value was returned from Reddit's callback.
            You may need to subtract an offset before passing in this number to
            account for a delay between when Reddit prepared the response, and
            when you make this function call.
        :param scope: A space-delimited string of Reddit OAuth2 scope names as
            returned from Reddit's callback.

        Raise :class:`.ClientException` if :class:`.Reddit` was initialized for
        a non-installed application type.

        """
        authenticator = self._reddit._read_only_core._authorizer._authenticator
        if not isinstance(authenticator, UntrustedAuthenticator):
            raise ClientException(
                "implicit can only be used with installed apps."
            )
        implicit_session = session(
            ImplicitAuthorizer(authenticator, access_token, expires_in, scope)
        )
        self._reddit._core = self._reddit._authorized_core = implicit_session
Esempio n. 6
0
    def _prepare_common_authorizer(self, authenticator):
        if self._token_manager is not None:
            warn(
                "Token managers have been depreciated and will be removed in the near"
                " future. See https://www.reddit.com/r/redditdev/comments/olk5e6/"
                "followup_oauth2_api_changes_regarding_refresh/ for more details.",
                category=DeprecationWarning,
                stacklevel=2,
            )
            if self.config.refresh_token:
                raise TypeError(
                    "``refresh_token`` setting cannot be provided when providing"
                    " ``token_manager``")

            self._token_manager.reddit = self
            authorizer = Authorizer(
                authenticator,
                post_refresh_callback=self._token_manager.
                post_refresh_callback,
                pre_refresh_callback=self._token_manager.pre_refresh_callback,
            )
        elif self.config.refresh_token:
            authorizer = Authorizer(authenticator,
                                    refresh_token=self.config.refresh_token)
        else:
            self._core = self._read_only_core
            return
        self._core = self._authorized_core = session(authorizer)
Esempio n. 7
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. 8
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. 9
0
File: auth.py Progetto: gavin19/praw
    def authorize(self, code):
        """Complete the web authorization flow and return the refresh token.

        :param code: The code obtained through the request to the redirect uri.
        :returns: The obtained refresh token, if available, otherwise ``None``.

        The session's active authorization will be updated upon success.

        """
        authenticator = self._reddit._read_only_core._authorizer._authenticator
        authorizer = Authorizer(authenticator)
        authorizer.authorize(code)
        authorized_session = session(authorizer)
        self._reddit._core = self._reddit._authorized_core = authorized_session
        return authorizer.refresh_token
Esempio n. 10
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. 11
0
    def authorize(self, code):
        """Complete the web authorization flow and return the refresh token.

        :param code: The code obtained through the request to the redirect uri.
        :returns: The obtained refresh token, if available, otherwise ``None``.

        The session's active authorization will be updated upon success.

        """
        authenticator = self._reddit._read_only_core._authorizer._authenticator
        authorizer = Authorizer(authenticator)
        authorizer.authorize(code)
        authorized_session = session(authorizer)
        self._reddit._core = self._reddit._authorized_core = authorized_session
        return authorizer.refresh_token
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
File: auth.py Progetto: RGood/praw
    def authorize(self, code):
        """Complete the web authorization flow and return the refresh token.

        :param code: The code obtained through the request to the redirect uri.
        :returns: The obtained refresh token, if available, otherwise ``None``.

        The session's active authorization will be updated upon success.

        """
        authenticator = self._reddit._read_only_core._authorizer._authenticator
        if not isinstance(authenticator, TrustedAuthenticator) or \
           self._reddit.config.username:
            raise ClientException('authorize can only be used with web apps.')
        authorizer = Authorizer(authenticator)
        authorizer.authorize(code)
        authorized_session = session(authorizer)
        self._reddit._core = self._reddit._authorized_core = authorized_session
        return authorizer.refresh_token
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 implicit(self, access_token: str, expires_in: int, scope: str) -> None:
        """Set the active authorization to be an implicit authorization.

        :param access_token: The access_token obtained from Reddit's callback.
        :param expires_in: The number of seconds the ``access_token`` is valid for. The
            origin of this value was returned from Reddit's callback. You may need to
            subtract an offset before passing in this number to account for a delay
            between when Reddit prepared the response, and when you make this function
            call.
        :param scope: A space-delimited string of Reddit OAuth2 scope names as returned
            from Reddit's callback.

        :raises: :class:`.InvalidImplicitAuth` if :class:`.Reddit` was initialized for a
            non-installed application type.

        """
        authenticator = self._reddit._read_only_core._authorizer._authenticator
        if not isinstance(authenticator, UntrustedAuthenticator):
            raise InvalidImplicitAuth
        implicit_session = session(
            ImplicitAuthorizer(authenticator, access_token, expires_in, scope))
        self._reddit._core = self._reddit._authorized_core = implicit_session
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.UntrustedAuthenticator(
        prawcore.Requestor('prawcore_device_id_auth_example'),
        os.environ['PRAWCORE_CLIENT_ID'])
    authorizer = prawcore.DeviceIDAuthorizer(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. 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

    authenticator = prawcore.UntrustedAuthenticator(
        prawcore.Requestor('prawcore_device_id_auth_example'),
        os.environ['PRAWCORE_CLIENT_ID'])
    authorizer = prawcore.DeviceIDAuthorizer(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. 18
0
    def _prepare_common_authorizer(self, authenticator):
        if self._token_manager is not None:
            if self.config._do_not_use_refresh_token != self.config.CONFIG_NOT_SET:
                raise TypeError(
                    "legacy ``refresh_token`` setting cannot be provided when providing"
                    " ``token_manager``")

            self._token_manager.reddit = self
            authorizer = Authorizer(
                authenticator,
                post_refresh_callback=self._token_manager.
                post_refresh_callback,
                pre_refresh_callback=self._token_manager.pre_refresh_callback,
            )
        elif self.config._do_not_use_refresh_token != self.config.CONFIG_NOT_SET:
            authorizer = Authorizer(
                authenticator,
                refresh_token=self.config._do_not_use_refresh_token)
        else:
            self._core = self._read_only_core
            return
        self._core = self._authorized_core = session(authorizer)
Esempio n. 19
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

    authenticator = prawcore.UntrustedAuthenticator(
        prawcore.Requestor("prawcore_device_id_auth_example"),
        os.environ["PRAWCORE_CLIENT_ID"],
    )
    authorizer = prawcore.DeviceIDAuthorizer(authenticator)
    authorizer.refresh()

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

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

    return 0
Esempio n. 20
0
 def test_session(self):
     self.assertIsInstance(
         prawcore.session(InvalidAuthorizer()), prawcore.Session
     )
Esempio n. 21
0
 def _prepare_untrusted_prawcore(self, requestor):
     authenticator = UntrustedAuthenticator(requestor,
                                            self.config.client_id,
                                            self.config.redirect_uri)
     read_only_authorizer = DeviceIDAuthorizer(authenticator)
     self._core = self._read_only_core = session(read_only_authorizer)
Esempio n. 22
0
 def test_session(self):
     self.assertIsInstance(prawcore.session(InvalidAuthorizer()),
                           prawcore.Session)