Esempio n. 1
0
    def get_folders(self, **kwargs):
        folder_id = kwargs.get('folder_id')
        if folder_id is None:
            return [{
                'id': '0',
                'path': '/',
                'addon': 'box',
                'kind': 'folder',
                'name': '/ (Full Box)',
                'urls': {
                    # 'folders': node.api_url_for('box_folder_list', folderId=0),
                    'folders': api_v2_url('nodes/{}/addons/box/folders/'.format(self.owner._id),
                        params={'id': '0'}
                    )
                }
            }]

        try:
            Provider(self.external_account).refresh_oauth_key()
            client = BoxClient(self.external_account.oauth_key)
        except BoxClientException:
            raise HTTPError(http.FORBIDDEN)

        try:
            metadata = client.get_folder(folder_id)
        except BoxClientException:
            raise HTTPError(http.NOT_FOUND)
        except MaxRetryError:
            raise HTTPError(http.BAD_REQUEST)

        # Raise error if folder was deleted
        if metadata.get('is_deleted'):
            raise HTTPError(http.NOT_FOUND)

        folder_path = '/'.join(
            [
                x['name']
                for x in metadata['path_collection']['entries']
            ] + [metadata['name']]
        )

        return [
            {
                'addon': 'box',
                'kind': 'folder',
                'id': item['id'],
                'name': item['name'],
                'path': os.path.join(folder_path, item['name']).replace('All Files', ''),
                'urls': {
                    'folders': api_v2_url('nodes/{}/addons/box/folders/'.format(self.owner._id),
                        params={'id': item['id']}
                    )
                }
            }
            for item in metadata['item_collection']['entries']
            if item['type'] == 'folder'
        ]
Esempio n. 2
0
 def absolute_api_v2_url(self):
     if self.is_registration:
         path = '/registrations/{}/'.format(self._id)
         return api_v2_url(path)
     if self.is_collection:
         path = '/collections/{}/'.format(self._id)
         return api_v2_url(path)
     path = '/nodes/{}/'.format(self._id)
     return api_v2_url(path)
Esempio n. 3
0
    def test_api_v2_url_with_port(self):
        full_url = api_v2_url('/nodes/abcd3/contributors/',
                              base_route='http://localhost:8000/',
                              base_prefix='v2/')
        assert_equal(full_url, "http://localhost:8000/v2/nodes/abcd3/contributors/")

        # Handles URL the same way whether or not user enters a leading slash
        full_url = api_v2_url('nodes/abcd3/contributors/',
                              base_route='http://localhost:8000/',
                              base_prefix='v2/')
        assert_equal(full_url, "http://localhost:8000/v2/nodes/abcd3/contributors/")
Esempio n. 4
0
    def get_folders(self, **kwargs):
        folder_id = kwargs.get('folder_id')
        if folder_id is None:
            return [{
                'addon': 'dropbox',
                'id': '/',
                'path': '/',
                'kind': 'folder',
                'name': '/ (Full Dropbox)',
                'urls': {
                    'folders': api_v2_url('nodes/{}/addons/dropbox/folders/'.format(self.owner._id),
                        params={'id': '/'}
                    )
                }
            }]

        client = DropboxClient(self.external_account.oauth_key)
        file_not_found = HTTPError(http.NOT_FOUND, data={
            'message_short': 'File not found',
            'message_long': 'The Dropbox file you requested could not be found.'
        })

        max_retry_error = HTTPError(http.REQUEST_TIMEOUT, data={
            'message_short': 'Request Timeout',
            'message_long': 'Dropbox could not be reached at this time.'
        })

        try:
            metadata = client.metadata(folder_id)
        except ErrorResponse:
            raise file_not_found
        except MaxRetryError:
            raise max_retry_error

        # Raise error if folder was deleted
        if metadata.get('is_deleted'):
            raise file_not_found

        return [
            {
                'addon': 'dropbox',
                'kind': 'folder',
                'id': item['path'],
                'name': item['path'].split('/')[-1],
                'path': item['path'],
                'urls': {
                    'folders': api_v2_url('nodes/{}/addons/box/folders/'.format(self.owner._id),
                        params={'id': item['path']}
                    )
                }
            }
            for item in metadata['contents']
            if item['is_dir']
        ]
Esempio n. 5
0
    def get_folders(self, **kwargs):
        folder_id = kwargs.get('folder_id')
        if folder_id is None:
            return [{
                'addon': 'dropbox',
                'id': '/',
                'path': '/',
                'kind': 'folder',
                'name': '/ (Full Dropbox)',
                'urls': {
                    'folders': api_v2_url('nodes/{}/addons/dropbox/folders/'.format(self.owner._id),
                        params={'id': '/'}
                    )
                }
            }]

        client = Dropbox(self.external_account.oauth_key)

        try:
            folder_id = '' if folder_id == '/' else folder_id
            list_folder = client.files_list_folder(folder_id)
            contents = [x for x in list_folder.entries]
            while list_folder.has_more:
                list_folder = client.files_list_folder_continue(list_folder.cursor)
                contents += [x for x in list_folder.entries]
        except ApiError as error:
            raise HTTPError(http.BAD_REQUEST, data={
                'message_short': error.user_message_text,
                'message_long': error.user_message_text,
            })
        except DropboxException:
            raise HTTPError(http.BAD_REQUEST)

        return [
            {
                'addon': 'dropbox',
                'kind': 'folder',
                'id': item.path_display,
                'name': item.path_display.split('/')[-1],
                'path': item.path_display,
                'urls': {
                    'folders': api_v2_url('nodes/{}/addons/dropbox/folders/'.format(self.owner._id),
                        params={'id': item.path_display}
                    )
                }
            }
            for item in contents
            if isinstance(item, FolderMetadata)
        ]
Esempio n. 6
0
def absolute_reverse(view_name, query_kwargs=None, args=None, kwargs=None):
    """Like django's `reverse`, except returns an absolute URL. Also add query parameters."""
    relative_url = reverse(view_name, kwargs=kwargs)

    url = website_util.api_v2_url(relative_url, params=query_kwargs,
                                  base_prefix=api_settings.API_PATH)
    return url
Esempio n. 7
0
    def test_node_write_scope_cant_read_user_view(self, mock_user_info):
        mock_user_info.return_value = self._scoped_response(['osf.nodes.all_write'])
        url = api_v2_url('users/me/', base_route='/', base_prefix='v2/')
        payload = {u'suffix': u'VIII'}

        res = self.app.get(url, params=payload, auth='some_valid_token', auth_type='jwt', expect_errors=True)
        assert_equal(res.status_code, 403)
Esempio n. 8
0
    def test_user_read_scope_cant_write_user_view(self, mock_user_info):
        mock_user_info.return_value = self._scoped_response(["osf.users.all_read"])
        url = api_v2_url("users/me/", base_route="/", base_prefix="v2/")
        payload = {"data": {"type": "users", "id": self.user._id, "attributes": {u"suffix": u"VIII"}}}

        res = self.app.patch_json_api(url, params=payload, auth="some_valid_token", auth_type="jwt", expect_errors=True)
        assert_equal(res.status_code, 403)
Esempio n. 9
0
    def test_node_write_scope_cant_read_user_view(self, mock_user_info):
        mock_user_info.return_value = self._scoped_response(["osf.nodes.all_write"])
        url = api_v2_url("users/me/", base_route="/", base_prefix="v2/")
        payload = {u"suffix": u"VIII"}

        res = self.app.get(url, params=payload, auth="some_valid_token", auth_type="jwt", expect_errors=True)
        assert_equal(res.status_code, 403)
Esempio n. 10
0
def get_globals():
    """Context variables that are available for every template rendered by
    OSFWebRenderer.
    """
    user = _get_current_user()
    user_institutions = [{'id': inst._id, 'name': inst.name, 'logo_path': inst.logo_path} for inst in user.affiliated_institutions] if user else []
    all_institutions = [{'id': inst._id, 'name': inst.name, 'logo_path': inst.logo_path} for inst in Institution.find().sort('name')]
    if request.host_url != settings.DOMAIN:
        try:
            inst_id = (Institution.find_one(Q('domains', 'eq', request.host.lower())))._id
            request_login_url = '{}institutions/{}'.format(settings.DOMAIN, inst_id)
        except NoResultsFound:
            request_login_url = request.url.replace(request.host_url, settings.DOMAIN)
    else:
        request_login_url = request.url
    return {
        'private_link_anonymous': is_private_link_anonymous_view(),
        'user_name': user.username if user else '',
        'user_full_name': user.fullname if user else '',
        'user_id': user._primary_key if user else '',
        'user_locale': user.locale if user and user.locale else '',
        'user_timezone': user.timezone if user and user.timezone else '',
        'user_url': user.url if user else '',
        'user_gravatar': profile_views.current_user_gravatar(size=25)['gravatar_url'] if user else '',
        'user_email_verifications': user.unconfirmed_email_info if user else [],
        'user_api_url': user.api_url if user else '',
        'user_entry_point': metrics.get_entry_point(user) if user else '',
        'user_institutions': user_institutions if user else None,
        'all_institutions': all_institutions,
        'display_name': get_display_name(user.fullname) if user else '',
        'use_cdn': settings.USE_CDN_FOR_CLIENT_LIBS,
        'piwik_host': settings.PIWIK_HOST,
        'piwik_site_id': settings.PIWIK_SITE_ID,
        'sentry_dsn_js': settings.SENTRY_DSN_JS if sentry.enabled else None,
        'dev_mode': settings.DEV_MODE,
        'allow_login': settings.ALLOW_LOGIN,
        'cookie_name': settings.COOKIE_NAME,
        'status': status.pop_status_messages(),
        'domain': settings.DOMAIN,
        'api_domain': settings.API_DOMAIN,
        'disk_saving_mode': settings.DISK_SAVING_MODE,
        'language': language,
        'noteworthy_links_node': settings.NEW_AND_NOTEWORTHY_LINKS_NODE,
        'popular_links_node': settings.POPULAR_LINKS_NODE,
        'web_url_for': util.web_url_for,
        'api_url_for': util.api_url_for,
        'api_v2_url': util.api_v2_url,  # URL function for templates
        'api_v2_base': util.api_v2_url(''),  # Base url used by JS api helper
        'sanitize': sanitize,
        'sjson': lambda s: sanitize.safe_json(s),
        'webpack_asset': paths.webpack_asset,
        'waterbutler_url': settings.WATERBUTLER_URL,
        'login_url': cas.get_login_url(request_login_url),
        'reauth_url': util.web_url_for('auth_logout', redirect_url=request.url, reauth=True),
        'profile_url': cas.get_profile_url(),
        'enable_institutions': settings.ENABLE_INSTITUTIONS,
        'keen_project_id': settings.KEEN_PROJECT_ID,
        'keen_write_key': settings.KEEN_WRITE_KEY,
        'maintenance': maintenance.get_maintenance(),
    }
Esempio n. 11
0
def oauth_application_list(auth, **kwargs):
    """Return app creation page with list of known apps. API is responsible for tying list to current user."""
    # TODO: Remove dev_only restriction when APIv2 is released into production
    app_list_url = api_v2_url("applications/")
    return {
        "app_list_url": app_list_url
    }
Esempio n. 12
0
def get_globals():
    """Context variables that are available for every template rendered by
    OSFWebRenderer.
    """
    user = _get_current_user()
    return {
        'user_name': user.username if user else '',
        'user_full_name': user.fullname if user else '',
        'user_id': user._primary_key if user else '',
        'user_url': user.url if user else '',
        'user_gravatar': profile_views.current_user_gravatar(size=25)['gravatar_url'] if user else '',
        'user_api_url': user.api_url if user else '',
        'display_name': get_display_name(user.fullname) if user else '',
        'use_cdn': settings.USE_CDN_FOR_CLIENT_LIBS,
        'piwik_host': settings.PIWIK_HOST,
        'piwik_site_id': settings.PIWIK_SITE_ID,
        'sentry_dsn_js': settings.SENTRY_DSN_JS if sentry.enabled else None,
        'dev_mode': settings.DEV_MODE,
        'allow_login': settings.ALLOW_LOGIN,
        'cookie_name': settings.COOKIE_NAME,
        'status': status.pop_status_messages(),
        'domain': settings.DOMAIN,
        'disk_saving_mode': settings.DISK_SAVING_MODE,
        'language': language,
        'web_url_for': util.web_url_for,
        'api_url_for': util.api_url_for,
        'api_v2_url': util.api_v2_url,  # URL function for templates
        'api_v2_base': util.api_v2_url(''),  # Base url used by JS api helper
        'sanitize': sanitize,
        'js_str': lambda x: x.replace("'", r"\'").replace('"', r'\"'),
        'webpack_asset': paths.webpack_asset,
        'waterbutler_url': settings.WATERBUTLER_URL,
        'login_url': cas.get_login_url(request.url, auto=True),
        'access_token': session.data.get('auth_user_access_token') or '',
    }
Esempio n. 13
0
 def test_user_email_scope_cannot_read_other_email(self, mock_user_info):
     mock_user_info.return_value = self._scoped_response(['osf.users.profile_read', 'osf.users.email_read'])
     url = api_v2_url('users/{}/'.format(self.user2._id), base_route='/', base_prefix='v2/')
     res = self.app.get(url, auth='some_valid_token', auth_type='jwt')
     assert_equal(res.status_code, 200)
     assert_not_in('email', res.json['data']['attributes'])
     assert_not_in(self.user2.username, res.json)
Esempio n. 14
0
    def test_user_read_scope_cant_write_user_view(self, mock_user_info):
        mock_user_info.return_value = self._scoped_response(['osf.users.all_read'])
        url = api_v2_url('users/me/', base_route='/', base_prefix='v2/')
        payload = {'data': {'type': 'users', 'id': self.user._id, 'attributes': {u'suffix': u'VIII'}}}

        res = self.app.patch_json_api(url, params=payload,
                             auth='some_valid_token', auth_type='jwt', expect_errors=True)
        assert_equal(res.status_code, 403)
Esempio n. 15
0
 def test_api_v2_url_with_params(self):
     """Handles- and encodes- URLs with parameters (dict and kwarg) correctly"""
     full_url = api_v2_url('/nodes/abcd3/contributors/',
                           params={'filter[fullname]': 'bob'},
                           base_route='https://api.osf.io/',
                           base_prefix='v2/',
                           page_size=10)
     assert_equal(full_url, "https://api.osf.io/v2/nodes/abcd3/contributors/?filter%5Bfullname%5D=bob&page_size=10")
Esempio n. 16
0
    def test_api_v2_url_with_port(self):
        full_url = api_v2_url('/nodes/abcd3/contributors/',
                              base_route='http://localhost:8000/',
                              base_prefix='v2/')
        assert_equal(full_url, "http://localhost:8000/v2/nodes/abcd3/contributors/")

        # Handles URL the same way whether or not user enters a leading slash
        full_url = api_v2_url('nodes/abcd3/contributors/',
                              base_route='http://localhost:8000/',
                              base_prefix='v2/')
        assert_equal(full_url, "http://localhost:8000/v2/nodes/abcd3/contributors/")

        # User is still responsible for the trailing slash. If they omit it, it doesn't appear at end of URL
        full_url = api_v2_url('/nodes/abcd3/contributors',
                              base_route='http://localhost:8000/',
                              base_prefix='v2/')
        assert_not_equal(full_url, "http://localhost:8000/v2/nodes/abcd3/contributors/")
Esempio n. 17
0
 def test_cross_origin_request_with_cookies_does_not_get_cors_headers(self):
     url = api_v2_url('users/me/')
     domain = urlparse("https://dinosaurs.sexy")
     request = self.request_factory.get(url, HTTP_ORIGIN=domain.geturl())
     response = {}
     with mock.patch.object(request, 'COOKIES', True):
         self.middleware.process_request(request)
         processed = self.middleware.process_response(request, response)
     assert_not_in('Access-Control-Allow-Origin', response)
Esempio n. 18
0
 def test_full_write_scope_can_read_guid_view_and_user_cannot_view_project(self, mock_user_info):
     project = ProjectFactory()
     mock_user_info.return_value = self._scoped_response(['osf.full_write'])
     url = api_v2_url('guids/{}/'.format(project._id), base_route='/', base_prefix='v2/')
     res = self.app.get(url, auth='some_valid_token', auth_type='jwt')
     redirect_url = '{}{}nodes/{}/'.format(API_DOMAIN, API_BASE, project._id)
     assert_equal(res.status_code, 302)
     assert_equal(res.location, redirect_url)
     redirect_res = res.follow(auth='some_valid_token', auth_type='jwt', expect_errors=True)
     assert_equal(redirect_res.status_code, 403)
Esempio n. 19
0
 def test_cross_origin_request_with_Authorization_gets_cors_headers(self):
     url = api_v2_url("users/me/")
     domain = urlparse("https://dinosaurs.sexy")
     request = self.request_factory.get(
         url, HTTP_ORIGIN=domain.geturl(), HTTP_AUTHORIZATION="Bearer aqweqweohuweglbiuwefq"
     )
     response = HttpResponse()
     self.middleware.process_request(request)
     processed = self.middleware.process_response(request, response)
     assert_equal(response["Access-Control-Allow-Origin"], domain.geturl())
Esempio n. 20
0
 def test_full_read_scope_can_read_guid_view_and_user_can_view_project(self, mock_user_info):
     project = ProjectFactory(creator=self.user)
     mock_user_info.return_value = self._scoped_response(['osf.full_read'])
     url = api_v2_url('guids/{}/'.format(project._id), base_route='/', base_prefix='v2/')
     res = self.app.get(url, auth='some_valid_token', auth_type='jwt')
     redirect_url = '{}{}nodes/{}/'.format(API_DOMAIN, API_BASE, project._id)
     assert_equal(res.status_code, 302)
     assert_equal(res.location, redirect_url)
     redirect_res = res.follow(auth='some_valid_token', auth_type='jwt')
     assert_equal(redirect_res.json['data']['attributes']['title'], project.title)
Esempio n. 21
0
 def test_user_read_scope_can_read_user_view(self, mock_user_info):
     mock_user_info.return_value = self._scoped_response(
         ['osf.users.profile_read']
     )
     url = api_v2_url('users/me/', base_route='/', base_prefix='v2/')
     res = self.app.get(
         url,
         auth='some_valid_token', auth_type='jwt',
         expect_errors=True
     )
     assert_equal(res.status_code, 200)
Esempio n. 22
0
 def test_cross_origin_request_with_Authorization_and_cookie_does_not_get_cors_headers(self):
     url = api_v2_url("users/me/")
     domain = urlparse("https://dinosaurs.sexy")
     request = self.request_factory.get(
         url, HTTP_ORIGIN=domain.geturl(), HTTP_AUTHORIZATION="Bearer aqweqweohuweglbiuwefq"
     )
     response = {}
     with mock.patch.object(request, "COOKIES", True):
         self.middleware.process_request(request)
         processed = self.middleware.process_response(request, response)
     assert_not_in("Access-Control-Allow-Origin", response)
Esempio n. 23
0
    def get_folders(self, **kwargs):
        path = kwargs.get('path')
        if path is None:
            return [{
                'addon': 'owncloud',
                'path': '/',
                'kind': 'folder',
                'id': '/',
                'name': '/ (Full ownCloud)',
                'urls': {
                    'folders': api_v2_url('nodes/{}/addons/owncloud/folders/'.format(self.owner._id),
                        params={
                            'path': '/',
                    })
                }
            }]

        provider = OwnCloudProvider(account=self.external_account)

        c = OwnCloudClient(provider.host, verify_certs=settings.USE_SSL)
        c.login(provider.username, provider.password)

        ret = []
        for item in c.list(path):
            if item.file_type is 'dir':
                ret.append({
                    'addon': 'owncloud',
                    'path': item.path,
                    'kind': 'folder',
                    'id': item.path,
                    'name': item.path.strip('/').split('/')[-1],
                    'urls': {
                        'folders': api_v2_url('nodes/{}/addons/owncloud/folders/'.format(self.owner._id),
                            params={
                                'path': item.path,
                        })

                    }
                })

        return ret
Esempio n. 24
0
    def test_deleting_token_should_hide_it_from_api_list(
            self, mock_method, app, user_one, tokens_user_one, url_token_list):
        mock_method.return_value(True)
        api_token = tokens_user_one[0]
        url = api_v2_url('tokens/{}/'.format(api_token._id), base_route='/')

        res = app.delete(url, auth=user_one.auth)
        assert res.status_code == 204

        res = app.get(url_token_list, auth=user_one.auth)
        assert res.status_code == 200
        assert (len(res.json['data']) == len(tokens_user_one) - 1)
Esempio n. 25
0
 def test_institutions_added_to_cors_whitelist(self):
     url = api_v2_url("users/me/")
     domain = urlparse("https://dinosaurs.sexy")
     institution = factories.InstitutionFactory(
         institution_domains=[domain.netloc.lower()], title="Institute for Sexy Lizards"
     )
     settings.load_institutions()
     request = self.request_factory.get(url, HTTP_ORIGIN=domain.geturl())
     response = HttpResponse()
     self.middleware.process_request(request)
     processed = self.middleware.process_response(request, response)
     assert_equal(response["Access-Control-Allow-Origin"], domain.geturl())
 def test_institutions_added_to_cors_whitelist(self):
     url = api_v2_url('users/me/')
     domain = urlparse('https://dinosaurs.sexy')
     factories.InstitutionFactory(
         domains=[domain.netloc.lower()],
         name='Institute for Sexy Lizards'
     )
     settings.load_origins_whitelist()
     request = self.request_factory.get(url, HTTP_ORIGIN=domain.geturl())
     response = HttpResponse()
     self.middleware.process_request(request)
     self.middleware.process_response(request, response)
     assert_equal(response['Access-Control-Allow-Origin'], domain.geturl())
Esempio n. 27
0
 def test_preprintproviders_added_to_cors_whitelist(self):
     url = api_v2_url('users/me/')
     domain = urlparse('https://dinoprints.sexy')
     preprintprovider = factories.PreprintProviderFactory(
         domain=domain.geturl().lower(),
         _id='DinoXiv'
     )
     settings.load_origins_whitelist()
     request = self.request_factory.get(url, HTTP_ORIGIN=domain.geturl())
     response = HttpResponse()
     self.middleware.process_request(request)
     processed = self.middleware.process_response(request, response)
     assert_equal(response['Access-Control-Allow-Origin'], domain.geturl())
Esempio n. 28
0
 def test_non_institution_preflight_request_requesting_authorization_header_gets_cors_headers(self):        
     url = api_v2_url('users/me/')
     domain = urlparse("https://dinosaurs.sexy")
     request = self.request_factory.options(
         url,
         HTTP_ORIGIN=domain.geturl(),
         HTTP_ACCESS_CONTROL_REQUEST_METHOD='GET',
         HTTP_ACCESS_CONTROL_REQUEST_HEADERS='authorization'
     )
     response = {}
     self.middleware.process_request(request)
     processed = self.middleware.process_response(request, response)
     assert_equal(response['Access-Control-Allow-Origin'], domain.geturl())
Esempio n. 29
0
def personal_access_token_detail(auth, **kwargs):
    """Show detail for a single personal access token"""
    _id = kwargs.get("_id")

    # The ID must be an active and existing record, and the logged-in user must have permission to view it.
    try:
        record = ApiOAuth2PersonalToken.find_one(Q("_id", "eq", _id))
    except NoResultsFound:
        raise HTTPError(http.NOT_FOUND)
    if record.owner != auth.user:
        raise HTTPError(http.FORBIDDEN)
    if record.is_active is False:
        raise HTTPError(http.GONE)

    token_detail_url = api_v2_url("tokens/{}/".format(_id))  # Send request to this URL
    return {"token_list_url": "", "token_detail_url": token_detail_url, "scope_options": get_available_scopes()}
Esempio n. 30
0
def oauth_application_detail(auth, **kwargs):
    """Show detail for a single OAuth application"""
    client_id = kwargs.get("client_id")

    # The client ID must be an active and existing record, and the logged-in user must have permission to view it.
    try:
        #
        record = ApiOAuth2Application.find_one(Q("client_id", "eq", client_id))
    except NoResultsFound:
        raise HTTPError(http.NOT_FOUND)
    if record.owner != auth.user:
        raise HTTPError(http.FORBIDDEN)
    if record.is_active is False:
        raise HTTPError(http.GONE)

    app_detail_url = api_v2_url("applications/{}/".format(client_id))  # Send request to this URL
    return {"app_list_url": "", "app_detail_url": app_detail_url}
Esempio n. 31
0
def personal_access_token_list(auth, **kwargs):
    """Return token creation page with list of known tokens. API is responsible for tying list to current user."""
    token_list_url = api_v2_url("tokens/")
    return {
        "token_list_url": token_list_url
    }
Esempio n. 32
0
def personal_access_token_register(auth, **kwargs):
    """Register a personal access token: blank form view"""
    token_list_url = api_v2_url("tokens/")  # POST request to this url
    return {"token_list_url": token_list_url,
            "token_detail_url": '',
            "scope_options": get_available_scopes()}
Esempio n. 33
0
 def test_api_v2_url_base_path(self):
     """Given a blank string, should return the base path (domain + port + prefix) with no extra cruft at end"""
     full_url = api_v2_url('',
                           base_route='http://localhost:8000/',
                           base_prefix='v2/')
     assert_equal(full_url, 'http://localhost:8000/v2/')
Esempio n. 34
0
 def absolute_api_v2_url(self):
     path = '/comments/{}/'.format(self._id)
     return api_v2_url(path)
Esempio n. 35
0
def _get_token_detail_route(token):
    path = "tokens/{}/".format(token._id)
    return api_v2_url(path, base_route='/')
Esempio n. 36
0
def oauth_application_list(auth, **kwargs):
    """Return app creation page with list of known apps. API is responsible for tying list to current user."""
    # TODO: Remove dev_only restriction when APIv2 is released into production
    app_list_url = api_v2_url("applications/")
    return {"app_list_url": app_list_url}
Esempio n. 37
0
 def absolute_api_v2_url(self):
     path = '/providers/registrations/{}/'.format(self._id)
     return api_v2_url(path)
Esempio n. 38
0
 def url(self, name):
     return api_v2_url('/banners/{}/'.format(name), base_prefix='_/')
 def url_token_list(self):
     return api_v2_url('tokens/', base_route='/')
 def url_token_detail(self, user_one, token_user_one):
     path = 'tokens/{}/?version={}'.format(token_user_one._id,
                                           SCOPES_RELATIONSHIP_VERSION)
     return api_v2_url(path, base_route='/')
Esempio n. 41
0
 def absolute_api_v2_url(self):
     path = '/preprint_providers/{}/'.format(self._id)
     return api_v2_url(path)
Esempio n. 42
0
 def absolute_api_v2_url(self):
     path = '/regions/{}/'.format(self._id)
     return api_v2_url(path)
Esempio n. 43
0
 def absolute_api_v2_url(self):
     path = '/applications/{}/'.format(self.client_id)
     return api_v2_url(path)
Esempio n. 44
0
 def absolute_api_v2_url(self):
     node = self.branched_from
     path = '/nodes/{}/draft_registrations/{}/'.format(node._id, self._id)
     return api_v2_url(path)
Esempio n. 45
0
def oauth_application_register(auth, **kwargs):
    """Register an API application: blank form view"""
    app_list_url = api_v2_url("applications/")  # POST request to this url
    return {"app_list_url": app_list_url,
            "app_detail_url": ''}
Esempio n. 46
0
 def institutions_relationship_url(self):
     # For NodeInstitutionsRelationshipSerializer
     path = '/draft_registrations/{}/relationships/institutions/'.format(self._id)
     return api_v2_url(path)
Esempio n. 47
0
def oauth_application_register(auth, **kwargs):
    """Register an API application: blank form view"""
    # TODO: Remove dev_only restriction when APIv2 is released into production
    app_list_url = api_v2_url("applications/")  # POST request to this url
    return {"app_list_url": app_list_url, "app_detail_url": ''}
Esempio n. 48
0
def oauth_application_list(auth, **kwargs):
    """Return app creation page with list of known apps. API is responsible for tying list to current user."""
    app_list_url = api_v2_url("applications/")
    return {
        "app_list_url": app_list_url
    }
Esempio n. 49
0
def absolute_reverse(view_name, query_kwargs=None, args=None, kwargs=None):
    """Like django's `reverse`, except returns an absolute URL. Also add query parameters."""
    relative_url = reverse(view_name, kwargs=kwargs)

    url = website_util.api_v2_url(relative_url, params=query_kwargs, base_prefix='')
    return url
Esempio n. 50
0
 def absolute_api_v2_url(self):
     return api_v2_url('taxonomies/{}/'.format(self._id))
Esempio n. 51
0
import copy
import mock

from nose.tools import *  # flake8: noqa

from website.models import User, ApiOAuth2PersonalToken
from website.util import api_v2_url
from website.util import sanitize

from tests.base import ApiTestCase
from osf_tests.factories import ApiOAuth2PersonalTokenFactory, AuthUserFactory

TOKEN_LIST_URL = api_v2_url('tokens/', base_route='/')


def _get_token_detail_route(token):
    path = "tokens/{}/".format(token._id)
    return api_v2_url(path, base_route='/')


class TestTokenList(ApiTestCase):
    def setUp(self):
        super(TestTokenList, self).setUp()

        self.user1 = AuthUserFactory()
        self.user2 = AuthUserFactory()

        self.user1_tokens = [
            ApiOAuth2PersonalTokenFactory(owner=self.user1) for i in xrange(3)
        ]
        self.user2_tokens = [
 def url_token_list(self):
     return api_v2_url(
         'tokens/?version={}'.format(SCOPES_RELATIONSHIP_VERSION),
         base_route='/')
 def url_token_detail(self, user_one, token_user_one):
     path = 'tokens/{}/'.format(token_user_one._id)
     return api_v2_url(path, base_route='/')
Esempio n. 54
0
 def get_absolute_url(self, obj):
     return api_v2_url('files/{}/'.format(obj._id))
Esempio n. 55
0
def get_globals():
    """Context variables that are available for every template rendered by
    OSFWebRenderer.
    """
    user = _get_current_user()
    return {
        'user_name':
        user.username if user else '',
        'user_full_name':
        user.fullname if user else '',
        'user_id':
        user._primary_key if user else '',
        'user_url':
        user.url if user else '',
        'user_gravatar':
        profile_views.current_user_gravatar(
            size=25)['gravatar_url'] if user else '',
        'user_api_url':
        user.api_url if user else '',
        'display_name':
        get_display_name(user.fullname) if user else '',
        'use_cdn':
        settings.USE_CDN_FOR_CLIENT_LIBS,
        'piwik_host':
        settings.PIWIK_HOST,
        'piwik_site_id':
        settings.PIWIK_SITE_ID,
        'sentry_dsn_js':
        settings.SENTRY_DSN_JS if sentry.enabled else None,
        'dev_mode':
        settings.DEV_MODE,
        'allow_login':
        settings.ALLOW_LOGIN,
        'cookie_name':
        settings.COOKIE_NAME,
        'status':
        status.pop_status_messages(),
        'domain':
        settings.DOMAIN,
        'disk_saving_mode':
        settings.DISK_SAVING_MODE,
        'language':
        language,
        'web_url_for':
        util.web_url_for,
        'api_url_for':
        util.api_url_for,
        'api_v2_url':
        util.api_v2_url,  # URL function for templates
        'api_v2_base':
        util.api_v2_url(''),  # Base url used by JS api helper
        'sanitize':
        sanitize,
        'js_str':
        lambda x: x.replace("'", r"\'").replace('"', r'\"'),
        'sjson':
        lambda s: sanitize.safe_json(s),
        'webpack_asset':
        paths.webpack_asset,
        'waterbutler_url':
        settings.WATERBUTLER_URL,
        'login_url':
        cas.get_login_url(request.url, auto=True),
        'access_token':
        session.data.get('auth_user_access_token') or '',
        'auth_url':
        cas.get_login_url(request.url),
        'profile_url':
        cas.get_profile_url(),
    }
Esempio n. 56
0
 def absolute_api_v2_subject_url(self):
     return api_v2_url('subjects/{}/'.format(self._id))
Esempio n. 57
0
def _get_application_detail_route(app):
    path = 'applications/{}/'.format(app.client_id)
    return api_v2_url(path, base_route='/')
Esempio n. 58
0
def _get_application_reset_route(app):
    path = "applications/{}/reset/".format(app.client_id)
    return api_v2_url(path, base_route='/')
Esempio n. 59
0
def _get_application_list_url():
    path = 'applications/'
    return api_v2_url(path, base_route='/')
Esempio n. 60
0
 def absolute_api_v2_url(self):
     return api_v2_url('/collections{}'.format(self.url))