Example #1
0
def box_oauth_finish(auth, **kwargs):
    """View called when the Oauth flow is completed. Adds a new BoxUserSettings
    record to the user and saves the user's access token and account info.
    """
    user = auth.user
    node = Node.load(session.data.pop('box_auth_nid', None))

    # Handle request cancellations from Box's API
    if request.args.get('error'):
        flash('Box authorization request cancelled.')
        if node:
            return redirect(node.web_url_for('node_setting'))
        return redirect(web_url_for('user_addons'))

    result = finish_auth()

    # If result is a redirect response, follow the redirect
    if isinstance(result, BaseResponse):
        return result

    client = BoxClient(CredentialsV2(
        result['access_token'],
        result['refresh_token'],
        settings.BOX_KEY,
        settings.BOX_SECRET,
    ))

    about = client.get_user_info()
    oauth_settings = BoxOAuthSettings.load(about['id'])

    if not oauth_settings:
        oauth_settings = BoxOAuthSettings(user_id=about['id'], username=about['name'])
        oauth_settings.save()

    oauth_settings.refresh_token = result['refresh_token']
    oauth_settings.access_token = result['access_token']
    oauth_settings.expires_at = datetime.utcfromtimestamp(time.time() + 3600)

    # Make sure user has box enabled
    user.add_addon('box')
    user.save()

    user_settings = user.get_addon('box')
    user_settings.oauth_settings = oauth_settings

    user_settings.save()

    flash('Successfully authorized Box', 'success')

    if node:
        # Automatically use newly-created auth
        if node.has_addon('box'):
            node_addon = node.get_addon('box')
            node_addon.set_user_auth(user_settings)
            node_addon.save()
        return redirect(node.web_url_for('node_setting'))
    return redirect(web_url_for('user_addons'))
Example #2
0
    def test_automatic_refresh(self):
        credentials = CredentialsV2("access_token", "refresh_token", "client_id", "client_secret")
        client = BoxClient(credentials)

        requests_mock = flexmock(requests)

        # The first attempt, which is denied
        (
            requests_mock.should_receive("request")
            .with_args(
                "get", "https://api.box.com/2.0/users/me", params=None, data=None, headers=client.default_headers
            )
            .and_return(mocked_response(status_code=401))
            .once()
        )

        # The call to refresh the token
        (
            requests_mock.should_receive("post")
            .with_args(
                "https://www.box.com/api/oauth2/token",
                {
                    "client_id": "client_id",
                    "client_secret": "client_secret",
                    "refresh_token": "refresh_token",
                    "grant_type": "refresh_token",
                },
            )
            .and_return(mocked_response({"access_token": "new_access_token", "refresh_token": "new_refresh_token"}))
            .once()
        )

        # The second attempt with the new access token
        (
            requests_mock.should_receive("request")
            .with_args(
                "get",
                "https://api.box.com/2.0/users/me",
                params=None,
                data=None,
                headers={"Authorization": "Bearer new_access_token"},
            )
            .and_return(mocked_response({"name": "bla"}))
            .once()
        )

        result = client.get_user_info()
        self.assertDictEqual(result, {"name": "bla"})

        self.assertEqual(credentials._access_token, "new_access_token")
        self.assertEqual(credentials._refresh_token, "new_refresh_token")
Example #3
0
    def test_automatic_refresh(self):
        credentials = CredentialsV2("access_token", "refresh_token", "client_id", "client_secret")
        client = BoxClient(credentials)

        requests_mock = flexmock(requests)

        # The first attempt, which is denied
        (requests_mock
            .should_receive('request')
            .with_args("get",
                       'https://api.box.com/2.0/users/me',
                       params=None,
                       data=None,
                       headers=client.default_headers)
            .and_return(mocked_response(status_code=401))
            .once())

        # The call to refresh the token
        (requests_mock
            .should_receive('post')
            .with_args('https://www.box.com/api/oauth2/token', {
                'client_id': 'client_id',
                'client_secret': 'client_secret',
                'refresh_token': 'refresh_token',
                'grant_type': 'refresh_token',
            })
            .and_return(mocked_response({"access_token": "new_access_token",
                                         "refresh_token": "new_refresh_token"}))\
            .once())

        # The second attempt with the new access token
        (requests_mock
            .should_receive('request')
            .with_args("get",
                       'https://api.box.com/2.0/users/me',
                       params=None,
                       data=None,
                       headers={"Authorization": "Bearer new_access_token"})
            .and_return(mocked_response({'name': 'bla'}))
            .once())

        result = client.get_user_info()
        self.assertDictEqual(result, {'name': 'bla'})

        self.assertEqual(credentials._access_token, "new_access_token")
        self.assertEqual(credentials._refresh_token, "new_refresh_token")
Example #4
0
    def test_automatic_refresh(self):
        credentials = CredentialsV2("access_token", "refresh_token", "client_id", "client_secret")
        client = BoxClient(credentials)

        requests_mock = flexmock(requests)

        # The first attempt, which is denied
        requests_mock \
            .should_receive('request') \
            .with_args("get",
                       'https://api.box.com/2.0/users/me',
                       params=None,
                       data=None,
                       headers=client.default_headers) \
            .and_return(mocked_response(status_code=401)) \
            .once()

        # The call to refresh the token
        requests_mock \
            .should_receive('post')\
            .with_args('https://www.box.com/api/oauth2/token', {
                'client_id': 'client_id',
                'client_secret': 'client_secret',
                'refresh_token': 'refresh_token',
                'grant_type': 'refresh_token',
            })\
            .and_return(mocked_response({"access_token": "new_access_token",
                                         "refresh_token": "new_refresh_token"}))\
            .once()

        # The second attempt with the new access token
        requests_mock \
            .should_receive('request') \
            .with_args("get",
                       'https://api.box.com/2.0/users/me',
                       params=None,
                       data=None,
                       headers={"Authorization": "Bearer new_access_token"}) \
            .and_return(mocked_response({'name': 'bla'})) \
            .once()

        result = client.get_user_info()
        self.assertDictEqual(result, {'name': 'bla'})

        self.assertEqual(credentials._access_token, "new_access_token")
        self.assertEqual(credentials._refresh_token, "new_refresh_token")
Example #5
0
    def handle_callback(self, response):
        """View called when the Oauth flow is completed. Adds a new BoxUserSettings
        record to the user and saves the user's access token and account info.
        """

        client = BoxClient(CredentialsV2(
            response['access_token'],
            response['refresh_token'],
            settings.BOX_KEY,
            settings.BOX_SECRET,
        ))

        about = client.get_user_info()

        return {
            'provider_id': about['id'],
            'display_name': about['name'],
            'profile_url': 'https://app.box.com/profile/{0}'.format(about['id'])
        }