Beispiel #1
0
    def set_auth(self, external_account, user, **kwargs):
        super(NodeSettings, self).set_auth(external_account, user, **kwargs)

        client = OneDriveClient(self.fetch_access_token())
        user_info = client.user_info()
        self.drive_id = user_info['drive_id']
        self.save()
Beispiel #2
0
 def handle_callback(self, response):
     """View called when the Oauth flow is completed. Adds a new OneDriveUserSettings
     record to the user and saves the user's access token and account info.
     """
     client = OneDriveClient(response['access_token'])
     user_info = client.user_info()
     return {
         'provider_id': user_info['id'],
         'display_name': user_info['name'],
         'profile_url': user_info['link'],
     }
Beispiel #3
0
class OneDriveProvider(ExternalProvider):
    name = 'Microsoft OneDrive'
    short_name = 'onedrive'

    client_id = settings.ONEDRIVE_KEY
    client_secret = settings.ONEDRIVE_SECRET

    auth_url_base = settings.ONEDRIVE_OAUTH_AUTH_ENDPOINT
    callback_url = settings.ONEDRIVE_OAUTH_TOKEN_ENDPOINT
    auto_refresh_url = settings.ONEDRIVE_OAUTH_TOKEN_ENDPOINT
    default_scopes = [
        'wl.basic wl.signin onedrive.readwrite wl.offline_access'
    ]

    refresh_time = settings.REFRESH_TIME

    _drive_client = OneDriveClient()

    def handle_callback(self, response):
        """View called when the Oauth flow is completed. Adds a new OneDriveUserSettings
        record to the user and saves the user's access token and account info.
        """
        user_info = self._drive_client.user_info_for_token(
            response['access_token'])

        return {
            'provider_id': user_info['id'],
            'display_name': user_info['name'],
            'profile_url': user_info['link']
        }

    def fetch_access_token(self, force_refresh=False):
        self.refresh_oauth_key(force=force_refresh)
        return self.account.oauth_key
Beispiel #4
0
def test_folders():
    def _quack(method, url, headers, params, expects, throws):
        if method != 'GET':
            raise 'failure to match method'

        if '{}/drives'.format(settings.MSGRAPH_API_URL) not in url:
            raise 'failure to match url'

        mock_res = mock.Mock()
        mock_res.json = mock.Mock(
            return_value={'value': raw_root_folder_response})
        return mock_res

    client = OneDriveClient(access_token='meowmix')
    with mock.patch.object(client, '_make_request', side_effect=_quack):
        retval = client.folders(drive_id='abcd')
        assert (retval == raw_root_folder_response)
Beispiel #5
0
def test_user_info_token():
    def _woof(method, url, headers, expects, throws):
        if method != 'GET':
            raise 'failure to match method'

        if url.endswith('/me'):
            mock_me_res = mock.Mock()
            mock_me_res.json = mock.Mock(return_value=raw_me_response)
            return mock_me_res
        elif url.endswith('/drive'):
            mock_drive_res = mock.Mock()
            mock_drive_res.json = mock.Mock(
                return_value=raw_user_personal_drive_response)
            return mock_drive_res

        raise 'failure to match url'

    client = OneDriveClient(access_token='meowmix')
    with mock.patch.object(client, '_make_request', side_effect=_woof):
        retval = client.user_info()
        assert (retval == dummy_user_info)
Beispiel #6
0
    def get_folders(self, folder_id=None, **kwargs):
        """Get list of folders underneath the folder with id ``folder_id``.  If
        ``folder_id`` is ``None``, return a single entry representing the root folder.
        In OneDrive, the root folder has a unique id, so fetch that and return it.

        This method returns a list of dicts with metadata about each folder under ``folder_id``.
        These dicts have the following properties::

            {
                'addon': 'onedrive',          # short name of the addon
                'id': folder_id,              # id of the folder.  root may need special casing
                'path': '/',                  # human-readable path of the folder
                'kind': 'folder',             # always 'folder'
                'name': '/ (Full OneDrive)',  # human readable name of the folder. root may need special casing
                'urls': {                     # urls to fetch information about the folder
                    'folders': api_v2_url(    # url to get subfolders of this folder.
                        'nodes/{}/addons/onedrive/folders/'.format(self.owner._id),
                         params={'id': folder_id}
                    ),
                }
            }

        Some providers include additional information::

        * figshare includes ``permissions``, ``hasChildren``

        * googledrive includes ``urls.fetch``

        :param str folder_id: the id of the folder to fetch subfolders of. Defaults to ``None``
        :rtype: list
        :return: a list of dicts with metadata about the subfolder of ``folder_id``.
        """

        if folder_id is None:
            return [{
                'id': DEFAULT_ROOT_ID,
                'path': '/',
                'addon': 'onedrive',
                'kind': 'folder',
                'name': '/ (Full OneDrive)',
                'urls': {
                    'folders':
                    api_v2_url('nodes/{}/addons/onedrive/folders/'.format(
                        self.owner._id),
                               params={'id': DEFAULT_ROOT_ID}),
                }
            }]

        try:
            access_token = self.fetch_access_token()
        except exceptions.InvalidAuthError:
            raise HTTPError(403)

        client = OneDriveClient(access_token)
        items = client.folders(folder_id)
        return [{
            'addon': 'onedrive',
            'kind': 'folder',
            'id': item['id'],
            'name': item['name'],
            'path': item['name'],
            'urls': {
                'folders':
                api_v2_url('nodes/{}/addons/onedrive/folders/'.format(
                    self.owner._id),
                           params={'id': item['id']}),
            }
        } for item in items]
Beispiel #7
0
def test_headers():
    client = OneDriveClient(access_token='meowmix')
    assert (client._default_headers == {'Authorization': 'Bearer meowmix'})
Beispiel #8
0
    def get_folders(self, folder_id=None, **kwargs):
        """Get list of folders underneath the folder with id ``folder_id``.  If
        ``folder_id`` is ``None``, return a single entry representing the root folder.
        In OneDrive, the root folder has a unique id, so fetch that and return it.

        This method returns a list of dicts with metadata about each folder under ``folder_id``.
        These dicts have the following properties::

            {
                'addon': 'onedrive',          # short name of the addon
                'id': folder_id,              # id of the folder.  root may need special casing
                'path': '/',                  # human-readable path of the folder
                'kind': 'folder',             # always 'folder'
                'name': '/ (Full OneDrive)',  # human readable name of the folder. root may need special casing
                'urls': {                     # urls to fetch information about the folder
                    'folders': api_v2_url(    # url to get subfolders of this folder.
                        'nodes/{}/addons/onedrive/folders/'.format(self.owner._id),
                         params={'id': folder_id}
                    ),
                }
            }

        Some providers include additional information::

        * figshare includes ``permissions``, ``hasChildren``

        * googledrive includes ``urls.fetch``

        :param str folder_id: the id of the folder to fetch subfolders of. Defaults to ``None``
        :rtype: list
        :return: a list of dicts with metadata about the subfolder of ``folder_id``.
        """

        if folder_id is None:
            return [{
                'id': DEFAULT_ROOT_ID,
                'path': '/',
                'addon': 'onedrive',
                'kind': 'folder',
                'name': '/ (Full OneDrive)',
                'urls': {
                    'folders': api_v2_url('nodes/{}/addons/onedrive/folders/'.format(self.owner._id),
                                          params={'id': DEFAULT_ROOT_ID}),
                }
            }]

        try:
            access_token = self.fetch_access_token()
        except exceptions.InvalidAuthError:
            raise HTTPError(403)

        client = OneDriveClient(access_token)
        items = client.folders(folder_id)
        return [
            {
                'addon': 'onedrive',
                'kind': 'folder',
                'id': item['id'],
                'name': item['name'],
                'path': item['name'],
                'urls': {
                    'folders': api_v2_url('nodes/{}/addons/onedrive/folders/'.format(self.owner._id),
                                          params={'id': item['id']}),
                }
            }
            for item in items
        ]