repo
stringclasses 856
values | pull_number
int64 3
127k
| instance_id
stringlengths 12
58
| issue_numbers
sequencelengths 1
5
| base_commit
stringlengths 40
40
| patch
stringlengths 67
1.54M
| test_patch
stringlengths 0
107M
| problem_statement
stringlengths 3
307k
| hints_text
stringlengths 0
908k
| created_at
timestamp[s] |
---|---|---|---|---|---|---|---|---|---|
ckan/ckan | 5,985 | ckan__ckan-5985 | [
"5771"
] | 04bffb5ebb7ca4d824dda9016c055fe8422462cd | diff --git a/ckan/lib/changes.py b/ckan/lib/changes.py
--- a/ckan/lib/changes.py
+++ b/ckan/lib/changes.py
@@ -370,6 +370,24 @@ def check_metadata_changes(change_list, old, new):
_extra_fields(change_list, old, new)
+def check_metadata_org_changes(change_list, old, new):
+ '''
+ Compares two versions of a organization and records the changes between
+ them in change_list.
+ '''
+ # if the title has changed
+ if old.get(u'title') != new.get(u'title'):
+ _title_change(change_list, old, new)
+
+ # if the description of the organization changed
+ if old.get(u'description') != new.get(u'description'):
+ _description_change(change_list, old, new)
+
+ # if the image URL has changed
+ if old.get(u'image_url') != new.get(u'image_url'):
+ _image_url_change(change_list, old, new)
+
+
def _title_change(change_list, old, new):
'''
Appends a summary of a change to a dataset's title between two versions
@@ -832,3 +850,53 @@ def _extra_fields(change_list, old, new):
u'pkg_id': new.get(u'id'),
u'title': new.get(u'title'),
u'key_list': deleted_fields})
+
+
+def _description_change(change_list, old, new):
+ '''
+ Appends a summary of a change to a organization's description between two
+ versions (old and new) to change_list.
+ '''
+
+ # if the old organization had a description
+ if old.get(u'description') and new.get(u'description'):
+ change_list.append({u'type': u'description', u'pkg_id':
+ new.get(u'id'), u'title': new.get(u'title'),
+ u'new_description': new.get(u'description'),
+ u'old_description': old.get(u'description'),
+ u'method': u'change'})
+ elif not new.get(u'description'):
+ change_list.append({u'type': u'description', u'pkg_id':
+ new.get(u'id'), u'title': new.get(u'title'),
+ u'method': u'remove'})
+ else:
+ change_list.append({u'type': u'description', u'pkg_id':
+ new.get(u'id'), u'title': new.get(u'title'),
+ u'new_description': new.get(u'description'),
+ u'method': u'add'})
+
+
+def _image_url_change(change_list, old, new):
+ '''
+ Appends a summary of a change to a organization's image URL between two
+ versions (old and new) to change_list.
+ '''
+ # if both old and new versions have image URLs
+ if old.get(u'image_url') and new.get(u'image_url'):
+ change_list.append({u'type': u'image_url', u'method': u'change',
+ u'pkg_id': new.get(u'id'), u'title':
+ new.get(u'title'), u'new_image_url':
+ new.get(u'image_url'), u'old_image_url':
+ old.get(u'image_url')})
+ # if the user removed the image URL
+ elif not new.get(u'image_url'):
+ change_list.append({u'type': u'image_url', u'method': u'remove',
+ u'pkg_id': new.get(u'id'),
+ u'title': new.get(u'title'),
+ u'old_image_url': old.get(u'image_url')})
+ # if there wasn't one there before
+ else:
+ change_list.append({u'type': u'image_url', u'method': u'add',
+ u'pkg_id': new.get(u'id'),
+ u'title': new.get(u'title'),
+ u'new_image_url': new.get(u'image_url')})
diff --git a/ckan/lib/helpers.py b/ckan/lib/helpers.py
--- a/ckan/lib/helpers.py
+++ b/ckan/lib/helpers.py
@@ -2966,6 +2966,35 @@ def compare_pkg_dicts(old, new, old_activity_id):
return change_list
+@core_helper
+def compare_group_dicts(old, new, old_activity_id):
+ '''
+ Takes two package dictionaries that represent consecutive versions of
+ the same organization and returns a list of detailed & formatted summaries
+ of the changes between the two versions. old and new are the two package
+ dictionaries. The function assumes that both dictionaries will have
+ all of the default package dictionary keys, and also checks for fields
+ added by extensions and extra fields added by the user in the web
+ interface.
+
+ Returns a list of dictionaries, each of which corresponds to a change
+ to the dataset made in this revision. The dictionaries each contain a
+ string indicating the type of change made as well as other data necessary
+ to form a detailed summary of the change.
+ '''
+ from ckan.lib.changes import check_metadata_org_changes
+ change_list = []
+
+ check_metadata_org_changes(change_list, old, new)
+
+ # if the organization was updated but none of the fields we check
+ # were changed, display a message stating that
+ if len(change_list) == 0:
+ change_list.append({u'type': 'no_change'})
+
+ return change_list
+
+
@core_helper
def activity_list_select(pkg_activity_list, current_activity_id):
'''
diff --git a/ckan/views/group.py b/ckan/views/group.py
--- a/ckan/views/group.py
+++ b/ckan/views/group.py
@@ -7,6 +7,7 @@
import six
from six import string_types
from six.moves.urllib.parse import urlencode
+from datetime import datetime
import ckan.lib.base as base
import ckan.lib.helpers as h
@@ -507,6 +508,132 @@ def activity(id, group_type, is_organization, offset=0):
_get_group_template(u'activity_template', group_type), extra_vars)
+def changes(id, group_type, is_organization):
+ '''
+ Shows the changes to an organization in one particular activity stream
+ item.
+ '''
+ activity_id = id
+ context = {
+ u'model': model, u'session': model.Session,
+ u'user': g.user, u'auth_user_obj': g.userobj
+ }
+ try:
+ activity_diff = get_action(u'activity_diff')(
+ context, {u'id': activity_id, u'object_type': u'group',
+ u'diff_type': u'html'})
+ except NotFound as e:
+ log.info(u'Activity not found: {} - {}'.format(str(e), activity_id))
+ return base.abort(404, _(u'Activity not found'))
+ except NotAuthorized:
+ return base.abort(403, _(u'Unauthorized to view activity data'))
+
+ # 'group_dict' needs to go to the templates for page title & breadcrumbs.
+ # Use the current version of the package, in case the name/title have
+ # changed, and we need a link to it which works
+ group_id = activity_diff[u'activities'][1][u'data'][u'group'][u'id']
+ current_group_dict = get_action(group_type + u'_show')(
+ context, {u'id': group_id})
+ group_activity_list = get_action(group_type + u'_activity_list')(
+ context, {
+ u'id': group_id,
+ u'limit': 100
+ }
+ )
+
+ return base.render(
+ u'organization/changes.html', {
+ u'activity_diffs': [activity_diff],
+ u'group_dict': current_group_dict,
+ u'group_activity_list': group_activity_list,
+ u'group_type': current_group_dict[u'type'],
+ }
+ )
+
+
+def changes_multiple(is_organization, group_type=None):
+ '''
+ Called when a user specifies a range of versions they want to look at
+ changes between. Verifies that the range is valid and finds the set of
+ activity diffs for the changes in the given version range, then
+ re-renders changes.html with the list.
+ '''
+
+ new_id = h.get_request_param(u'new_id')
+ old_id = h.get_request_param(u'old_id')
+
+ context = {
+ u'model': model, u'session': model.Session,
+ u'user': g.user, u'auth_user_obj': g.userobj
+ }
+
+ # check to ensure that the old activity is actually older than
+ # the new activity
+ old_activity = get_action(u'activity_show')(context, {
+ u'id': old_id,
+ u'include_data': False})
+ new_activity = get_action(u'activity_show')(context, {
+ u'id': new_id,
+ u'include_data': False})
+
+ old_timestamp = old_activity[u'timestamp']
+ new_timestamp = new_activity[u'timestamp']
+
+ t1 = datetime.strptime(old_timestamp, u'%Y-%m-%dT%H:%M:%S.%f')
+ t2 = datetime.strptime(new_timestamp, u'%Y-%m-%dT%H:%M:%S.%f')
+
+ time_diff = t2 - t1
+ # if the time difference is negative, just return the change that put us
+ # at the more recent ID we were just looking at
+ # TODO: do something better here - go back to the previous page,
+ # display a warning that the user can't look at a sequence where
+ # the newest item is older than the oldest one, etc
+ if time_diff.total_seconds() < 0:
+ return changes(h.get_request_param(u'current_new_id'))
+
+ done = False
+ current_id = new_id
+ diff_list = []
+
+ while not done:
+ try:
+ activity_diff = get_action(u'activity_diff')(
+ context, {
+ u'id': current_id,
+ u'object_type': u'group',
+ u'diff_type': u'html'})
+ except NotFound as e:
+ log.info(
+ u'Activity not found: {} - {}'.format(str(e), current_id)
+ )
+ return base.abort(404, _(u'Activity not found'))
+ except NotAuthorized:
+ return base.abort(403, _(u'Unauthorized to view activity data'))
+
+ diff_list.append(activity_diff)
+
+ if activity_diff['activities'][0]['id'] == old_id:
+ done = True
+ else:
+ current_id = activity_diff['activities'][0]['id']
+
+ group_id = diff_list[0][u'activities'][1][u'data'][u'group'][u'id']
+ current_group_dict = get_action(group_type + u'_show')(
+ context, {u'id': group_id})
+ group_activity_list = get_action(group_type + u'_activity_list')(context, {
+ u'id': group_id,
+ u'limit': 100})
+
+ return base.render(
+ u'organization/changes.html', {
+ u'activity_diffs': diff_list,
+ u'group_dict': current_group_dict,
+ u'group_activity_list': group_activity_list,
+ u'group_type': current_group_dict[u'type'],
+ }
+ )
+
+
def about(id, group_type, is_organization):
extra_vars = {}
set_org(is_organization)
@@ -1200,6 +1327,10 @@ def register_group_plugin_rules(blueprint):
u'/{0}/<id>'.format(action),
methods=[u'GET', u'POST'],
view_func=globals()[action])
+ blueprint.add_url_rule(u'/changes/<id>', view_func=changes)
+ blueprint.add_url_rule(
+ u'/organization.changes_multiple',
+ view_func=changes_multiple)
register_group_plugin_rules(group)
| Organization changes do not have detailed Activity Stream UI
**CKAN version**
2.9.1
**Describe the bug**
One of the major features in 2.9 is the detailed Dataset Activity Stream. Even though Organization changes are also stored in the `activity` table, it only logs that the Organization has been updated.
**Steps to reproduce**
Make changes to an Organization and check the Activity Stream.
**Expected behavior**
The Activity Stream should at least show the diff, similar to how its done with Datasets, as the Organization metadata is stored in `activity.data` column.
| @amercader @jqnatividad , I am interested to work on this issue. I have started the investigation. | 2021-03-24T15:27:50 |
|
ckan/ckan | 5,996 | ckan__ckan-5996 | [
"5965"
] | c838dd8455cdc962c9eac2fe1321a28419db3384 | diff --git a/ckan/lib/search/__init__.py b/ckan/lib/search/__init__.py
--- a/ckan/lib/search/__init__.py
+++ b/ckan/lib/search/__init__.py
@@ -9,6 +9,7 @@
import requests
+from ckan.common import asbool, config
import ckan.model as model
import ckan.plugins as p
import ckan.logic as logic
@@ -117,7 +118,8 @@ class SynchronousSearchPlugin(p.SingletonPlugin):
p.implements(p.IDomainObjectModification, inherit=True)
def notify(self, entity, operation):
- if not isinstance(entity, model.Package):
+ if (not isinstance(entity, model.Package) or
+ not asbool(config.get('ckan.search.automatic_indexing', True))):
return
if operation != model.domain_object.DomainObjectOperation.deleted:
dispatch_by_operation(
diff --git a/ckan/plugins/core.py b/ckan/plugins/core.py
--- a/ckan/plugins/core.py
+++ b/ckan/plugins/core.py
@@ -83,7 +83,23 @@ def __iter__(self):
iterator = super(PluginImplementations, self).__iter__()
- return reversed(list(iterator))
+ plugin_lookup = {pf.name: pf for pf in iterator}
+
+ plugins_in_config = (
+ config.get('ckan.plugins', '').split() + find_system_plugins())
+
+ ordered_plugins = []
+ for pc in plugins_in_config:
+ if pc in plugin_lookup:
+ ordered_plugins.append(plugin_lookup[pc])
+ plugin_lookup.pop(pc)
+
+ if plugin_lookup:
+ # Any oustanding plugin not in the ini file (ie system ones),
+ # add to the end of the iterator
+ ordered_plugins.extend(plugin_lookup.values())
+
+ return iter(ordered_plugins)
class PluginNotFoundException(Exception):
@@ -145,12 +161,6 @@ def load_all():
unload_all()
plugins = config.get('ckan.plugins', '').split() + find_system_plugins()
- # Add the synchronous search plugin, unless already loaded or
- # explicitly disabled
- if 'synchronous_search' not in plugins and \
- asbool(config.get('ckan.search.automatic_indexing', True)):
- log.debug('Loading the synchronous search plugin')
- plugins.append('synchronous_search')
load(*plugins)
diff --git a/setup.py b/setup.py
--- a/setup.py
+++ b/setup.py
@@ -68,16 +68,11 @@
'solr = ckan.lib.search.solr_backend:SolrSearchBackend',
],
'ckan.plugins': [
- 'synchronous_search = ckan.lib.search:SynchronousSearchPlugin',
'stats = ckanext.stats.plugin:StatsPlugin',
- 'publisher_form = ckanext.publisher_form.forms:PublisherForm',
- 'publisher_dataset_form = ckanext.publisher_form.forms:PublisherDatasetForm',
'multilingual_dataset = ckanext.multilingual.plugin:MultilingualDataset',
'multilingual_group = ckanext.multilingual.plugin:MultilingualGroup',
'multilingual_tag = ckanext.multilingual.plugin:MultilingualTag',
'multilingual_resource = ckanext.multilingual.plugin:MultilingualResource',
- 'organizations = ckanext.organizations.forms:OrganizationForm',
- 'organizations_dataset = ckanext.organizations.forms:OrganizationDatasetForm',
'expire_api_token = ckanext.expire_api_token.plugin:ExpireApiTokenPlugin',
'chained_functions = ckanext.chained_functions.plugin:ChainedFunctionsPlugin',
'datastore = ckanext.datastore.plugin:DatastorePlugin',
@@ -163,6 +158,7 @@
'example_humanizer = ckanext.example_humanizer.plugin:ExampleHumanizerPlugin',
],
'ckan.system_plugins': [
+ 'synchronous_search = ckan.lib.search:SynchronousSearchPlugin',
'domain_object_mods = ckan.model.modification:DomainObjectModificationExtension',
],
'ckan.test_plugins': [
| diff --git a/ckan/tests/plugins/test_core.py b/ckan/tests/plugins/test_core.py
--- a/ckan/tests/plugins/test_core.py
+++ b/ckan/tests/plugins/test_core.py
@@ -19,3 +19,19 @@ def test_plugins_order_in_pluginimplementations():
u"example_idatasetform_v3"
]
)
+
+
[email protected](u"with_plugins")
[email protected]_config(
+ u"ckan.plugins",
+ u"example_idatasetform_v1 example_idatasetform_v3 example_idatasetform_v2")
+def test_plugins_order_in_pluginimplementations_matches_config():
+
+ assert (
+ [plugin.name for plugin in p.PluginImplementations(p.IDatasetForm)] ==
+ [
+ u"example_idatasetform_v1",
+ u"example_idatasetform_v3",
+ u"example_idatasetform_v2"
+ ]
+ )
| Templates not overriden due to plugin ordering issues in 2.9
Tl;DR:
* `PluginImplementations` return plugins in the order that their class (extending `SingletonPlugin`) is first evaluated, not when the plugin is loaded
* This causes issues like the template folders always being loaded in a particular position
* Let's ignore how pyutilib returns the plugins and always enforce the order in the ini file
---
This is related to https://github.com/ckan/ckan/issues/5731 but a different issue. The initial symptom was that some templates from `plugin1` that I was overriding from `plugin2` never got applied regardless of the ordering of `plugin2` in `ckan.plugins`. Inspecting the `config['computed_template_paths']` you could tell that the templates from `plugin1` always were loaded first than the `plugin2`, regardless of the order of the plugins in the ini file.
As with all plugin ordering issues, this order eventually boils down to the order in which plugins are returned by the [PluginImplementations](https://github.com/ckan/ckan/blob/72180ea38ca70c3178379fe0a430a2cb0e492ac2/ckan/plugins/core.py#L74) iterator (in this particular case in the one called in [`environment.py`](https://github.com/ckan/ckan/blob/72180ea38ca70c3178379fe0a430a2cb0e492ac2/ckan/config/environment.py#L173) to call the `update_config()` hook where the template dirs are registered).
pyutilib uses an internal [`_id property`](https://github.com/PyUtilib/pyutilib/blob/d99406f2af1fb62268c34453a2fbe6bd4a7348f0/pyutilib/component/core/core.py#L292) to order the output list of plugins that implement a particular interface when using `PluginImplementations`. Our assumption has always been that this order was determined by the order in which plugins were [loaded](https://github.com/ckan/ckan/blob/72180ea38ca70c3178379fe0a430a2cb0e492ac2/ckan/plugins/core.py#L158) by CKAN, and in most cases tsat is true. But the actual time this internal `_id` property is set is when the [plugin class is initialized](https://github.com/PyUtilib/pyutilib/blob/master/pyutilib/component/core/core.py#L845), ie when we define a plugin class that implements `SingletonPlugin`, eg:
```python
import ckan.plugins as p
class MyPlugin1(p.SingletonPlugin):
p.implements(ITemplateHelpers)
def get_helpers(self):
return {'plugin1_helper': plugin1_helper}
def plugin1_helper():
pass
```
That is fine if plugins don't import modules from other plugins, but if they do, when evaluating the imports they can initialize the other plugin class, and so that one will be always loaded first.
For instance:
```python
import ckan.plugins as p
from ckanext.plugin1.plugin import plugin1_helper
class MyPlugin2(p.SingletonPlugin):
#...
```
When loading `plugin2`, the imports will get processed and `MyPlugin1` will get evaluated, receiving a lower `_id` than `plugin1` and so always being returned first than `plugin1` regardless of the ordering in the ini file.
This particular case might seem like an edge case but note this is a simplified example, the imports could be in another module of `plugin2`, not necessarily `plugin.py`. The same ordering issue is happening eg when using `text_view`, which loads `resourceproxy` causing it to always come up first.
Considering how plugin ordering is and how difficult these issues are to track down, my suggestion to address this and future issues is that we enforce on the CKAN side that the order of plugins returned by `PluginImplementations` matches the ones defined in `ckan.plugins` (as in reordering the iterator returned by pyutilib based on the value of `ckan.plugins`):
```python
# on ckan/plugins/core.py
from pyutilib.component.core import ExtensionPoint
class PluginImplementations(ExtensionPoint):
def __iter__(self):
iterator = super(PluginImplementations, self).__iter__()
plugins_found = list(iterator)
plugins_in_config = config.get('ckan.plugins', '').split()
# TODO reorder plugins_found based on plugins_in_config :)
return plugins_found
```
| 2021-03-29T09:57:08 |
|
ckan/ckan | 5,999 | ckan__ckan-5999 | [
"5998"
] | 713716b0689bf848865f05acd328ded29f041c5a | diff --git a/ckan/model/__init__.py b/ckan/model/__init__.py
--- a/ckan/model/__init__.py
+++ b/ckan/model/__init__.py
@@ -266,7 +266,7 @@ def setup_migration_version_control(self):
self.reset_alembic_output()
alembic_config = AlembicConfig(self._alembic_ini)
alembic_config.set_main_option(
- "sqlalchemy.url", str(self.metadata.bind.url)
+ "sqlalchemy.url", config.get("sqlalchemy.url")
)
try:
sqlalchemy_migrate_version = self.metadata.bind.execute(
| DB INIT error when using usernames with non-alphanumeric chars
**CKAN version**
Master 713716b0689bf848865f05acd328ded29f041c5a (2.9.something)
**Describe the bug**
DB usernames with non alphanum chars will terminate in error the command `ckan db init`.
**Steps to reproduce**
Create a pg user with for instance a "`@`" in it, then update `ckan.ini` with the proper URL,
e.g.: user `ckan@ckan`:
sqlalchemy.url = postgresql://ckan@ckan:ckan@localhost/ckan_at
Running `ckan run` will not raise connection error (it won't find table, eventually).
Running `ckan db init` will terminate with the error:
invalid interpolation syntax in 'postgresql://ckan%40ckan:ckan@localhost/ckan_at' at position 17
**Expected behavior**
The command should connect to the db without errors.
**Additional details**
At https://github.com/ckan/ckan/blob/713716b0689bf848865f05acd328ded29f041c5a/ckan/model/__init__.py#L268-L270
`self.metadata.bind.url` contains `postgresql://ckan%40ckan:ckan@localhost/ckan_at`
We could replace the line with
```python
alembic_config.set_main_option(
"sqlalchemy.url", config.get("sqlalchemy.url")
)
```
| 2021-03-31T14:55:58 |
||
ckan/ckan | 6,008 | ckan__ckan-6008 | [
"4413"
] | 3ec23fec9f904019a246372e60ea228de258b6c3 | diff --git a/ckan/views/home.py b/ckan/views/home.py
--- a/ckan/views/home.py
+++ b/ckan/views/home.py
@@ -1,6 +1,6 @@
# encoding: utf-8
-from flask import Blueprint, abort
+from flask import Blueprint, abort, redirect
import ckan.model as model
import ckan.logic as logic
@@ -82,9 +82,36 @@ def about():
return base.render(u'home/about.html', extra_vars={})
+def redirect_locale(target_locale, path=None):
+ target = f'/{target_locale}/{path}' if path else f'/{target_locale}'
+ return redirect(target, code=308)
+
+
util_rules = [
(u'/', index),
(u'/about', about)
]
for rule, view_func in util_rules:
home.add_url_rule(rule, view_func=view_func)
+
+locales_mapping = [
+ ('zh_TW', 'zh_Hant_TW'),
+ ('zh_CN', 'zh_Hans_CN'),
+]
+
+for locale in locales_mapping:
+
+ legacy_locale = locale[0]
+ new_locale = locale[1]
+
+ home.add_url_rule(
+ f'/{legacy_locale}/',
+ view_func=redirect_locale,
+ defaults={'target_locale': new_locale}
+ )
+
+ home.add_url_rule(
+ f'/{legacy_locale}/<path:path>',
+ view_func=redirect_locale,
+ defaults={'target_locale': new_locale}
+ )
| diff --git a/ckan/tests/controllers/test_home.py b/ckan/tests/controllers/test_home.py
--- a/ckan/tests/controllers/test_home.py
+++ b/ckan/tests/controllers/test_home.py
@@ -117,3 +117,30 @@ def test_right_option_is_selected_on_language_selector(self, app):
assert option["selected"] == "selected"
else:
assert not option.has_attr("selected")
+
+ def test_redirects_legacy_locales(self, app):
+ locales_mapping = [
+ ('zh_TW', 'zh_Hant_TW'),
+ ('zh_CN', 'zh_Hans_CN'),
+ ]
+
+ for locale in locales_mapping:
+
+ legacy_locale = locale[0]
+ new_locale = locale[1]
+
+ response = app.get(f'/{legacy_locale}/', follow_redirects=False)
+
+ assert response.status_code == 308
+ assert (
+ response.headers['Location'] ==
+ f'http://test.ckan.net/{new_locale}'
+ )
+
+ response = app.get(f'/{legacy_locale}/dataset', follow_redirects=False)
+
+ assert response.status_code == 308
+ assert (
+ response.headers['Location'] ==
+ f'http://test.ckan.net/{new_locale}/dataset'
+ )
| Flask-Babel does not translate zh_TW and zh_CN
### CKAN Version if known (or site URL)
≧ 2.8.0
### Please describe the expected behaviour
When switching to ``zh_TW`` or ``zh_CN`` languages on the pages written in Flask (ex. ``/`` and ``/user``), the pages should be shown in corresponding languages.
### Please describe the actual behaviour
It shows English instead of ``zh_TW`` or ``zh_CN``.
### What steps can be taken to reproduce the issue?
Switch language to Chinese on the above-mentioned pages.
| The problem is caused by the ``Flask-Babel`` module which is used to translate pages written in Flask.
Pylons uses Python's ``gettext`` module which is [directory-based](https://github.com/python/cpython/blob/2.7/Lib/gettext.py#L524). However, ``Flask-Babel`` tries to find the directory containing translated strings through Babel's ``Locale.parse()`` function ([ref1](https://github.com/python-babel/flask-babel/blob/v0.11.2/flask_babel/__init__.py#L227), [ref2](https://github.com/python-babel/flask-babel/blob/v0.11.2/flask_babel/__init__.py#L243)), which "normalizes" the ``zh_TW`` and ``zh_CN`` to ``zh_Hant_TW`` and ``zh_Hans_CN`` respectively. Since there is no dirs named ``zh_Hant_TW`` and ``zh_Hans_CN``, those pages will not shown in desired languages.
A [similar situation](https://github.com/flask-admin/flask-admin/issues/403) happened on ``flask-admin`` and they decided to rename the dirs. But I think renaming dirs will break backwards compatibility in CKAN if people bookmark urls with old ``/zh_TW`` or ``/zh_CN`` path. Any ideas or suggestions are welcomed.
@u10313335 Please check #4402. I think its fixing this issue
@tino097 thanks. But #4402 is about the "label" shown on the language switcher. The problem I have described in this issue is the language of a CKAN site.
Sorry, i didnt read your comment, just went through the issue description :/
flask-babel needs to allow passing through args to babel.parse, specifically `resolve_likely_subtags=False` would fix this problem.
@TkTech thanks.
But I got the ``babel.core.UnknownLocaleError: unknown locale 'zh_TW'`` exception after setting ``resolve_likely_subtags=False``.
@TkTech any pointers on how to progress with this?
I didn't change resolve_likely_subtags=False
I just cp zh_CN(or zh_TW) zh_Hans_CN(zh_Hant_TW)
And it works!
@ltf9651 You should set the ``resolve_likely_subtags`` argument to babel.parse in flask-babel just like @TkTech said. However, I have tried that but no luck.
And, renaming dirs resolve this issue but it will break backwards compatibility in CKAN if people bookmark urls with old /zh_TW or /zh_CN path.
Please refer to my previous comment here: https://github.com/ckan/ckan/issues/4413#issuecomment-414532805
@u10313335
cd /ckan/i18n
copy zh_CN zh_Hans_CN
My problem fixed, you should have a try
@ltf9651 I know that renaming dirs will resolve this issue. But it will break the links with /zh_TW or /zh_CN in the older versions of CKAN.
>
>
> @u10313335
> cd /ckan/i18n
> copy zh_CN zh_Hans_CN
> My problem fixed, you should have a try
It does work properly, thanks
>
>
> @u10313335
> cd /ckan/i18n
> copy zh_CN zh_Hans_CN
> My problem fixed, you should have a try
Thanks. It is working.
>
>
> @ltf9651 I know that renaming dirs will resolve this issue. But it will break the links with /zh_TW or /zh_CN in the older versions of CKAN.
The links remain zh_CN or zh_TW when using the workaround above provided by @u10313335.
For example, the URL is http://127.0.0.1:5000/zh_CN/dataset/example_xxx_dataset
rather than http://127.0.0.1:5000/zh_Hans_CN/dataset/example_xxx_dataset
When switch the language to zh_CN, an error occurs with the details page of an organization:
...
File "/usr/local/lib64/python3.6/site-packages/markupsafe/init.py", line 249, in getitem
return self._kwargs[key]
KeyError: 'organization'
[**Note**:
_This is the only problem After renaming the the locale folder 'zh_CN' to 'zh_Hans_CN' and Update the locale name from 'zh_CN' to 'zh_Hans_CN' in the config file ckan.ini but not changing any other things. That is to say, everything is okay but displaying the details page of an organization in this locale and the page can be normally displayed in the other locales._
The page shows "Error [500] - CKAN" on the page tile bar and "Internal server error " in the section of the oganization details.
]
The details page of an organization is okay when switch the language to other language such as ja or zh_TW.
And ckan/i18n uses the folder named 'zh_Hans_CN' and 'zh_Hans_TW'.
But the po and mo files remain intact as the original files released by the CKAN GitHub project.
The error is still there even after the database has been cleared and initialized.
It's okay with other languages such as en, ja or zh_TW.
> I didn't change resolve_likely_subtags=False
> I just cp zh_CN(or zh_TW) zh_Hans_CN(zh_Hant_TW)
> And it works!
Did you encounter the internal server error about showing the details page of an organization?
> The problem is caused by the `Flask-Babel` module which is used to translate pages written in Flask.
> ... Any ideas or suggestions are welcomed.
Is there any solution or workaround for this issue? Thanks.
>
>
> flask-babel needs to allow passing through args to babel.parse, specifically `resolve_likely_subtags=False` would fix this problem.
@u10313335
How to set resolve_likely_subtags=False? The python file 'core.py' in the folder '/usr/local/lib/python3.6/site-packages/Babel'? Thanks
Workaround to be fully evaluated:
Temporarily COMMENT the line for calling the feeds snippet in the read-base of "organization". That's all. Any idea or suggestion? THX.
The formal solution seems within the snippet feeds.html | 2021-04-09T11:58:02 |
ckan/ckan | 6,019 | ckan__ckan-6019 | [
"6018"
] | f8d26482f6c0164a8f6b3b3b0b627df529fedef0 | diff --git a/ckan/views/feed.py b/ckan/views/feed.py
--- a/ckan/views/feed.py
+++ b/ckan/views/feed.py
@@ -174,7 +174,7 @@ def output_feed(results, feed_title, feed_description, feed_link, feed_url,
title=pkg.get(u'title', u''),
link=h.url_for(
u'api.action',
- logic_function=u'package_read',
+ logic_function=u'package_show',
id=pkg['id'],
ver=3,
_external=True),
| RSS Feed uses package_read instead of package_show
**CKAN version**
2.8.6
Seems to be present in master
**Describe the bug**
RSS output generated by feed results in:
"Bad request - Action name not known: package_read"
Due to package_read being used instead of package_show
https://github.com/ckan/ckan/blob/f8d26482f6c0164a8f6b3b3b0b627df529fedef0/ckan/views/feed.py#L177
**Steps to reproduce**
Configure RSS feed for organization or dataset
**Expected behavior**
RSS reader should direct user to organization/dataset
**Additional details**
Sample XML
```
<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en"><title>CKAN - Custom query</title><link href="/dataset?query=q&query=name%3Araw-leaf-tobacco-registrant-list" rel="alternate"></link><link href="/feeds/custom.atom?query=q&query=name%3Araw-leaf-tobacco-registrant-list" rel="self"></link><id>http://localhost/feeds/custom.atom</id><updated>2021-04-09T18:04:21Z</updated><author><name>default</name></author><subtitle>Recently created or updated datasets on CKAN. Custom query: 'name:raw-leaf-tobacco-registrant-list'</subtitle><link href="/feeds/custom.atom?query=q&query=name%3Araw-leaf-tobacco-registrant-list" rel="first"></link><link href="/feeds/custom.atom?query=page&query=1" rel="last"></link><entry><title>Raw leaf tobacco registrant list</title><link href="http://localhost/api/3/action/package_read?id=12a41b0f-3e51-4652-9756-962909b7fd78" rel="alternate"></link><author><name></name><email></email></author><id>http://localhost/dataset/12a41b0f-3e51-4652-9756-962909b7fd78</id><summary type="html">This list allows you to identify legal entities authorized by the Minister of
Finance, under the [Tobacco Tax Act](https://www.ontario.ca/laws/statute/90t10), to process, sell,
distribute, import, export and transport raw leaf tobacco products.
Raw leaf tobacco includes all varieties of unmanufactured tobacco grown in or
brought into Ontario, including flue‑cured, dark‑fire‑cured/dark‑air‑cured
(also known as black) and burley tobacco.
Registrants on this list hold a valid registration certificate, permit or
designation.
This data includes:
* name and address of legal entity
* whether the legal entity is a processor, dealer, importer/exporter of raw leaf tobacco
* whether the legal entity has an Interjurisdictional Transporter Registration Certificate
* the date any changes were made to the legal entity's registrant data, if applicable.
</summary><link length="15702" href="http://localhost/api/3/action/package_show?id=raw-leaf-tobacco-registrant-list" type="application/json" rel="enclosure"></link><category term="Economy and Business"></category><category term="Gouvernement et finances"></category><category term="Government and Finance"></category><category term="Impôts et avantages fiscaux"></category><category term="Taxes and benefits"></category><category term="Économie et affaires"></category><updated>2021-04-09T18:04:21Z</updated><published>2021-03-09T18:58:47Z</published></entry></feed>
```
| 2021-04-13T20:32:22 |
||
ckan/ckan | 6,031 | ckan__ckan-6031 | [
"6030"
] | abfda8b401ec370c9c74fc67678dcb38f8c72a26 | diff --git a/ckan/views/user.py b/ckan/views/user.py
--- a/ckan/views/user.py
+++ b/ckan/views/user.py
@@ -661,14 +661,18 @@ def post(self):
h.flash_error(_(u'Error sending the email. Try again later '
'or contact an administrator for help'))
log.exception(e)
- return h.redirect_to(u'home.index')
+ return h.redirect_to(config.get(
+ u'ckan.user_reset_landing_page',
+ u'home.index'))
# always tell the user it succeeded, because otherwise we reveal
# which accounts exist or not
h.flash_success(
_(u'A reset link has been emailed to you '
'(unless the account specified does not exist)'))
- return h.redirect_to(u'home.index')
+ return h.redirect_to(config.get(
+ u'ckan.user_reset_landing_page',
+ u'home.index'))
def get(self):
self._prepare()
@@ -734,7 +738,9 @@ def post(self, id):
mailer.create_reset_key(context[u'user_obj'])
h.flash_success(_(u'Your password has been reset.'))
- return h.redirect_to(u'home.index')
+ return h.redirect_to(config.get(
+ u'ckan.user_reset_landing_page',
+ u'home.index'))
except logic.NotAuthorized:
h.flash_error(_(u'Unauthorized to edit user %s') % id)
except logic.NotFound:
| Password reset doesn't work well with external homepage hosting
**CKAN version**
2.8, 2.9
**Describe the bug**
After requesting or performing a password reset, there is a hardcoded redirect to the homepage. This works so long as CKAN is using its own homepage, but if the site owner chooses to host the homepage externally on a CDN, then it will be unable to display or consume the flash messages.
It would be good to have an option to make the target of this redirect configurable for sites that need it.
Will open a pull request soon with this functionality.
| 2021-04-20T06:56:39 |
||
ckan/ckan | 6,040 | ckan__ckan-6040 | [
"5915"
] | e25a0e53541a54bdfeeae6cbb13280810e2de0d5 | diff --git a/ckan/views/group.py b/ckan/views/group.py
--- a/ckan/views/group.py
+++ b/ckan/views/group.py
@@ -513,6 +513,8 @@ def changes(id, group_type, is_organization):
Shows the changes to an organization in one particular activity stream
item.
'''
+ set_org(is_organization)
+ extra_vars = {}
activity_id = id
context = {
u'model': model, u'session': model.Session,
@@ -541,14 +543,14 @@ def changes(id, group_type, is_organization):
}
)
- return base.render(
- u'organization/changes.html', {
- u'activity_diffs': [activity_diff],
- u'group_dict': current_group_dict,
- u'group_activity_list': group_activity_list,
- u'group_type': current_group_dict[u'type'],
- }
- )
+ extra_vars = {
+ u'activity_diffs': [activity_diff],
+ u'group_dict': current_group_dict,
+ u'group_activity_list': group_activity_list,
+ u'group_type': current_group_dict[u'type'],
+ }
+
+ return base.render(_replace_group_org(u'group/changes.html'), extra_vars)
def changes_multiple(is_organization, group_type=None):
@@ -558,7 +560,8 @@ def changes_multiple(is_organization, group_type=None):
activity diffs for the changes in the given version range, then
re-renders changes.html with the list.
'''
-
+ set_org(is_organization)
+ extra_vars = {}
new_id = h.get_request_param(u'new_id')
old_id = h.get_request_param(u'old_id')
@@ -624,14 +627,14 @@ def changes_multiple(is_organization, group_type=None):
u'id': group_id,
u'limit': 100})
- return base.render(
- u'organization/changes.html', {
- u'activity_diffs': diff_list,
- u'group_dict': current_group_dict,
- u'group_activity_list': group_activity_list,
- u'group_type': current_group_dict[u'type'],
- }
- )
+ extra_vars = {
+ u'activity_diffs': diff_list,
+ u'group_dict': current_group_dict,
+ u'group_activity_list': group_activity_list,
+ u'group_type': current_group_dict[u'type'],
+ }
+
+ return base.render(_replace_group_org(u'group/changes.html'), extra_vars)
def about(id, group_type, is_organization):
@@ -1329,7 +1332,7 @@ def register_group_plugin_rules(blueprint):
view_func=globals()[action])
blueprint.add_url_rule(u'/changes/<id>', view_func=changes)
blueprint.add_url_rule(
- u'/organization.changes_multiple',
+ u'/changes_multiple',
view_func=changes_multiple)
| Groups Activity Stream do not have detailed "changes" in UI
**CKAN version**
2.9
**Describe the bug**
If there is any change in Groups, it only logs that the Groups has been updated.
**Steps to reproduce**
Make changes to a Group and check the Activity Stream.
**Expected behavior**
The Groups Activity Stream should show the differences.
**Additional details**
This is similar to Dataset detailed Activity Stream.
| Only datasets currently have detailed changes view and this needs an implementation similarly as in #5771.
@Zharktas, I am working on this issue. | 2021-04-22T07:27:22 |
|
ckan/ckan | 6,042 | ckan__ckan-6042 | [
"5973"
] | e25a0e53541a54bdfeeae6cbb13280810e2de0d5 | diff --git a/ckan/logic/schema.py b/ckan/logic/schema.py
--- a/ckan/logic/schema.py
+++ b/ckan/logic/schema.py
@@ -102,7 +102,7 @@ def default_create_tag_schema(
def default_create_package_schema(
duplicate_extras_key, ignore, empty_if_not_sysadmin, ignore_missing,
unicode_safe, package_id_does_not_exist, not_empty, name_validator,
- package_name_validator, if_empty_same_as, email_validator,
+ package_name_validator, if_empty_same_as, strip_value, email_validator,
package_version_validator, ignore_not_package_admin,
boolean_validator, datasets_with_no_organization_cannot_be_private,
empty, tag_string_convert, owner_org_validator, no_http):
@@ -114,9 +114,11 @@ def default_create_package_schema(
not_empty, unicode_safe, name_validator, package_name_validator],
'title': [if_empty_same_as("name"), unicode_safe],
'author': [ignore_missing, unicode_safe],
- 'author_email': [ignore_missing, unicode_safe, email_validator],
+ 'author_email': [ignore_missing, unicode_safe, strip_value,
+ email_validator],
'maintainer': [ignore_missing, unicode_safe],
- 'maintainer_email': [ignore_missing, unicode_safe, email_validator],
+ 'maintainer_email': [ignore_missing, unicode_safe, strip_value,
+ email_validator],
'license_id': [ignore_missing, unicode_safe],
'notes': [ignore_missing, unicode_safe],
'url': [ignore_missing, unicode_safe],
@@ -386,7 +388,7 @@ def default_update_relationship_schema(
def default_user_schema(
ignore_missing, unicode_safe, name_validator, user_name_validator,
user_password_validator, user_password_not_empty, email_is_unique,
- ignore_not_sysadmin, not_empty, email_validator,
+ ignore_not_sysadmin, not_empty, strip_value, email_validator,
user_about_validator, ignore, boolean_validator, json_object):
return {
'id': [ignore_missing, unicode_safe],
@@ -396,7 +398,8 @@ def default_user_schema(
'password': [user_password_validator, user_password_not_empty,
ignore_missing, unicode_safe],
'password_hash': [ignore_missing, ignore_not_sysadmin, unicode_safe],
- 'email': [not_empty, email_validator, email_is_unique, unicode_safe],
+ 'email': [not_empty, strip_value, email_validator, email_is_unique,
+ unicode_safe],
'about': [ignore_missing, user_about_validator, unicode_safe],
'created': [ignore],
'sysadmin': [ignore_missing, ignore_not_sysadmin],
@@ -445,13 +448,13 @@ def user_edit_form_schema(
def default_update_user_schema(
ignore_missing, name_validator, user_name_validator,
unicode_safe, user_password_validator, email_is_unique,
- not_empty, email_validator):
+ not_empty, strip_value, email_validator):
schema = default_user_schema()
schema['name'] = [
ignore_missing, name_validator, user_name_validator, unicode_safe]
schema['email'] = [
- not_empty, email_validator, email_is_unique, unicode_safe]
+ not_empty, strip_value, email_validator, email_is_unique, unicode_safe]
schema['password'] = [
user_password_validator, ignore_missing, unicode_safe]
diff --git a/ckan/logic/validators.py b/ckan/logic/validators.py
--- a/ckan/logic/validators.py
+++ b/ckan/logic/validators.py
@@ -883,6 +883,11 @@ def empty_if_not_sysadmin(key, data, errors, context):
)
+def strip_value(value):
+ '''Trims the Whitespace'''
+ return value.strip()
+
+
def email_validator(value, context):
'''Validate email input '''
| diff --git a/ckan/tests/logic/test_validators.py b/ckan/tests/logic/test_validators.py
--- a/ckan/tests/logic/test_validators.py
+++ b/ckan/tests/logic/test_validators.py
@@ -294,6 +294,21 @@ def call_validator(*args, **kwargs):
call_validator(valid_value)
+def test_strip_value_with_valid_value():
+ valid_values = [
+ " [email protected]",
+ " [email protected]",
+ "[email protected] ",
+ "[email protected] ",
+ " [email protected] ",
+ " [email protected] ",
+ ]
+
+ for valid_value in valid_values:
+
+ assert validators.strip_value(valid_value) == "[email protected]"
+
+
def test_name_validator_with_valid_value():
"""If given a valid string name_validator() should do nothing and
return the string.
| Email validators block email addressees with space at the end
**CKAN version**
2.9.2
**Describe the bug**
If you enter email address with space at the end, validators don't allow it.
IT isn't major problem, but it would be nice if address can be trimmed before validating and saving..
**Steps to reproduce**
Steps to reproduce the behavior:
When creating new dataset in author email enter address with space at the end (or start) " [email protected] "
**Expected behavior**
Trim data before validation and saving
**Additional details**
For me this is big issue because i am harvesting data from older portals which don't have email validation, and some of resources are failing because they have spaces in email addresses..
IT can be fixed in harvester but i think this is better place..
| @VladimirZD that makes sense. Actually a generic `trim_value` validator that is applied in most text fields would be a really good addition.
In the meantime you can implement a [custom schema](https://github.com/ckan/ckanext-scheming) for your extension and add the trim validator to the email field.
@amercader @VladimirZD , I am interested to work on this issue. I have investigated and found that Email validators not only block email addresses with space at the end but also blocks email addresses starting with the space.
@Gauravp-NEC here's what I would suggest:
* Create a new `strip_value` validator in `validators.py` that trims whitespace at either end of the provided value. Something simple like:
```python
def strip_value(value):
return value.strip()
```
* Add it to the relevant (all?) text fields in the [dataset schema](https://github.com/ckan/ckan/blob/3ec23fec9f904019a246372e60ea228de258b6c3/ckan/logic/schema.py#L102) (and you can also add them to other schemas like the group, user, etc)
* Add a couple of tests in [test_validators.py](https://github.com/ckan/ckan/blob/master/ckan/tests/logic/test_validators.py)
@amercader , Thankyou for your suggestion.
I want to know why there is a need of strip_value in group schema?
https://github.com/ckan/ckan/blob/3ec23fec9f904019a246372e60ea228de258b6c3/ckan/logic/schema.py#L247-L250 | 2021-04-22T08:18:18 |
ckan/ckan | 6,057 | ckan__ckan-6057 | [
"6028"
] | 67376681491f2808fae56920f757c4b594b58284 | diff --git a/ckan/model/activity.py b/ckan/model/activity.py
--- a/ckan/model/activity.py
+++ b/ckan/model/activity.py
@@ -225,8 +225,7 @@ def _group_activity_query(group_id, include_hidden_activity=False):
).outerjoin(
model.Package,
and_(
- or_(model.Package.id == model.Member.table_id,
- model.Package.owner_org == group_id),
+ model.Package.id == model.Member.table_id,
model.Package.private == False,
)
).filter(
| diff --git a/ckan/tests/logic/action/test_get.py b/ckan/tests/logic/action/test_get.py
--- a/ckan/tests/logic/action/test_get.py
+++ b/ckan/tests/logic/action/test_get.py
@@ -4338,14 +4338,44 @@ def test_activities_on_a_dataset_in_a_followed_group(self):
user = factories.User()
another_user = factories.Sysadmin()
group = factories.Group(user=user)
+ helpers.call_action(
+ "follow_group", context={"user": user["name"]}, **group
+ )
_clear_activities()
dataset = factories.Dataset(
groups=[{"name": group["name"]}], user=another_user
)
dataset["title"] = "Dataset with changed title"
helpers.call_action(
- "follow_dataset", context={"user": user["name"]}, **dataset
+ "package_update", context={"user": another_user["name"]}, **dataset
)
+
+ activities = helpers.call_action(
+ "dashboard_activity_list", context={"user": user["id"]}
+ )
+ assert [
+ (activity["activity_type"], activity["is_new"])
+ for activity in activities[::-1]
+ ] == [("new package", True), ("changed package", True)]
+ assert (
+ helpers.call_action(
+ "dashboard_new_activities_count", context={"user": user["id"]}
+ )
+ == 2
+ )
+
+ def test_activities_on_a_dataset_in_a_followed_org(self):
+ user = factories.User()
+ another_user = factories.Sysadmin()
+ org = factories.Organization(user=user)
+ helpers.call_action(
+ "follow_group", context={"user": user["name"]}, **org
+ )
+ _clear_activities()
+ dataset = factories.Dataset(
+ owner_org=org['id'], user=another_user
+ )
+ dataset["title"] = "Dataset with changed title"
helpers.call_action(
"package_update", context={"user": another_user["name"]}, **dataset
)
| Activity queries getting slow (~15 seconds) when following entities.
## CKAN version
Tested in 2.9.2 but probably also happening in master
## Describe the bug
`<lib/helpers.py:2567(new_activities)>` spikes to ~15 seconds if the user is following 2 or 3 organizations (with around 200 datasets each) in a ~1000+ dataset system. This makes the system unusable since this helper is called in almost every request to the UI.
**Without following organizations (50 ms):**
Calls | Total Time (ms) | Per Call (ms) | Cumulative Time (ms) | Per Call (ms) | Function
-- | -- | -- | -- | -- | --
1 | 0.005 | 0.0050 | 52.439 | 52.4390 | <lib/helpers.py:2567(new_activities)>
1 | 0.006 | 0.0060 | 52.374 | 52.3740 | <logic/action/get.py:3216(dashboard_new_activities_count)>
1 | 0.016 | 0.0160 | 50.164 | 50.1640 | <ckanext/gdx/logic/action.py:418(dashboard_activity_list)>
**Following 3 organizations with 100 datasets each (1500 ms):**
Calls | Total Time (ms) | Per Call (ms) | Cumulative Time (ms) | Per Call (ms) | Function
-- | -- | -- | -- | -- | --
1 | 0.01 | 0.0100 | 1610.417 | 1610.4170 | <lib/helpers.py:2567(new_activities)>
1 | 0.018 | 0.0180 | 1610.26 | 1610.2600 | <logic/action/get.py:3216(dashboard_new_activities_count)>
1 | 0.031 | 0.0310 | 1605.896 | 1605.8960 | <ckanext/gdx/logic/action.py:418(dashboard_activity_list)>
## Steps to reproduce
Steps to reproduce the behavior:
- Create 3 organizations
- Add ~100 datasets to each one (enough to test)
- Login with a user
- Open the home page
- Using flask debug toolbar's profiler measure the response time of the activity related methods: `<lib/helpers.py:2567(new_activities)>`
- It should be around `50 ms`
- Now follow the 3 organizations
- Refresh the web page
- The call to `<lib/helpers.py:2567(new_activities)>` it's now in 1500 ms (it will scale to ~20 seconds with a bigger database)
## Expected behavior
The response time of the new activities feature will not impact on the UX of the site. (A delay time of ~100 ms?)
## Additional details
The issue seems to be related to two main factors:
1. How the overall logic to get the new activities count is being made
2. How the internal queries to the activity models are being made
**1. New Activities logic:**
The logic queries everything from the database and then uses some business logic in the action layer to filter results. Even when this approach may be fine in most cases, it is creating a bottleneck in the database for this feature.
Example: Even when activities from the users [are not counted](https://github.com/ckan/ckan/blob/abfda8b401ec370c9c74fc67678dcb38f8c72a26/ckan/logic/action/get.py#L3235), it [queries them](https://github.com/ckan/ckan/blob/abfda8b401ec370c9c74fc67678dcb38f8c72a26/ckan/model/activity.py#L413) from the database, and then adds some logic to the returned dictionary to [filter the count](https://github.com/ckan/ckan/blob/abfda8b401ec370c9c74fc67678dcb38f8c72a26/ckan/logic/action/get.py#L3218).
**2. Internal queries**
The logic to get activities from the database is a little bit complicated and not optimized. For each type of entity it:
- Get every followee object (user following X object)
- Creates and executes a select query for each of the previous objects
- Creates a union of all the previous queries
https://github.com/ckan/ckan/blob/abfda8b401ec370c9c74fc67678dcb38f8c72a26/ckan/model/activity.py#L346-L358
I played a little bit with queries. Instead of doing a union of select results, if I do a select filtering by id and the time of the query is reduced to a half (although It's not enough to reduce the time for a good UX).
```python
def _activities_from_datasets_followed_by_user_query(user_id, limit):
'''Return a query for all activities from datasets that user_id follows.'''
import ckan.model as model
# Get a list of the datasets that the user is following.
follower_objects = model.UserFollowingDataset.followee_list(user_id)
if not follower_objects:
# Return a query with no results.
return model.Session.query(model.Activity).filter(text('0=1'))
packages_id = set([f.object_id for f in follower_objects])
return model.Session.query(model.Activity).\
filter(model.Activity.object_id.in_(packages_id)).\
limit(limit)
```
| +1 for rewriting the activity queries for each specific use case. This would let us optimize for each case and identify query improvements and missing indexes to improve performance.
Like our other APIs activities are not using index-based pagination. Now might be a great time to switch to index-based (activity date in this case) pagination and stop using integer offsets in queries which are much slower to generate on the db side.
Many of the queries have filters like "endswith('_package')" which might be slow to compute.
For the specific case of showing the number of new activities on each page in ckan we should also consider caching this value per-user to speed up page load times. If the cache stores the last activity date along with the number it can be ignored and recomputed only when there is the potential for a new activity, when a user visits their feed the cache can be cleared explicitly. | 2021-04-29T12:02:00 |
ckan/ckan | 6,058 | ckan__ckan-6058 | [
"6054"
] | d013f8455c95064c07d33fc2a4b3e973e31ed5e8 | diff --git a/ckan/lib/helpers.py b/ckan/lib/helpers.py
--- a/ckan/lib/helpers.py
+++ b/ckan/lib/helpers.py
@@ -2735,7 +2735,7 @@ def resource_formats():
os.path.dirname(os.path.realpath(ckan.config.__file__)),
'resource_formats.json'
)
- with open(format_file_path) as format_file:
+ with open(format_file_path, encoding='utf-8') as format_file:
try:
file_resource_formats = json.loads(format_file.read())
except ValueError as e:
| UTF-8 not supported in resource_formats.json
**CKAN version**
CKAN 2.9.2
Ubuntu 18.04
Python 3.6
**Describe the bug**
When trying to upload a resource I get a message "Internal server error".
The log file reveals an error that occurs when resource_formats.json is loaded:
`ValueError: Invalid JSON syntax in /usr/lib/ckan/default/src/ckan/ckan/config/resource_formats.json: 'ascii' codec can't decode byte 0xc2 in position 4411: ordinal not in range(128)`.
The problem seems to be caused by utf-8 characters in the JSON file.
**Steps to reproduce**
- Add utf-8 characters to resource_formats.json
- Upload resource
**Expected behavior**
The resource is uploaded without error log
**Additional details**
It seems that JSON files are not loaded as utf-8 by default and that you have to specify the encoding (according to https://stackoverflow.com/a/35052042/395879).
The relevant code is probably `ckan/lib/helpers.py` in line 2685:
```python
with open(format_file_path) as format_file:
try:
file_resource_formats = json.loads(format_file.read())
```
Stack trace:
```
File "/usr/lib/ckan/default/src/ckan/ckan/logic/action/update.py", line 295, in package_update
package_plugin, context, data_dict, schema, 'package_update')
File "/usr/lib/ckan/default/src/ckan/ckan/lib/plugins.py", line 306, in plugin_validate
return toolkit.navl_validate(data_dict, schema, context)
File "/usr/lib/ckan/default/src/ckan/ckan/lib/navl/dictization_functions.py", line 273, in validate
converted_data, errors = _validate(flattened, schema, validators_context)
File "/usr/lib/ckan/default/src/ckan/ckan/lib/navl/dictization_functions.py", line 314, in _validate
convert(converter, key, converted_data, errors, context)
File "/usr/lib/ckan/default/src/ckan/ckan/lib/navl/dictization_functions.py", line 224, in convert
value = converter(converted_data.get(key))
File "/usr/lib/ckan/default/src/ckan/ckan/logic/validators.py", line 798, in clean_format
return h.unified_resource_format(format)
File "/usr/lib/ckan/default/src/ckan/ckan/lib/helpers.py", line 2713, in unified_resource_format
formats = resource_formats()
File "/usr/lib/ckan/default/src/ckan/ckan/lib/helpers.py", line 2691, in resource_formats
(format_file_path, e))
ValueError: Invalid JSON syntax in /usr/lib/ckan/default/src/ckan/ckan/config/resource_formats.json: 'ascii' codec can't decode byte 0xc2 in position 4411: ordinal not in range(128)
```
| 2021-04-30T08:38:19 |
||
ckan/ckan | 6,076 | ckan__ckan-6076 | [
"6006"
] | 65be1da5dbe763025eed93f06e065d1177005211 | diff --git a/ckan/views/group.py b/ckan/views/group.py
--- a/ckan/views/group.py
+++ b/ckan/views/group.py
@@ -1036,18 +1036,13 @@ def post(self, group_type, is_organization, id=None):
u'has been deleted') or _(u'Group')
h.flash_notice(
_(u'%s has been deleted.') % _(group_label))
- group_dict = _action(u'group_show')(context, {u'id': id})
except NotAuthorized:
base.abort(403, _(u'Unauthorized to delete group %s') % u'')
except NotFound:
base.abort(404, _(u'Group not found'))
except ValidationError as e:
h.flash_error(e.error_dict['message'])
- return h.redirect_to(u'organization.read', id=id)
-
return h.redirect_to(u'{}.read'.format(group_type), id=id)
- # TODO: Remove
- g.group_dict = group_dict
return h.redirect_to(u'{}.index'.format(group_type))
| diff --git a/ckan/tests/controllers/test_group.py b/ckan/tests/controllers/test_group.py
--- a/ckan/tests/controllers/test_group.py
+++ b/ckan/tests/controllers/test_group.py
@@ -287,6 +287,7 @@ def test_owner_delete(self, app, initial_data):
data={"delete": ""},
extra_environ=initial_data["user_env"],
)
+ assert response.status_code == 200
group = helpers.call_action(
"group_show", id=initial_data["group"]["id"]
)
@@ -300,6 +301,7 @@ def test_sysadmin_delete(self, app, initial_data):
data={"delete": ""},
extra_environ=extra_environ,
)
+ assert response.status_code == 200
group = helpers.call_action(
"group_show", id=initial_data["group"]["id"]
)
| Authorization error when a non-sysadmin user deletes a group/org
**CKAN version**
\>=2.7
**Describe the bug**
When a non-sysadmin user deletes a group or organization, they get a 403 Not Authorized error. The group/org gets actually deleted.
This is because after deleting the group/org we are calling `group_show` on the deleted entity:
https://github.com/ckan/ckan/blob/170556a97f38d42b94474943ccab4cef19fd9d49/ckan/views/group.py#L1039
AFAICT we are not using this `group_dict` at all so it can be removed.
The tests in place didn't check the status code returned so that's why it slipped unnoticed.
| 2021-05-10T10:02:01 |
|
ckan/ckan | 6,087 | ckan__ckan-6087 | [
"6086"
] | 93ef47244b01db097cd65494677296234a4d37d6 | diff --git a/ckanext/datastore/backend/postgres.py b/ckanext/datastore/backend/postgres.py
--- a/ckanext/datastore/backend/postgres.py
+++ b/ckanext/datastore/backend/postgres.py
@@ -119,7 +119,7 @@ def _get_engine_from_url(connection_url):
engine = _engines.get(connection_url)
if not engine:
extras = {'url': connection_url}
- config.setdefault('pool_pre_ping', True)
+ config.setdefault('ckan.datastore.sqlalchemy.pool_pre_ping', True)
engine = sqlalchemy.engine_from_config(config,
'ckan.datastore.sqlalchemy.',
**extras)
| Datastore: sqlalchemy setting "pool_pre_ping"
**CKAN version**
2.9.x master at 93ef47244b01db097cd65494677296234a4d37d6
**Describe the bug**
The setting "`pool_pre_ping`" for the datastore connection is not working, because of a wrong setting key.
This is the [code](https://github.com/ckan/ckan/blob/93ef47244b01db097cd65494677296234a4d37d6/ckanext/datastore/backend/postgres.py#L122-L125):
```python
config.setdefault('pool_pre_ping', True)
engine = sqlalchemy.engine_from_config(config,
'ckan.datastore.sqlalchemy.',
**extras)
```
Since sqlachemy is told to read config keys with prefix `ckan.datastore.sqlalchemy.`, the setting `pool_pre_ping` will not be taken into consideration.
**Additional details**
This issue is identical to #5932, but related to the datastore engine and not to the main ckan db.
| 2021-05-12T11:54:07 |
||
ckan/ckan | 6,088 | ckan__ckan-6088 | [
"5899"
] | 93ef47244b01db097cd65494677296234a4d37d6 | diff --git a/ckan/lib/uploader.py b/ckan/lib/uploader.py
--- a/ckan/lib/uploader.py
+++ b/ckan/lib/uploader.py
@@ -52,6 +52,8 @@ def get_uploader(upload_to, old_filename=None):
upload = None
for plugin in plugins.PluginImplementations(plugins.IUploader):
upload = plugin.get_uploader(upload_to, old_filename)
+ if upload:
+ break
# default uploader
if upload is None:
@@ -65,6 +67,8 @@ def get_resource_uploader(data_dict):
upload = None
for plugin in plugins.PluginImplementations(plugins.IUploader):
upload = plugin.get_resource_uploader(data_dict)
+ if upload:
+ break
# default uploader
if upload is None:
| Allow uploaders to only override asset / resource uploading
**CKAN version**
2.8.7, 2.9.2
**Describe the bug**
Currently, CKAN allows handling both image / asset uploading and resource uploading via the `IUploader` plugin interface. That interface allows plugins to return `None` from `get_uploader()` / `get_resource_uploader()` so that to signify that this uploader in not meant to handle that type of upload.
However, when trying to use two different plugins each implementing a different type of uploader, one may encounter a problem where depending on the order of loading, there could be conflicts or CKAN might fall back to it's built-in uploader for no good reason.
This is because of this logic in https://github.com/ckan/ckan/blob/5a4af6fc3bee81331fbc19c632bf6089dd1aa18a/ckan/lib/uploader.py#L52-L57 - it will iterate over *all* uploaders and call `get_uploader()`. If the *last one* returns None, it will fall back to CKAN's built in. It should pick either the first or last uploader to return a non-`None` value instead.
Same happens for `get_resource_uploader()` in https://github.com/ckan/ckan/blob/5a4af6fc3bee81331fbc19c632bf6089dd1aa18a/ckan/lib/uploader.py#L65-L70.
This is an easy fix, but I'm not sure if the preferred logic is to pick the *first* or *last* plugin to implement an uploader for that file type.
**Steps to reproduce**
Install two plugins, each supporting a different kind of uploader, and see them conflict, and see CKAN fall back to it's internal uploader for one of the file types.
**Expected behavior**
CKAN picks the first / last uploader plugin that supports this file type.
**Additional details**
I have encountered this when working on ckanext-asset-storage, but I suppose it can affect other uploaders / custom built ones as well.
| You are right that this is bad behavior. The convention in other plugin hooks across CKAN is that first plugin wins, so that should be the case here as well. If anyone wants to pick this up this should be an easy fix.
@amercader , I am interested to working on this issue. What is your suggestion to do in this issue?
@Gauravp-NEC as the convention in CKAN is "first plugin wins", we need to break the loop whenever the first plugin returns a valid `upload` value:
```python
for plugin in plugins.PluginImplementations(plugins.IUploader):
upload = plugin.get_uploader(upload_to, old_filename)
if upload:
break
```
and
```python
for plugin in plugins.PluginImplementations(plugins.IUploader):
upload = plugin.get_resource_uploader(data_dict)
if upload:
break
``` | 2021-05-12T14:10:27 |
|
ckan/ckan | 6,105 | ckan__ckan-6105 | [
"6103"
] | fe76b33fd57e33a493ee67f896aa5d430c51a714 | diff --git a/ckan/lib/helpers.py b/ckan/lib/helpers.py
--- a/ckan/lib/helpers.py
+++ b/ckan/lib/helpers.py
@@ -1632,7 +1632,8 @@ def sanitize_url(url):
netloc = parsed_url.netloc.encode('idna').decode('ascii')
if not _PLAUSIBLE_HOST_IDNA.match(netloc):
return ''
- # quote with allowed characters from https://www.ietf.org/rfc/rfc3986.txt
+ # quote with allowed characters from
+ # https://www.ietf.org/rfc/rfc3986.txt
parsed_url = parsed_url._replace(
scheme=quote(unquote(parsed_url.scheme), '+'),
path=quote(unquote(parsed_url.path), "/"),
| "latest" documentation not being built in Read The Docs
https://readthedocs.org/projects/ckan/builds/13792875/
```
ERROR: Could not find a version that satisfies the requirement freezegun==1.1.0 (from -r dev-requirements.txt (line 8)) (from versions: 0.0.1, 0.0.2, 0.0.3, 0.0.4, 0.0.5, 0.0.6, 0.0.7, 0.0.8, 0.0.9, 0.1.0, 0.1.1, 0.1.2, 0.1.3, 0.1.4, 0.1.5, 0.1.6, 0.1.7, 0.1.8, 0.1.9, 0.1.11, 0.1.12, 0.1.13, 0.1.14, 0.1.15, 0.1.16, 0.1.17, 0.1.18, 0.1.19, 0.1.19.1, 0.2.0, 0.2.1, 0.2.2, 0.2.3, 0.2.4, 0.2.5, 0.2.6, 0.2.7, 0.2.8, 0.3.0, 0.3.1, 0.3.2, 0.3.3, 0.3.4, 0.3.5, 0.3.6, 0.3.7, 0.3.8, 0.3.9, 0.3.10, 0.3.11, 0.3.12, 0.3.13, 0.3.14, 0.3.15)
ERROR: No matching distribution found for freezegun==1.1.0 (from -r dev-requirements.txt (line 8))
```
Haven't investigated at all but it looks like a py2/py3 requirements issue
| Freezegun apparently dropped support for py2 in 1.0.0. Docs probably should be built with py3. | 2021-05-19T14:54:56 |
|
ckan/ckan | 6,110 | ckan__ckan-6110 | [
"6045"
] | bcda3f6bfec5c68ac339070886702437df1c6ff2 | diff --git a/ckan/config/middleware/flask_app.py b/ckan/config/middleware/flask_app.py
--- a/ckan/config/middleware/flask_app.py
+++ b/ckan/config/middleware/flask_app.py
@@ -238,7 +238,7 @@ def ungettext_alias():
(_ckan_i18n_dir, u'ckan')
] + [
(p.i18n_directory(), p.i18n_domain())
- for p in PluginImplementations(ITranslation)
+ for p in reversed(list(PluginImplementations(ITranslation)))
]
i18n_dirs, i18n_domains = zip(*pairs)
| Plugin order for translations is reversed
**CKAN version**
2.8, 2.9, master
**Describe the bug**
If the developer has multiple plugins implementing ITranslation interface and has the same translation keys in them, the last plugin wins.
**Steps to reproduce**
Create two plugins with ITranslation interface and the same translation key.
Translations from last plugin will be used.
**Expected behavior**
Translations from the first plugin should be used as the common convention is that the first plugin wins.
**Additional details**
https://github.com/vrk-kpa/ckanext-forcetranslation we made this couple years ago to circumvent this. Simple plugin which allows to choose which plugins translations to use. Related bug in https://github.com/ckan/ckanext-harvest/issues/266 which in essence is caused by the same thing.
| like other similar issues this might be fixed with a `reversed()` in places that have `for p in PluginImplementations(ITranslation)`
hi , @Zharktas i would like to work on this issue. | 2021-05-21T11:56:38 |
|
ckan/ckan | 6,114 | ckan__ckan-6114 | [
"6113"
] | bcda3f6bfec5c68ac339070886702437df1c6ff2 | diff --git a/ckan/logic/validators.py b/ckan/logic/validators.py
--- a/ckan/logic/validators.py
+++ b/ckan/logic/validators.py
@@ -936,20 +936,21 @@ def dict_only(value):
raise Invalid(_('Must be a dict'))
return value
+
def email_is_unique(key, data, errors, context):
'''Validate email is unique'''
model = context['model']
session = context['session']
users = session.query(model.User) \
- .filter(model.User.email == data[key]).all()
+ .filter(model.User.email == data[key]).all()
# is there is no users with this email it's free
if not users:
return
else:
# allow user to update their own email
for user in users:
- if (user.name == data[("name",)]
+ if (user.name in [data[("name",)], data[("id",)]]
or user.id == data[("id",)]):
return
| diff --git a/ckan/tests/logic/test_validators.py b/ckan/tests/logic/test_validators.py
--- a/ckan/tests/logic/test_validators.py
+++ b/ckan/tests/logic/test_validators.py
@@ -185,6 +185,22 @@ def test_email_is_unique_validator_user_update_email_unchanged(app):
assert updated_user.email == old_email
[email protected]("clean_db")
+def test_email_is_unique_validator_user_update_using_name_as_id(app):
+ with app.flask_app.test_request_context():
+ user = factories.User(username="user01", email="[email protected]")
+
+ # try to update user1 and leave email unchanged
+ old_email = "[email protected]"
+
+ helpers.call_action(
+ "user_update", id=user['name'], email=user['email'], about='test')
+ updated_user = model.User.get(user["id"])
+
+ assert updated_user.email == old_email
+ assert updated_user.about == 'test'
+
+
@pytest.mark.usefixtures("clean_db")
def test_email_is_unique_validator_user_update_email_new(app):
with app.flask_app.test_request_context():
| Can not update user via `user_update` when using `name` for `id` parameter
**CKAN version**
2.9
**Describe the bug**
CKAN 2.9 introduced the `email_is_unique` validator to prevent duplicates. But the current implementation only works when the `id` param contains the actual UUID not the name, eg:
http POST localhost:5000/api/action/user_update Authorization:{API_TOKEN} id=2e2dafdf-a7a8-495e-a9da-84ed4a1051a0 [email protected] about=hola
Works fine, but this:
http POST localhost:5000/api/action/user_update Authorization:{API_TOKEN} id=adria-mercader [email protected] about=hola
Fails with a `ValidationError: "The email address '[email protected]' belongs to a registered user.`
The validator just needs to account for this scenario here:
https://github.com/ckan/ckan/blob/bcda3f6bfec5c68ac339070886702437df1c6ff2/ckan/logic/validators.py#L952-L953
| 2021-05-25T12:54:28 |
|
ckan/ckan | 6,123 | ckan__ckan-6123 | [
"6106"
] | 27f0b8cf52bb2140f16e2f09f3c42ed15e7e9b99 | diff --git a/ckan/logic/action/get.py b/ckan/logic/action/get.py
--- a/ckan/logic/action/get.py
+++ b/ckan/logic/action/get.py
@@ -2534,6 +2534,11 @@ def package_activity_list(context, data_dict):
NB Only sysadmins may set include_hidden_activity to true.
(default: false)
:type include_hidden_activity: bool
+ :param activity_types: A list of activity types to include in the response
+ :type activity_types: list
+
+ :param exclude_activity_types: A list of activity types to exclude from the response
+ :type exclude_activity_types: list
:rtype: list of dictionaries
@@ -2542,6 +2547,12 @@ def package_activity_list(context, data_dict):
# authorized to read.
data_dict['include_data'] = False
include_hidden_activity = data_dict.get('include_hidden_activity', False)
+ activity_types = data_dict.pop('activity_types', None)
+ exclude_activity_types = data_dict.pop('exclude_activity_types', None)
+
+ if activity_types is not None and exclude_activity_types is not None:
+ raise ValidationError({'activity_types': ['Cannot be used together with `exclude_filters']})
+
_check_access('package_activity_list', context, data_dict)
model = context['model']
@@ -2557,6 +2568,8 @@ def package_activity_list(context, data_dict):
activity_objects = model.activity.package_activity_list(
package.id, limit=limit, offset=offset,
include_hidden_activity=include_hidden_activity,
+ activity_types=activity_types,
+ exclude_activity_types=exclude_activity_types
)
return model_dictize.activity_list_dictize(
diff --git a/ckan/logic/schema.py b/ckan/logic/schema.py
--- a/ckan/logic/schema.py
+++ b/ckan/logic/schema.py
@@ -618,7 +618,8 @@ def default_dashboard_activity_list_schema(
def default_activity_list_schema(
not_missing, unicode_safe, configured_default,
natural_number_validator, limit_to_configured_maximum,
- ignore_missing, boolean_validator, ignore_not_sysadmin):
+ ignore_missing, boolean_validator, ignore_not_sysadmin,
+ list_of_strings):
schema = default_pagination_schema()
schema['id'] = [not_missing, unicode_safe]
schema['limit'] = [
@@ -627,6 +628,8 @@ def default_activity_list_schema(
limit_to_configured_maximum('ckan.activity_list_limit_max', 100)]
schema['include_hidden_activity'] = [
ignore_missing, ignore_not_sysadmin, boolean_validator]
+ schema['activity_types'] = [ignore_missing, list_of_strings]
+ schema['exclude_activity_types'] = [ignore_missing, list_of_strings]
return schema
diff --git a/ckan/model/activity.py b/ckan/model/activity.py
--- a/ckan/model/activity.py
+++ b/ckan/model/activity.py
@@ -182,9 +182,12 @@ def _package_activity_query(package_id):
def package_activity_list(
- package_id, limit, offset, include_hidden_activity=False):
+ package_id, limit, offset, include_hidden_activity=False,
+ activity_types=None, exclude_activity_types=None):
'''Return the given dataset (package)'s public activity stream.
+ activity_types, exclude_activity_types: Optional. list of strings for activity types
+
Returns all activities about the given dataset, i.e. where the given
dataset is the object of the activity, e.g.:
@@ -198,6 +201,11 @@ def package_activity_list(
if not include_hidden_activity:
q = _filter_activitites_from_users(q)
+ if activity_types:
+ q = _filter_activitites_from_type(q, include=True, types=activity_types)
+ elif exclude_activity_types:
+ q = _filter_activitites_from_type(q, include=False, types=exclude_activity_types)
+
return _activities_at_offset(q, limit, offset)
@@ -452,7 +460,7 @@ def recently_changed_packages_activity_list(limit, offset):
def _filter_activitites_from_users(q):
'''
- Adds a filter to an existing query object ot avoid activities from users
+ Adds a filter to an existing query object to avoid activities from users
defined in :ref:`ckan.hide_activity_from_users` (defaults to the site user)
'''
users_to_avoid = _activity_stream_get_filtered_users()
@@ -461,6 +469,17 @@ def _filter_activitites_from_users(q):
return q
+def _filter_activitites_from_type(q, types, include=True):
+ '''
+ Adds a filter to an existing query object to include or exclude (include=False)
+ activities based on a list of types
+ '''
+ if include:
+ q = q.filter(ckan.model.Activity.activity_type.in_(types))
+ else:
+ q = q.filter(ckan.model.Activity.activity_type.notin_(types))
+
+ return q
def _activity_stream_get_filtered_users():
'''
| diff --git a/ckan/tests/logic/action/test_get.py b/ckan/tests/logic/action/test_get.py
--- a/ckan/tests/logic/action/test_get.py
+++ b/ckan/tests/logic/action/test_get.py
@@ -3177,6 +3177,72 @@ def test_private_dataset_delete_has_no_activity(self):
)
assert [activity["activity_type"] for activity in activities] == []
+ def _create_bulk_types_activities(self, types):
+ dataset = factories.Dataset()
+ from ckan import model
+
+ user = factories.User()
+
+ objs = [
+ model.Activity(
+ user_id=user['id'],
+ object_id=dataset["id"],
+ activity_type=activity_type,
+ data=None,
+ )
+ for activity_type in types
+ ]
+ model.Session.add_all(objs)
+ model.repo.commit_and_remove()
+ return dataset["id"]
+
+ def test_error_bad_search(self):
+ with pytest.raises(logic.ValidationError):
+ helpers.call_action(
+ "package_activity_list",
+ id=id,
+ activity_types=['new package'],
+ exclude_activity_types=['deleted package']
+ )
+
+ def test_activity_types_filter(self):
+ types = [
+ 'new package',
+ 'changed package',
+ 'deleted package',
+ 'changed package',
+ 'new package'
+ ]
+ id = self._create_bulk_types_activities(types)
+
+ activities_new = helpers.call_action(
+ "package_activity_list",
+ id=id,
+ activity_types=['new package']
+ )
+ assert len(activities_new) == 2
+
+ activities_not_new = helpers.call_action(
+ "package_activity_list",
+ id=id,
+ exclude_activity_types=['new package']
+ )
+ assert len(activities_not_new) == 3
+
+ activities_delete = helpers.call_action(
+ "package_activity_list",
+ id=id,
+ activity_types=['deleted package']
+ )
+ assert len(activities_delete) == 1
+
+ activities_not_deleted = helpers.call_action(
+ "package_activity_list",
+ id=id,
+ exclude_activity_types=['deleted package']
+ )
+ assert len(activities_not_deleted) == 4
+
def _create_bulk_package_activities(self, count):
dataset = factories.Dataset()
from ckan import model
| Allow `*_activity_list` actions to filter by `activity_type`
**CKAN version**: 2.9
It would be helpful if the `*_activity_list` actions had the ability to optionally accept a list of `activity_type`s to filter by.
e.g:
```py
get_action('package_activity_list')(context, {
'id': 'my-dataset',
'activity_types': ['changed package'],
})
```
- The default would be that all activities associated with `id` are returned (as it is now).
- Passing `activity_types` would filter to only the specified activity types.
This would be particularly useful for plugin authors leveraging custom activity types.
| I think this will make life for extension developers much easier.
Perhaps it would make sense to have two different parameters:
* `include_activity_types`: only return activities of these types
* `exclude_activity_types`: ignore activities of these types
The implementation would not be much more complex and I can see both being useful in situations I've encountered working with custom activities. | 2021-05-28T17:09:56 |
ckan/ckan | 6,125 | ckan__ckan-6125 | [
"4807"
] | 27f0b8cf52bb2140f16e2f09f3c42ed15e7e9b99 | diff --git a/setup.py b/setup.py
--- a/setup.py
+++ b/setup.py
@@ -191,7 +191,7 @@
extras_require = {}
_extras_groups = [
- ('requirements', 'requirements.txt'), ('requirements-py2', 'requirements-py2.txt'),
+ ('requirements', 'requirements.txt'),
('setuptools', 'requirement-setuptools.txt'), ('dev', 'dev-requirements.txt'),
]
| Remove remaining Python 2 code in core
This should be done in separate pull requests to make reviews easier
- [x] Remove `requirements.py2.*` files and update documentation to remove py2 mentions
- [x] Remove py2 specific code. Look for `if six.PY2:` and remove what's inside!
- [x] Remove py3 checks. Look for `six.PY3` and make that the standard code run (remove the check if any)
- [x] Remove usage of six. We should not need the compatibility layer any more. Make all code standard Python 3
This should definitely be done separately
- [ ] Remove unicode literals (eg `my_conf[u"test_key_1"] = u"Test value 1"` -> `my_conf["test_key_1"] = "Test value 1"`
| @amercader i'm working on this now.
For this `Remove requirements.py2.* files and update documentation to remove py2 mentions`: what part of the documentation do I need to update?
@amercader , I am interested to "Remove unicode literals". Where I need to remove it?
@steveoni my understanding is that you need to go look for any mentions of python 2 in the docs which is in the `/doc/` directory on this repository.
@Gauravp-NEC unicode literal need to be removed from the whole code base
@GabrielNicolasAvellaneda are you working on the removal of Unicode literals?
**Remove py3 checks. Look for six.PY3 and make that the standard code run (remove the check if any)**
Should test containing something like this`@pytest.mark.skipif(six.PY3, reason='')` be removed with all its content. e.g:
```js
@pytest.mark.skipif(six.PY3, reason='Only relevant to py2')
@mock.patch('paste.registry.TypeError')
def test_get_user_outside_web_request_py2(mock_TypeError):
auth._get_user('example')
assert mock_TypeError.called
```
@amercader
@steveoni , yes, these are py2 only tests that no longer run | 2021-05-29T17:26:12 |
|
ckan/ckan | 6,180 | ckan__ckan-6180 | [
"6179"
] | cd7103dddd299bbebad546c336733dfb9925eb05 | diff --git a/ckan/lib/search/__init__.py b/ckan/lib/search/__init__.py
--- a/ckan/lib/search/__init__.py
+++ b/ckan/lib/search/__init__.py
@@ -5,6 +5,7 @@
import sys
import cgitb
import warnings
+import base64
import xml.dom.minidom
import requests
@@ -259,7 +260,7 @@ def _get_schema_from_solr(file_offset):
http_auth = None
if solr_user is not None and solr_password is not None:
http_auth = solr_user + ':' + solr_password
- http_auth = 'Basic ' + http_auth.encode('base64').strip()
+ http_auth = 'Basic {}'.format(base64.b64encode(http_auth.encode('utf8')).strip())
url = solr_url.strip('/') + file_offset
| diff --git a/ckan/tests/lib/search/test_common.py b/ckan/tests/lib/search/test_common.py
new file mode 100644
--- /dev/null
+++ b/ckan/tests/lib/search/test_common.py
@@ -0,0 +1,12 @@
+# encoding: utf-8
+import pytest
+
+from ckan.common import config
+
+
[email protected]_config("solr_user", "solr")
[email protected]_config("solr_password", "password")
+def test_solr_user_and_password(app):
+
+ assert config["solr_user"] == "solr"
+ assert config["solr_password"] == "password"
| Can't use `solr_user` and `solr_password` in Python 3
**CKAN version**
2.9
**Describe the bug**
When setting the `solr_user` and `solr_password` config options running Python 3 you get a startup error:
```
File "/usr/lib/ckan/src/ckan/ckan/lib/search/__init__.py", line 309, in check_solr_schema_version
res = _get_schema_from_solr(SOLR_SCHEMA_FILE_OFFSET_MANAGED)
File "/usr/lib/ckan/src/ckan/ckan/lib/search/__init__.py", line 262, in _get_schema_from_solr
http_auth = 'Basic ' + http_auth.encode('base64').strip()
LookupError: 'base64' is not a text encoding; use codecs.encode() to handle arbitrary codecs
```
| 2021-06-21T12:39:23 |
|
ckan/ckan | 6,181 | ckan__ckan-6181 | [
"5025"
] | cd7103dddd299bbebad546c336733dfb9925eb05 | diff --git a/ckan/lib/helpers.py b/ckan/lib/helpers.py
--- a/ckan/lib/helpers.py
+++ b/ckan/lib/helpers.py
@@ -1178,8 +1178,9 @@ def get_facet_items_dict(
if search_facets is None:
search_facets = getattr(c, u'search_facets', None)
- if not search_facets or not search_facets.get(
- facet, {}).get('items'):
+ if not search_facets \
+ or not isinstance(search_facets, dict) \
+ or not search_facets.get(facet, {}).get('items'):
return []
facets = []
for facet_item in search_facets.get(facet)['items']:
| Search form validation
### CKAN Version if known (or site URL)
CKAN 2.8.3
### Please describe the expected behaviour
When user enter incorrect search query (in dataset search form on organization page), search form should inform her/him that something is wrong with that.
### Please describe the actual behaviour
Currently CKAN web UI returns "An internal server error occurs" message... which many users found to be misleading.
### What steps can be taken to reproduce the issue?
Go into random organization page and enter "and" into search field and press enter, url should be similar to that:
http://<instance address>/organization/<organization name>?q=AND&sort=score+desc%2C+metadata_modified+desc
| Since Pysolr returns us a pretty clear description of the exception that occurred, we can use it to explain to the user why exactly this happened.
`u"Solr responded with an error (HTTP 400): [Reason: Can't determine a Sort Order (asc or desc) in sort spec 'score dessc, metadata_modified descs', pos=5]".
`
For now, the message "There was an error while searching. Please try again." is hard-coded in the template, what is definitely could be unclear for someone. However, the text of the exception itself needs refinement before being presented to the user. I would like to work on this issues. | 2021-06-22T07:15:12 |
|
ckan/ckan | 6,189 | ckan__ckan-6189 | [
"6148"
] | 5c386b8cd44ad41c8a94d7c7953c863d6e2f64bb | diff --git a/ckan/cli/search_index.py b/ckan/cli/search_index.py
--- a/ckan/cli/search_index.py
+++ b/ckan/cli/search_index.py
@@ -4,7 +4,6 @@
import click
import sqlalchemy as sa
-
import ckan.plugins.toolkit as tk
@@ -18,7 +17,6 @@ def search_index():
@click.option(u'-v', u'--verbose', is_flag=True)
@click.option(u'-i', u'--force', is_flag=True,
help=u'Ignore exceptions when rebuilding the index')
[email protected](u'-r', u'--refresh', help=u'Refresh current index', is_flag=True)
@click.option(u'-o', u'--only-missing',
help=u'Index non indexed datasets only', is_flag=True)
@click.option(u'-q', u'--quiet', help=u'Do not output index rebuild progress',
@@ -28,9 +26,11 @@ def search_index():
u'ensures that changes are immediately available on the'
u'search, but slows significantly the process. Default'
u'is false.')
[email protected]('-c', '--clear', help='Clear the index before reindexing',
+ is_flag=True)
@click.argument(u'package_id', required=False)
def rebuild(
- verbose, force, refresh, only_missing, quiet, commit_each, package_id
+ verbose, force, only_missing, quiet, commit_each, package_id, clear
):
u''' Rebuild search index '''
from ckan.lib.search import rebuild, commit
@@ -39,9 +39,9 @@ def rebuild(
rebuild(package_id,
only_missing=only_missing,
force=force,
- refresh=refresh,
defer_commit=(not commit_each),
- quiet=quiet)
+ quiet=quiet,
+ clear=clear)
except Exception as e:
tk.error_shout(e)
if not commit_each:
diff --git a/ckan/lib/search/__init__.py b/ckan/lib/search/__init__.py
--- a/ckan/lib/search/__init__.py
+++ b/ckan/lib/search/__init__.py
@@ -137,8 +137,8 @@ def notify(self, entity, operation):
log.warn("Discarded Sync. indexing for: %s" % entity)
-def rebuild(package_id=None, only_missing=False, force=False, refresh=False,
- defer_commit=False, package_ids=None, quiet=False):
+def rebuild(package_id=None, only_missing=False, force=False, defer_commit=False,
+ package_ids=None, quiet=False, clear=False):
'''
Rebuilds the search index.
@@ -183,7 +183,7 @@ def rebuild(package_id=None, only_missing=False, force=False, refresh=False,
else:
log.info('Rebuilding the whole index...')
# When refreshing, the index is not previously cleared
- if not refresh:
+ if clear:
package_index.clear()
total_packages = len(package_ids)
| diff --git a/ckan/tests/cli/test_search_index.py b/ckan/tests/cli/test_search_index.py
--- a/ckan/tests/cli/test_search_index.py
+++ b/ckan/tests/cli/test_search_index.py
@@ -28,6 +28,13 @@ def test_search_index_rebuild(self, cli):
search_result = helpers.call_action(u'package_search', q=u"After")
assert search_result[u'count'] == 1
+ # Clear and defer commit
+ result = cli.invoke(ckan, [u'search-index', u'rebuild', '-e', '-c'])
+ print(result.output)
+ assert not result.exit_code
+ search_result = helpers.call_action(u'package_search', q=u"After")
+ assert search_result[u'count'] == 1
+
def test_test_main_operations(self, cli):
"""Create few datasets, clear index, rebuild it - make sure search results
are always reflect correct state of index.
| search-index rebuild is destructive by default
**CKAN version**
all
**Describe the bug**
If you run `search-index rebuild` without the `-r` flag, the solr index is first cleared so is empty while being reloaded. On a site with 10k datasets data will be inaccessible for ~30 minutes.
**Steps to reproduce**
run `search-index rebuild` without the `-r` flag
**Expected behavior**
The whole update could happen as a single transaction so that you only see the new records after the reindex is complete, or if the `-e` flag is used then the default should be to not clear the index, a new `--clear` flag could be added for people that want the current behavior.
| @wardi
I want to know if i understand the task to be done here:
we want the `search-index rebuild` to do the same thing as when `search-index rebuild -r` is called. i.e it refreshes the current index w/o the `-r` flag.
Also, when `-e` flag is used, the current index should just be refreshed and committed.
And the search index should only be cleared and rebuild when `--clear` flag is used.
did I get it?
not exactly, ideally:
`search-index rebuild` can clear the index but it should be done in the same solr commit so that it doesn't look like all the datasets have disappeared while the rebuild takes place.
`search-index rebuild -e` should behave like `search-index rebuild -e -r`
`search-index rebuild -e --clear` should behave like the current `search-index rebuild -e` (clear the index then commit each record)
ok. i will start working on this
@wardi
Base on your comment: `search-index rebuild -e` should behave like `search-index rebuild -e -r`.
While looking at the current code, both commands end up to this line of code which update and commit:
```py
try:
package_index.update_dict(
logic.get_action('package_show')(context,
{'id': pkg_id}
),
defer_commit
)
. . . . . . . . . .
```
To me, I think both commands are doing the same thing. What do you think?
> @wardi
>
> Base on your comment: `search-index rebuild -e` should behave like `search-index rebuild -e -r`.
>
> While looking at the current code, both commands end up to this line of code which update and commit:
>
> ```python
> try:
> package_index.update_dict(
> logic.get_action('package_show')(context,
> {'id': pkg_id}
> ),
> defer_commit
> )
> . . . . . . . . . .
> ```
>
> To me, I think both commands are doing the same thing. What do you think?
@wardi
@wardi
This command is used to update the search index, not the database. Start by setting up a site to test and understand the `search-index rebuild` command and the behavior of the options described, then trace the code.
ok.
Instead of setting up a site, can't I test this behavior with the test code in: https://github.com/ckan/ckan/blob/master/ckan/tests/cli/test_search_index.py
@wardi
I just re-read your comment again, here is how I track the code;
I'm using the test for `cli/test_search_index.py`
```py
class TestSearchIndex(object):
def test_search_index_rebuild(self, cli):
"""Direct update on package won't be reflected in search results till
re-index.
"""
dataset = factories.Dataset(title=u"Before rebuild")
model.Session.query(model.Package).filter_by(id=dataset[u'id']).update(
{u'title': u'After update'})
model.Session.commit()
search_result = helpers.call_action(u'package_search', q=u"After")
assert search_result[u'count'] == 0
print("IN TEST NOW")
result = cli.invoke(ckan, [u'search-index', u'rebuild', '-e', '-r'])
```
Then I trace the functionality to this file `cli/search_index.py`:
```py
@click.argument(u'package_id', required=False)
def rebuild(
verbose, force, refresh, only_missing, quiet, commit_each, package_id
):
u''' Rebuild search index '''
from ckan.lib.search import rebuild, commit
try:
rebuild(package_id,
only_missing=only_missing,
force=force,
refresh=refresh,
defer_commit=(not commit_each),
quiet=quiet)
except Exception as e:
tk.error_shout(e)
if not commit_each:
commit()
```
The preceding code has all things to do with `search-index rebuild` and all its following commands.
From the preceding code, I trace the `rebuild` functionality to `ckan/lib/search/__init__.py`:
```py
def rebuild(package_id=None, only_missing=False, force=False, refresh=False,
defer_commit=False, package_ids=None, quiet=False):
'''
Rebuilds the search index.
If a dataset id is provided, only this dataset will be reindexed.
When reindexing all datasets, if only_missing is True, only the
datasets not already indexed will be processed. If force equals
True, if an exception is found, the exception will be logged, but
the process will carry on.
'''
log.info("Rebuilding search index...")
```
Then from the search-index test, I tried each command and trace them down to each line in `rebuild` function responsible for the cli command functionality. Hence the line of code in my previous comment was from this `rebuild` function.
Like you said, `this command is used to update the search-index and not the database.` I will be glad if you could provide more explanation on this since the `rebuild` function is used to `rebuilds the search index`
@wardi
cc: @anuveyatsu
You're in the right place. The code that handles reindexing all datasets is https://github.com/ckan/ckan/blob/237644f8436be748b0cb2b74b52e80763083d4a5/ckan/lib/search/__init__.py#L171
and the package indexing logic is https://github.com/ckan/ckan/blob/237644f8436be748b0cb2b74b52e80763083d4a5/ckan/lib/search/index.py#L101
In `rebuild` the `defer_commit` and `refresh` parameters control whether a solr commit will happen after each dataset and whether the index will be cleared first. Clearing the index doesn't currently support a `defer_commit` parameter so that would need to be added.
Next the cli parameters would need to be changed as described above and the documentation updated: https://github.com/ckan/ckan/blob/237644f8436be748b0cb2b74b52e80763083d4a5/ckan/cli/search_index.py#L17
Thanks for the clearification | 2021-06-24T21:53:52 |
ckan/ckan | 6,191 | ckan__ckan-6191 | [
"6190"
] | 5c386b8cd44ad41c8a94d7c7953c863d6e2f64bb | diff --git a/ckan/lib/helpers.py b/ckan/lib/helpers.py
--- a/ckan/lib/helpers.py
+++ b/ckan/lib/helpers.py
@@ -1190,7 +1190,7 @@ def has_more_facets(facet, search_facets, limit=None, exclude_active=False):
facets.append(dict(active=False, **facet_item))
elif not exclude_active:
facets.append(dict(active=True, **facet_item))
- if c.search_facets_limits and limit is None:
+ if getattr(c, 'search_facets_limits', None) and limit is None:
limit = c.search_facets_limits.get(facet)
if limit is not None and len(facets) > limit:
return True
| Inadequate null check in helpers.has_more_facets
**CKAN version**
2.8+
**Describe the bug**
The `has_more_facets` helper has an insufficient guard clause checking whether `c.search_facets_limits` is present, resulting in an attribute error if used without search_facets_limits present:
if c.search_facets_limits and limit is None:
limit = c.search_facets_limits.get(facet)
Contrast this with the guard in `get_facet_items_dict`:
if hasattr(c, 'search_facets_limits'):
if c.search_facets_limits and limit is None:
limit = c.search_facets_limits.get(facet)
**Steps to reproduce**
Not sure how to recreate this in vanilla CKAN. We encountered it while doing development work with a mixture of `ckanext-datarequests` and `ckanext-s3filestore`.
**Expected behavior**
`c.search_facets_limits` should be ignored if not present.
**Additional details**
No stack trace occurs by default, merely an Internal Server Error page. Will submit a pull request soon.
| 2021-06-25T04:40:38 |
||
ckan/ckan | 6,207 | ckan__ckan-6207 | [
"4576"
] | 4e905cfb45799b67be42291ba3b0151774823467 | diff --git a/ckan/config/middleware/flask_app.py b/ckan/config/middleware/flask_app.py
--- a/ckan/config/middleware/flask_app.py
+++ b/ckan/config/middleware/flask_app.py
@@ -361,6 +361,8 @@ def ckan_before_request():
'''
response = None
+ g.__timer = time.time()
+
# Update app_globals
app_globals.app_globals._check_uptodate()
@@ -373,7 +375,6 @@ def ckan_before_request():
set_controller_and_action()
set_ckan_current_url(request.environ)
- g.__timer = time.time()
return response
| AttributeError: '_Globals' object has no attribute '__timer'
### CKAN Version if known (or site URL)
2.8.1
### What steps can be taken to reproduce the issue?
It happens from time to time.
```
[2018-12-06 11:26:09,833] ERROR in app: Exception on /user/ [GET]
Traceback (most recent call last):
File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/flask/app.py", line 1982, in wsgi_app
response = self.full_dispatch_request()
File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/flask/app.py", line 1615, in full_dispatch_request
return self.finalize_request(rv)
File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/flask/app.py", line 1632, in finalize_request
response = self.process_response(response)
File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/flask/app.py", line 1856, in process_response
response = handler(response)
File "/usr/lib/ckan/venv/src/ckan/ckan/config/middleware/flask_app.py", line 324, in ckan_after_request
r_time = time.time() - g.__timer
File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/werkzeug/local.py", line 347, in __getattr__
return getattr(self._get_current_object(), name)
File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/werkzeug/local.py", line 347, in __getattr__
return getattr(self._get_current_object(), name)
File "/usr/lib/ckan/venv/src/ckan/ckan/config/middleware/flask_app.py", line 368, in __getattr__
return getattr(app_globals.app_globals, name)
AttributeError: '_Globals' object has no attribute '__timer'
[2018-12-06 11:26:09,846] ERROR in app: Request finalizing failed with an error while handling an error
Traceback (most recent call last):
File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/flask/app.py", line 1632, in finalize_request
response = self.process_response(response)
File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/flask/app.py", line 1856, in process_response
response = handler(response)
File "/usr/lib/ckan/venv/src/ckan/ckan/config/middleware/flask_app.py", line 324, in ckan_after_request
r_time = time.time() - g.__timer
File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/werkzeug/local.py", line 347, in __getattr__
return getattr(self._get_current_object(), name)
File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/werkzeug/local.py", line 347, in __getattr__
return getattr(self._get_current_object(), name)
File "/usr/lib/ckan/venv/src/ckan/ckan/config/middleware/flask_app.py", line 368, in __getattr__
return getattr(app_globals.app_globals, name)
AttributeError: '_Globals' object has no attribute '__timer'
```
| The attributes error comes from this line, inside `ckan_after_request`:
https://github.com/ckan/ckan/blob/51e413087652a05f94d384a0f174a655c5d5b04d/ckan/config/middleware/flask_app.py#L330
The value of `g.__timer` is set in another function, `ckan_before_request`, but it is not set because there is an error before it: `_check_uptodate` is called, which uses `get_system_info`, which tries to fetch the first value of the query, but _I suspect_ it could fail because the table is empty:
https://github.com/ckan/ckan/blob/51e413087652a05f94d384a0f174a655c5d5b04d/ckan/model/system_info.py#L55-L64
```
Traceback (most recent call last):
File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/flask/app.py", line 1610, in full_dispatch_request
rv = self.preprocess_request()
File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/flask/app.py", line 1831, in preprocess_request
rv = func()
File "/usr/lib/ckan/venv/src/ckan/ckan/config/middleware/flask_app.py", line 305, in ckan_before_request
app_globals.app_globals._check_uptodate()
File "/usr/lib/ckan/venv/src/ckan/ckan/lib/app_globals.py", line 201, in _check_uptodate
value = model.get_system_info('ckan.config_update')
File "/usr/lib/ckan/venv/src/ckan/ckan/model/system_info.py", line 59, in get_system_info
obj = meta.Session.query(SystemInfo).filter_by(key=key).first()
File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/sqlalchemy/orm/query.py", line 3222, in first
ret = list(self[0:1])
File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/sqlalchemy/orm/query.py", line 3012, in __getitem__
return list(res)
File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/sqlalchemy/orm/query.py", line 3324, in __iter__
return self._execute_and_instances(context)
File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/sqlalchemy/orm/query.py", line 3349, in _execute_and_instances
result = conn.execute(querycontext.statement, self._params)
File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 988, in execute
return meth(self, multiparams, params)
File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/sqlalchemy/sql/elements.py", line 287, in _execute_on_connection
return connection._execute_clauseelement(self, multiparams, params)
File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1107, in _execute_clauseelement
distilled_params,
File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1248, in _execute_context
e, statement, parameters, cursor, context
File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1466, in _handle_dbapi_exception
util.raise_from_cause(sqlalchemy_exception, exc_info)
File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/sqlalchemy/util/compat.py", line 399, in raise_from_cause
reraise(type(exception), exception, tb=exc_tb, cause=cause)
File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1244, in _execute_context
cursor, statement, parameters, context
File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/sqlalchemy/engine/default.py", line 550, in do_execute
cursor.execute(statement, parameters)
OperationalError: (psycopg2.OperationalError) server closed the connection unexpectedly
This probably means the server terminated abnormally
before or while processing the request.
[SQL: SELECT system_info.id AS system_info_id, system_info.key AS system_info_key, system_info.value AS system_info_value, system_info.state AS system_info_state, system_info.revision_id AS ystem_info_revision_id
FROM system_info
WHERE system_info.key = %(key_1)s
LIMIT %(param_1)s]
[parameters: {'key_1': 'ckan.config_update', 'param_1': 1}]
(Background on this error at: http://sqlalche.me/e/e3q8)
```
It should have been setup by `config_option_update` probably:
https://github.com/ckan/ckan/blob/51e413087652a05f94d384a0f174a655c5d5b04d/ckan/logic/action/update.py#L1234
...or somewhere using the `set_system_info`.
https://github.com/ckan/ckan/blob/51e413087652a05f94d384a0f174a655c5d5b04d/ckan/model/system_info.py#L76-L77
...and/or by using a default value (but in this case an `OperationError` seems raised, which should be handled or, even better, avoided).
Inserting the entry manually on the database does not seem to be a valid workaround:
```sql
INSERT INTO system_info (id, key, value) VALUES (0, 'ckan.config_update', 1);
```
I still do not understand why I have an `OperationError` and if it is somehow related to that specific query and why everything else seems to work as usual, especially after https://github.com/ckan/ckan/pull/4853 (I wonder if the new option as been properly applied).
I am not able to replicate that issue on my PC, only on some servers with Docker. I start to think it could be a Docker networking bug.
@frafra Have you found a solution to this? We are having the same issue on a Docker server.
@hardingalexh No, still happening. No idea why. I spent much time with some internal server error raised by CKAN and I do not know if they are related. One of them is mitigated by fetching a page from time to time actually...
Hello everyone, could they find the solution to the error?
@gasti10 I am also getting this error.
This appears to be driven by `ckan/config/middleware/flask_app.py`. I think that, as indicated by the docstring for `ckan_before_request`, `g.__timer = time.time()` is not being reached. This is probably due to `response = identify_user()`, although it is hard to confirm without any logging of that function. As such, `ckan_after_request` is always doomed to fail where `r_time = time.time() - g.__timer` tries to reference the unset `g.__timer`
```python
def ckan_before_request():
u'''
Common handler executed before all Flask requests
If a response is returned by any of the functions called (
currently ``identify_user()` only) any further processing of the
request will be stopped and that response will be returned.
'''
response = None
# Update app_globals
app_globals.app_globals._check_uptodate()
# Identify the user from the repoze cookie or the API header
# Sets g.user and g.userobj
response = identify_user()
# Provide g.controller and g.action for backward compatibility
# with extensions
set_controller_and_action()
set_ckan_current_url(request.environ)
g.__timer = time.time()
return response
def ckan_after_request(response):
u'''Common handler executed after all Flask requests'''
# Dispose of the SQLALchemy session
model.Session.remove()
# Check session cookie
response = check_session_cookie(response)
# Set CORS headers if necessary
response = set_cors_headers_for_response(response)
# Set Cache Control headers
response = set_cache_control_headers_for_response(response)
r_time = time.time() - g.__timer
url = request.environ['PATH_INFO']
log.info(' %s render time %.3f seconds' % (url, r_time))
return response
```
I will try to modify the assignment of `g.__timer = time.time()` to be above `response = identify_user()`, and make a pull request if successful
can confirm that moving assignment of `g.__timer = time.time()` fixed the issue my my deployment:
```python
def ckan_before_request():
u'''
Common handler executed before all Flask requests
If a response is returned by any of the functions called (
currently ``identify_user()` only) any further processing of the
request will be stopped and that response will be returned.
'''
response = None
g.__timer = time.time()
# Update app_globals
app_globals.app_globals._check_uptodate()
# Identify the user from the repoze cookie or the API header
# Sets g.user and g.userobj
response = identify_user()
# Provide g.controller and g.action for backward compatibility
# with extensions
set_controller_and_action()
set_ckan_current_url(request.environ)
return response
```
I will leave this for someone with a better knowledge of this repository to action, as I am simply running from `2.9` branch. ideally this would be resolved in `master` also | 2021-06-30T17:46:27 |
|
ckan/ckan | 6,211 | ckan__ckan-6211 | [
"6142"
] | 4e905cfb45799b67be42291ba3b0151774823467 | diff --git a/ckan/views/user.py b/ckan/views/user.py
--- a/ckan/views/user.py
+++ b/ckan/views/user.py
@@ -263,10 +263,14 @@ def post(self, id=None):
if not context[u'save']:
return self.get(id)
+ # checks if user id match with the current logged user
if id in (g.userobj.id, g.userobj.name):
current_user = True
else:
current_user = False
+
+ # we save the username for later use.. in case the current
+ # logged in user change his username
old_username = g.userobj.name
try:
@@ -284,16 +288,33 @@ def post(self, id=None):
context[u'message'] = data_dict.get(u'log_message', u'')
data_dict[u'id'] = id
+
+ # we need this comparison when sysadmin edits a user,
+ # this will return True
+ # and we can utilize it for later use.
email_changed = data_dict[u'email'] != g.userobj.email
+ # common users can edit their own profiles without providing
+ # password, but if they want to change
+ # their old password with new one... old password must be provided..
+ # so we are checking here if password1
+ # and password2 are filled so we can enter the validation process.
+ # when sysadmins edits a user he MUST provide sysadmin password.
+ # We are recognizing sysadmin user
+ # by email_changed variable.. this returns True
+ # and we are entering the validation.
if (data_dict[u'password1']
and data_dict[u'password2']) or email_changed:
+
+ # getting the identity for current logged user
identity = {
u'login': g.user,
u'password': data_dict[u'old_password']
}
auth = authenticator.UsernamePasswordAuthenticator()
+ # we are checking if the identity is not the
+ # same with the current logged user if so raise error.
if auth.authenticate(request.environ, identity) != g.user:
errors = {
u'oldpassword': [_(u'Password entered was incorrect')]
| Sysadmin cannot edit normal user's profile
**CKAN version**
2.9.2
**Describe the bug**
When a sysadmin edit normal user's profile, ckan always reports `Old Password: incorrect password` error message.
**Steps to reproduce**
1. Login as sysadmin.
2. Select a normal user and into Manage page.
3. Typing something in the form exclude change password field.
4. Get the error message.
**Expected behavior**
Sysadmin can correctly update normal user's profile.
**Additional details**
I think that is about this:
https://github.com/ckan/ckan/blob/5e7ea57f97d03219fd2098c8d6848905ba056170/ckan/views/user.py#L287-L290
That will check if the email was changed, but it compare with `g.userobj.email`, i.e. current login user's email.
So when a sysadmin want update normal user's profile, it will always get an error about `Old Password incorrect`.
I am trying to fix it now.
| @asas1asas200 looks like you are not entering your sysadmin password when doing the changes. The current flow could be little bit confusing or misleading because the sysadmin pass field is part of the password changing block
In case that i missinterpreted your inputs, please reopen the issue and if possible add some additional details | 2021-07-01T12:06:09 |
|
ckan/ckan | 6,237 | ckan__ckan-6237 | [
"2317"
] | ca4d764f25f3378b083fa1e0b6b9f67be4c44864 | diff --git a/ckanext/datastore/backend/postgres.py b/ckanext/datastore/backend/postgres.py
--- a/ckanext/datastore/backend/postgres.py
+++ b/ckanext/datastore/backend/postgres.py
@@ -1319,6 +1319,9 @@ def search_data(context, data_dict):
else:
distinct = ''
+ if not sort and not distinct:
+ sort = ['_id']
+
if sort:
sort_clause = 'ORDER BY %s' % (', '.join(sort)).replace('%', '%%')
else:
| Unreliable ordering of datastore results
Hi,
In the absence of an "ORDER BY" clause, PostgreSQL does not make any promises regarding the ordering of rows. In particular if you use "OFFSET/LIMIT" clauses the ordering might actually **change** between two subsequent queries. This is from the PostgreSQL documentation:
> The query planner takes LIMIT into account when generating a query plan, so you are very likely to get different plans (yielding different row orders) depending on what you use for LIMIT and OFFSET. Thus, using different LIMIT/OFFSET values to select different subsets of a query result will give inconsistent results unless you enforce a predictable result ordering with ORDER BY. This is not a bug; it is an inherent consequence of the fact that SQL does not promise to deliver the results of a query in any particular order unless ORDER BY is used to constrain the order.
http://www.postgresql.org/docs/current/static/sql-select.html
This issue affects datastore queries (I have witnessed it). While this is not technically a CKAN bug (the problem can be moved upwards to the API consumers), it is an unexpected behaviour. I would suggest the best place to address this is in the datastore itself, to always ensure queries include an ORDER BY term on a unique key (eg. _id)
I can do a pull request if people agree this is a good thing to do.
| Note that this can be fixed in an extension. (Though I really think it should be fixed in ckan - data scientists using the API shouldn't have to know about issues like these!)
@aliceh75 dev meeting agrees with you :)
Just to confirm, is the `_id` field created by us and indexed?
Yes, the datastore always creates a `_id` field which is a primary key. See:
https://github.com/ckan/ckan/blob/master/ckanext/datastore/db.py#L295
This cannot be overriden by users as fields that start with an underscore are forbidden via the API:
https://github.com/ckan/ckan/blob/master/ckanext/datastore/db.py#L81
Postgresql always indexes the primary key as far as I understand:
> Adding a primary key will automatically create a unique btree index on the column or group of columns used in the primary key.
> http://www.postgresql.org/docs/9.1/static/ddl-constraints.html
So I will create a PR (next week, I'm away until Monday!)
ref #2309 - in CKAN 2.3 sometimes _id field is displayed in preview, and other times it is missing (and on the same dataset).
Not sure why this got closed by me merging a remote PR into a remote repo :( I've re-opened and submitted the PR into CKAN itself.
Is there any progress according to this issue?
We've stumbled into the same problem and would be happy about a fix. The PR seems to be pretty close - where it's getting stuck?
We just need a new PR to review | 2021-07-09T12:22:05 |
|
ckan/ckan | 6,246 | ckan__ckan-6246 | [
"6159"
] | 94194d43667d122bc5a55a45e16b07b4430f3405 | diff --git a/ckan/lib/helpers.py b/ckan/lib/helpers.py
--- a/ckan/lib/helpers.py
+++ b/ckan/lib/helpers.py
@@ -139,8 +139,36 @@ def _is_chained_helper(func):
def chained_helper(func):
- """Decorator function allowing helper functions to be chained.
- """
+ '''Decorator function allowing helper functions to be chained.
+
+ This chain starts with the first chained helper to be registered and
+ ends with the original helper (or a non-chained plugin override
+ version). Chained helpers must accept an extra parameter,
+ specifically the next helper in the chain, for example::
+
+ helper(next_helper, *args, **kwargs).
+
+ The chained helper function may call the next_helper function,
+ optionally passing different values, handling exceptions,
+ returning different values and/or raising different exceptions
+ to the caller.
+
+ Usage::
+
+ from ckan.plugins.toolkit import chained_helper
+
+ @chained_helper
+ def ckan_version(next_func, **kw):
+
+ return next_func(**kw)
+
+ :param func: chained helper function
+ :type func: callable
+
+ :returns: chained helper function
+ :rtype: callable
+
+ '''
func.chained_helper = True
return func
diff --git a/ckan/logic/__init__.py b/ckan/logic/__init__.py
--- a/ckan/logic/__init__.py
+++ b/ckan/logic/__init__.py
@@ -332,6 +332,33 @@ def clear_actions_cache():
def chained_action(func):
+ '''Decorator function allowing action function to be chained.
+
+ This allows a plugin to modify the behaviour of an existing action
+ function. A Chained action function must be defined as
+ ``action_function(original_action, context, data_dict)`` where the
+ first parameter will be set to the action function in the next plugin
+ or in core ckan. The chained action may call the original_action
+ function, optionally passing different values, handling exceptions,
+ returning different values and/or raising different exceptions
+ to the caller.
+
+ Usage::
+
+ from ckan.plugins.toolkit import chained_action
+
+ @chained_action
+ @side_effect_free
+ def package_search(original_action, context, data_dict):
+ return original_action(context, data_dict)
+
+ :param func: chained action function
+ :type func: callable
+
+ :returns: chained action function
+ :rtype: callable
+
+ '''
func.chained_action = True
return func
@@ -634,6 +661,33 @@ def auth_disallow_anonymous_access(action):
def chained_auth_function(func):
'''
Decorator function allowing authentication functions to be chained.
+
+ This chain starts with the last chained auth function to be registered and
+ ends with the original auth function (or a non-chained plugin override
+ version). Chained auth functions must accept an extra parameter,
+ specifically the next auth function in the chain, for example::
+
+ auth_function(next_auth, context, data_dict).
+
+ The chained auth function may call the next_auth function, optionally
+ passing different values, handling exceptions, returning different
+ values and/or raising different exceptions to the caller.
+
+ Usage::
+
+ from ckan.plugins.toolkit import chained_auth_function
+
+ @chained_auth_function
+ @auth_allow_anonymous_access
+ def user_show(next_auth, context, data_dict=None):
+ return next_auth(context, data_dict)
+
+ :param func: chained authentication function
+ :type func: callable
+
+ :returns: chained authentication function
+ :rtype: callable
+
'''
func.chained_auth_function = True
return func
| Chained actions, auth functions and helpers are not documented
**CKAN version**
2.7, 2,8, 2.9, master
**Describe the bug**
Chained actions are missing docstring completely:
https://github.com/ckan/ckan/blob/e89ca125dc68ddb9fe9bad68a401404146ba90c7/ckan/logic/__init__.py#L334-L336
There is a mention of chained actions within get_actions:
https://github.com/ckan/ckan/blob/e89ca125dc68ddb9fe9bad68a401404146ba90c7/ckan/plugins/interfaces.py#L922-L935
Chained auth functions have minimal docstring:
https://github.com/ckan/ckan/blob/e89ca125dc68ddb9fe9bad68a401404146ba90c7/ckan/logic/__init__.py#L634-L639
Chained helpers have minimal docstring:
https://github.com/ckan/ckan/blob/e89ca125dc68ddb9fe9bad68a401404146ba90c7/ckan/lib/helpers.py#L141-L145
Changelogs have minor mentions to them. `chained_action` was added in 2.7 https://github.com/ckan/ckan/pull/3494 and 2.9 docs have a mention to them:

`chained_auth_function` was added in 2.8 https://github.com/ckan/ckan/pull/3995 and docs have a small mention of them:

`chained_helper` is only in master https://github.com/ckan/ckan/pull/5337 and are not mentioned in the changelog.
There is a minor example how to use these in:
https://github.com/ckan/ckan/blob/e89ca125dc68ddb9fe9bad68a401404146ba90c7/ckanext/chained_functions/plugin.py#L32-L46
| 2021-07-12T22:32:09 |
||
ckan/ckan | 6,251 | ckan__ckan-6251 | [
"5968"
] | 61babaa307d4aa43f3f856b446bc366c3e5a72df | diff --git a/ckan/lib/jinja_extensions.py b/ckan/lib/jinja_extensions.py
--- a/ckan/lib/jinja_extensions.py
+++ b/ckan/lib/jinja_extensions.py
@@ -23,7 +23,7 @@
def _get_extensions():
- return ['jinja2.ext.do', 'jinja2.ext.with_',
+ return ['jinja2.ext.do', 'jinja2.ext.loopcontrols',
SnippetExtension,
CkanExtend,
CkanInternationalizationExtension,
| Add jinja2 loop controls extension and remove defunct with_ extension
**CKAN version**
master
**Describe the bug**
The jinja2 loop control extension adds `continue` and `break` statements in jinja templates. The with_ extension is no longer needed as its built-in as of jinja2 2.9.
There's an existing PR for this - https://github.com/ckan/ckan/pull/5519
| 2021-07-14T07:16:50 |
||
ckan/ckan | 6,252 | ckan__ckan-6252 | [
"5946"
] | 61babaa307d4aa43f3f856b446bc366c3e5a72df | diff --git a/ckan/config/middleware/flask_app.py b/ckan/config/middleware/flask_app.py
--- a/ckan/config/middleware/flask_app.py
+++ b/ckan/config/middleware/flask_app.py
@@ -247,6 +247,7 @@ def ungettext_alias():
app.config[u'BABEL_TRANSLATION_DIRECTORIES'] = ';'.join(i18n_dirs)
app.config[u'BABEL_DOMAIN'] = 'ckan'
app.config[u'BABEL_MULTIPLE_DOMAINS'] = ';'.join(i18n_domains)
+ app.config[u'BABEL_DEFAULT_TIMEZONE'] = str(helpers.get_display_timezone())
babel = CKANBabel(app)
| render_datetime helper does not respect ckan.display_timezone configuration
**CKAN version**
N/A
**Describe the bug**
[`ckan.display_timezone`](https://docs.ckan.org/en/latest/maintaining/configuration.html#ckan-display-timezone) sets the timezone to use when displaying dates on the frontend.
The `render_date` template helper however, still uses UTC even if `ckan.display_timezone` is set to a non-UTC timezone.
**Expected behavior**
`render_datetime` should respect the display_timezone setting.
| After further investigation, found that [snippets/local_friendly_datetime.html](https://github.com/ckan/ckan/blob/master/ckan/templates/snippets/local_friendly_datetime.html) is one way to render date in the localised format using the current display_timezone setting.
However, one problem with using a snippet (as with all snippets), is that they're primarily meant for use in templates, not for assigning values that can be readily consumed by Javascript as snippets produce surrounding comments that will need to be parsed out.
Further, the local_friendly_datetime.html snippet does not actually do the conversion. It just creates an HTML snippet with the `automatic-local-datetime` class which is then parsed and converted to the local format by CKAN's main.js.
https://github.com/ckan/ckan/blob/d5ee18452ea1be5a1e2e1cbc14e454b1c6b0d4b4/ckan/public/base/javascript/main.js#L33-L41
Perhaps an additional optional parameter should be added to the `render_datetime` helper to do the localisation/TZ conversion without having to depend on a snippet which can be used everywhere, not just in templates.
`render_datetime` should respect display_timezone setting as it calls https://github.com/ckan/ckan/blob/5aad00921d68721decc0b31b7007d31e0b8b5c15/ckan/lib/helpers.py#L1709 which calls
https://github.com/ckan/ckan/blob/5aad00921d68721decc0b31b7007d31e0b8b5c15/ckan/lib/helpers.py#L180 But of course there might be a bug in there.
Yes. I thought so myself.
However, an earlier check on line 174 if a datetime has timezone info short-circuits it and never reaches line 180.
https://github.com/ckan/ckan/blob/5aad00921d68721decc0b31b7007d31e0b8b5c15/ckan/lib/helpers.py#L174-L182
@Zharktas @jqnatividad I would like to work in this issue But I have following queries :
- Is this issue is specific to a version of CKAN ?
- Where time is displayed in CKAN UI?
Hi, @jqnatividad @Zharktas
Im doing some research around this issue and i noticed few things:
I've changed `ckan.display_timezone` to different timezone than my local (e.g Canada/Saskatchewan) and commented out the javascript snippet (.automatic-local-datetime)

As we can see the UI doesnt respect `ckan.display_timezone` and shows the UTC time.
I noticed that flask-babel [`format_datetime`](https://flask-babel.tkte.ch/#flask_babel.format_datetime) looks like converts the object to users timezone by default, if we pass `rebase=False` at line https://github.com/ckan/ckan/blob/master/ckan/lib/formatters.py#L55
it shows correct value.

What's your opinion over this? | 2021-07-14T07:30:47 |
|
ckan/ckan | 6,271 | ckan__ckan-6271 | [
"6051"
] | 24e85e560743ab7a9b4da8e4697e1ad6f565e642 | diff --git a/ckan/lib/i18n.py b/ckan/lib/i18n.py
--- a/ckan/lib/i18n.py
+++ b/ckan/lib/i18n.py
@@ -295,7 +295,7 @@ def _build_js_translation(lang, source_filenames, entries, dest_filename):
ordered_plural = sorted(entry.msgstr_plural.items())
for order, msgstr in ordered_plural:
plural.append(msgstr)
- with open(dest_filename, u'w') as f:
+ with open(dest_filename, u'w', encoding='utf-8') as f:
s = json.dumps(result, sort_keys=True, indent=2, ensure_ascii=False)
f.write(six.ensure_str(s))
diff --git a/ckan/views/api.py b/ckan/views/api.py
--- a/ckan/views/api.py
+++ b/ckan/views/api.py
@@ -479,7 +479,7 @@ def i18n_js_translations(lang, ver=API_REST_DEFAULT_VERSION):
u'base', u'i18n', u'{0}.js'.format(lang)))
if not os.path.exists(source):
return u'{}'
- translations = json.load(open(source, u'r'))
+ translations = json.load(open(source, u'r', encoding='utf-8'))
return _finish_ok(translations)
| i18n js files are empty and datasets are not shown
**CKAN 2.9.2**
Ubuntu 18.04
**Describe the bug**
The error occurs after upgrading from Python 2.7 to 3.6.
When navigating to a dataset the data isn't shown, but a loading spinner animation.
The devtools reveal there was an XHR call to `/api/i18n/de` which responded with a 500 error status code.
The web server logs contain an error message:
`File "/usr/lib/ckan/default/lib/python3.6/site-packages/simplejson/decoder.py", line 404, in raw_decode
return self.scan_once(s, idx=_w(s, idx).end())
simplejson.scanner.JSONDecodeError: Expecting value: line 1 column 1 (char 0)`
I think the cause is that the js files in /usr/lib/ckan/default/src/ckan/ckan/public/base/i18n are empty. First there was a file permission problem I had to solve. Then you could watch them being created one by one on the first run. The files in the old Python 2 environment are not empty. I tried to copy `de.js` from Python 2 to Python 3 environment, but this doesn't work and results in a different error:
`UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 156: ordinal not in range(128)`
_But how do I know if the XHR call is related to the dataset problem?_
I guess there is some sort of unicode incompatibility between Python2 and Python3. To avoid unicode problems I replaced the german i18n file (`de.js`) in the new Python 3 env by the english file (`en.js`) from Python 2. After that the dataset is shown and the error 500 is gone.
**Steps to reproduce**
- Upgrade Python 2 to Python 3 (https://docs.ckan.org/en/2.9/maintaining/upgrading/upgrade-to-python3.html)
- Run application (`sudo systemctl start apache2`)
- Open page with dataset
**Expected behavior**
- dataset is being shown
- Status 200 for XHR request `/api/i18n/de`
- i18n js files not to be empty
**Additional details**
Stack trace:
```
2021-04-28 10:05:39,522 ERROR [ckan.config.middleware.flask_app] Expecting value: line 1 column 1 (char 0)
Traceback (most recent call last):
File "/usr/lib/ckan/default/lib/python3.6/site-packages/flask/app.py", line 1949, in full_dispatch_request
rv = self.dispatch_request()
File "/usr/lib/ckan/default/lib/python3.6/site-packages/flask/app.py", line 1935, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/usr/lib/ckan/default/src/ckan/ckan/config/middleware/../../views/api.py", line 482, in i18n_js_translations
translations = json.load(open(source, u'r'))
File "/usr/lib/ckan/default/lib/python3.6/site-packages/simplejson/__init__.py", line 459, in load
use_decimal=use_decimal, **kw)
File "/usr/lib/ckan/default/lib/python3.6/site-packages/simplejson/__init__.py", line 516, in loads
return _default_decoder.decode(s)
File "/usr/lib/ckan/default/lib/python3.6/site-packages/simplejson/decoder.py", line 374, in decode
obj, end = self.raw_decode(s)
File "/usr/lib/ckan/default/lib/python3.6/site-packages/simplejson/decoder.py", line 404, in raw_decode
return self.scan_once(s, idx=_w(s, idx).end())
simplejson.scanner.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
```
Screenshot:

| 2021-07-21T08:59:11 |
||
ckan/ckan | 6,286 | ckan__ckan-6286 | [
"6285"
] | 45f9e1aefa095973e0f4355aa1f63842d16e90ca | diff --git a/ckan/lib/search/__init__.py b/ckan/lib/search/__init__.py
--- a/ckan/lib/search/__init__.py
+++ b/ckan/lib/search/__init__.py
@@ -257,16 +257,11 @@ def clear_all():
def _get_schema_from_solr(file_offset):
solr_url, solr_user, solr_password = SolrSettings.get()
- http_auth = None
- if solr_user is not None and solr_password is not None:
- http_auth = solr_user + ':' + solr_password
- http_auth = 'Basic {}'.format(base64.b64encode(http_auth.encode('utf8')).strip())
-
url = solr_url.strip('/') + file_offset
- if http_auth:
+ if solr_user is not None and solr_password is not None:
response = requests.get(
- url, headers={'Authorization': http_auth})
+ url, auth=requests.auth.HTTPBasicAuth(solr_user, solr_password))
else:
response = requests.get(url)
| ckan.lib.search.common.SearchError: Could not extract version info from the SOLR schema
**CKAN version**
2.9.3 (deb)
**Describe the bug**
CKAN fails to fetch the Solr schema using basic auth (401s)
**Steps to reproduce**
In ckan.ini
```
solr_url = http://solr:8983/solr/ckan
solr_user = solr
solr_password = pass
```
Then run CKAN with
`ckan run`
**Expected behavior**
CKAN to fetch the Solr schema and version
**Additional details**
```sh
root@ckan-78f8b8bdb5-c72ch:/# ckan run
2021-07-27 03:30:48,904 INFO [ckan.cli] Using configuration file /etc/ckan/default/ckan.ini
2021-07-27 03:30:48,905 INFO [ckan.config.environment] Loading static files from public
Traceback (most recent call last):
File "/usr/lib/ckan/default/bin/ckan", line 11, in <module>
load_entry_point('ckan', 'console_scripts', 'ckan')()
File "/usr/lib/ckan/default/lib/python3.8/site-packages/click/core.py", line 829, in __call__
return self.main(*args, **kwargs)
File "/usr/lib/ckan/default/lib/python3.8/site-packages/click/core.py", line 781, in main
with self.make_context(prog_name, args, **extra) as ctx:
File "/usr/lib/ckan/default/lib/python3.8/site-packages/click/core.py", line 700, in make_context
self.parse_args(ctx, args)
File "/usr/lib/ckan/default/lib/python3.8/site-packages/click/core.py", line 1212, in parse_args
rest = Command.parse_args(self, ctx, args)
File "/usr/lib/ckan/default/lib/python3.8/site-packages/click/core.py", line 1048, in parse_args
value, args = param.handle_parse_result(ctx, opts, args)
File "/usr/lib/ckan/default/lib/python3.8/site-packages/click/core.py", line 1630, in handle_parse_result
value = invoke_param_callback(self.callback, ctx, self, value)
File "/usr/lib/ckan/default/lib/python3.8/site-packages/click/core.py", line 123, in invoke_param_callback
return callback(ctx, param, value)
File "/usr/lib/ckan/default/src/ckan/ckan/cli/cli.py", line 102, in _init_ckan_config
ctx.obj = CkanCommand(value)
File "/usr/lib/ckan/default/src/ckan/ckan/cli/cli.py", line 52, in __init__
self.app = make_app(self.config)
File "/usr/lib/ckan/default/src/ckan/ckan/config/middleware/__init__.py", line 56, in make_app
load_environment(conf)
File "/usr/lib/ckan/default/src/ckan/ckan/config/environment.py", line 123, in load_environment
p.load_all()
File "/usr/lib/ckan/default/src/ckan/ckan/plugins/core.py", line 161, in load_all
unload_all()
File "/usr/lib/ckan/default/src/ckan/ckan/plugins/core.py", line 208, in unload_all
unload(*reversed(_PLUGINS))
File "/usr/lib/ckan/default/src/ckan/ckan/plugins/core.py", line 236, in unload
plugins_update()
File "/usr/lib/ckan/default/src/ckan/ckan/plugins/core.py", line 153, in plugins_update
environment.update_config()
File "/usr/lib/ckan/default/src/ckan/ckan/config/environment.py", line 236, in update_config
search.check_solr_schema_version()
File "/usr/lib/ckan/default/src/ckan/ckan/lib/search/__init__.py", line 327, in check_solr_schema_version
raise SearchError(msg)
ckan.lib.search.common.SearchError: Could not extract version info from the SOLR schema
root@ckan-78f8b8bdb5-c72ch:/#
```
Have already applied this patch #6179
| 2021-07-27T04:30:28 |
||
ckan/ckan | 6,326 | ckan__ckan-6326 | [
"5684"
] | 6769ee4043684bb420783719fff456adb2e5b49e | diff --git a/ckanext/stats/blueprint.py b/ckanext/stats/blueprint.py
--- a/ckanext/stats/blueprint.py
+++ b/ckanext/stats/blueprint.py
@@ -1,8 +1,8 @@
# encoding: utf-8
-
from flask import Blueprint
from ckan.plugins.toolkit import render
+import ckan.lib.helpers as h
import ckanext.stats.stats as stats_lib
@@ -13,8 +13,41 @@
def index():
stats = stats_lib.Stats()
extra_vars = {
- u'largest_groups': stats.largest_groups(),
- u'top_tags': stats.top_tags(),
- u'top_package_creators': stats.top_package_creators(),
+ 'largest_groups': stats.largest_groups(),
+ 'top_tags': stats.top_tags(),
+ 'top_package_creators': stats.top_package_creators(),
+ 'most_edited_packages': stats.most_edited_packages(),
+ 'new_packages_by_week': stats.get_by_week('new_packages'),
+ 'deleted_packages_by_week': stats.get_by_week('deleted_packages'),
+ 'num_packages_by_week': stats.get_num_packages_by_week(),
+ 'package_revisions_by_week': stats.get_by_week('package_revisions')
}
+
+ extra_vars['raw_packages_by_week'] = []
+ for week_date, num_packages, cumulative_num_packages\
+ in stats.get_num_packages_by_week():
+ extra_vars['raw_packages_by_week'].append(
+ {'date': h.date_str_to_datetime(week_date),
+ 'total_packages': cumulative_num_packages})
+
+ extra_vars['raw_all_package_revisions'] = []
+ for week_date, revs, num_revisions, cumulative_num_revisions\
+ in stats.get_by_week('package_revisions'):
+ extra_vars['raw_all_package_revisions'].append(
+ {'date': h.date_str_to_datetime(week_date),
+ 'total_revisions': num_revisions})
+
+ extra_vars['raw_new_datasets'] = []
+ for week_date, pkgs, num_packages, cumulative_num_revisions\
+ in stats.get_by_week('new_packages'):
+ extra_vars['raw_new_datasets'].append(
+ {'date': h.date_str_to_datetime(week_date),
+ 'new_packages': num_packages})
+
+ extra_vars['raw_deleted_datasets'] = []
+ for week_date, pkgs, num_packages, cumulative_num_packages\
+ in stats.get_by_week('deleted_packages'):
+ extra_vars['raw_deleted_datasets'].append(
+ {'date': h.date_str_to_datetime(
+ week_date), 'deleted_packages': num_packages})
return render(u'ckanext/stats/index.html', extra_vars)
diff --git a/ckanext/stats/plugin.py b/ckanext/stats/plugin.py
--- a/ckanext/stats/plugin.py
+++ b/ckanext/stats/plugin.py
@@ -14,10 +14,10 @@ class StatsPlugin(p.SingletonPlugin):
p.implements(p.IConfigurer)
p.implements(p.IBlueprint)
- def get_blueprint(self):
- return blueprint.stats
-
def update_config(self, config):
p.toolkit.add_template_directory(config, u'templates')
p.toolkit.add_public_directory(config, u'public')
p.toolkit.add_resource(u'public/ckanext/stats', u'ckanext_stats')
+
+ def get_blueprint(self):
+ return blueprint.stats
diff --git a/ckanext/stats/stats.py b/ckanext/stats/stats.py
--- a/ckanext/stats/stats.py
+++ b/ckanext/stats/stats.py
@@ -11,15 +11,15 @@
log = logging.getLogger(__name__)
cache_enabled = p.toolkit.asbool(
- config.get('ckanext.stats.cache_enabled', False)
+ config.get("ckanext.stats.cache_enabled", False)
)
if cache_enabled:
log.warn(
- 'ckanext.stats does not support caching in current implementations'
+ "ckanext.stats does not support caching in current implementations"
)
-DATE_FORMAT = '%Y-%m-%d'
+DATE_FORMAT = "%Y-%m-%d"
def table(name):
@@ -31,23 +31,28 @@ def datetime2date(datetime_):
class Stats(object):
-
@classmethod
def largest_groups(cls, limit=10):
- member = table('member')
- package = table('package')
+ package = table("package")
+ activity = table("activity")
- j = join(member, package, member.c.table_id == package.c.id)
+ j = join(activity, package, activity.c.object_id == package.c.id)
- s = select(
- [member.c.group_id,
- func.count(member.c.table_id)]
- ).select_from(j).group_by(member.c.group_id).where(
- and_(
- member.c.group_id != None, member.c.table_name == 'package',
- package.c.private == False, package.c.state == 'active'
+ s = (
+ select([package.c.owner_org, func.count(package.c.id)])
+ .select_from(j)
+ .group_by(package.c.owner_org)
+ .where(
+ and_(
+ package.c.owner_org != None,
+ activity.c.activity_type == "new package",
+ package.c.private == False,
+ package.c.state == "active",
+ )
)
- ).order_by(func.count(member.c.table_id).desc()).limit(limit)
+ .order_by(func.count(package.c.id).desc())
+ .limit(limit)
+ )
res_ids = model.Session.execute(s).fetchall()
res_groups = [
@@ -57,12 +62,12 @@ def largest_groups(cls, limit=10):
return res_groups
@classmethod
- def top_tags(cls, limit=10, returned_tag_info='object'): # by package
- assert returned_tag_info in ('name', 'id', 'object')
- tag = table('tag')
- package_tag = table('package_tag')
- package = table('package')
- if returned_tag_info == 'name':
+ def top_tags(cls, limit=10, returned_tag_info="object"): # by package
+ assert returned_tag_info in ("name", "id", "object")
+ tag = table("tag")
+ package_tag = table("package_tag")
+ package = table("package")
+ if returned_tag_info == "name":
from_obj = [package_tag.join(tag)]
tag_column = tag.c.name
else:
@@ -71,22 +76,29 @@ def top_tags(cls, limit=10, returned_tag_info='object'): # by package
j = join(
package_tag, package, package_tag.c.package_id == package.c.id
)
- s = select([tag_column,
- func.count(package_tag.c.package_id)],
- from_obj=from_obj).select_from(j).where(
- and_(
- package_tag.c.state == 'active',
- package.c.private == False,
- package.c.state == 'active'
- )
- )
- s = s.group_by(tag_column).order_by(
- func.count(package_tag.c.package_id).desc()
- ).limit(limit)
+ s = (
+ select(
+ [tag_column, func.count(package_tag.c.package_id)],
+ from_obj=from_obj,
+ )
+ .select_from(j)
+ .where(
+ and_(
+ package_tag.c.state == "active",
+ package.c.private == False,
+ package.c.state == "active",
+ )
+ )
+ )
+ s = (
+ s.group_by(tag_column)
+ .order_by(func.count(package_tag.c.package_id).desc())
+ .limit(limit)
+ )
res_col = model.Session.execute(s).fetchall()
- if returned_tag_info in ('id', 'name'):
+ if returned_tag_info in ("id", "name"):
return res_col
- elif returned_tag_info == 'object':
+ elif returned_tag_info == "object":
res_tags = [
(model.Session.query(model.Tag).get(text_type(tag_id)), val)
for tag_id, val in res_col
@@ -95,17 +107,329 @@ def top_tags(cls, limit=10, returned_tag_info='object'): # by package
@classmethod
def top_package_creators(cls, limit=10):
- userid_count = model.Session.query(
- model.Package.creator_user_id,
- func.count(model.Package.creator_user_id)
- ).filter(model.Package.state == 'active'
- ).filter(model.Package.private == False).group_by(
- model.Package.creator_user_id
- ).order_by(func.count(model.Package.creator_user_id).desc()
- ).limit(limit).all()
+ userid_count = (
+ model.Session.query(
+ model.Package.creator_user_id,
+ func.count(model.Package.creator_user_id),
+ )
+ .filter(model.Package.state == "active")
+ .filter(model.Package.private == False)
+ .group_by(model.Package.creator_user_id)
+ .order_by(func.count(model.Package.creator_user_id).desc())
+ .limit(limit)
+ .all()
+ )
user_count = [
(model.Session.query(model.User).get(text_type(user_id)), count)
for user_id, count in userid_count
if user_id
]
return user_count
+
+ @classmethod
+ def most_edited_packages(cls, limit=10):
+ package = table("package")
+ activity = table("activity")
+
+ s = (
+ select(
+ [package.c.id, func.count(activity.c.id)],
+ from_obj=[
+ activity.join(
+ package, activity.c.object_id == package.c.id
+ )
+ ],
+ )
+ .where(
+ and_(
+ package.c.private == False,
+ activity.c.activity_type == "changed package",
+ package.c.state == "active",
+ )
+ )
+ .group_by(package.c.id)
+ .order_by(func.count(activity.c.id).desc())
+ .limit(limit)
+ )
+ res_ids = model.Session.execute(s).fetchall()
+ res_pkgs = [
+ (model.Session.query(model.Package).get(text_type(pkg_id)), val)
+ for pkg_id, val in res_ids
+ ]
+ return res_pkgs
+
+ @classmethod
+ def get_package_revisions(cls):
+ """
+ @return: Returns list of revisions and date of them, in
+ format: [(id, date), ...]
+ """
+ package = table("package")
+ activity = table("activity")
+ s = select(
+ [package.c.id, activity.c.timestamp],
+ from_obj=[
+ activity.join(package, activity.c.object_id == package.c.id)
+ ],
+ ).order_by(activity.c.timestamp)
+ res = model.Session.execute(s).fetchall() # [(id, datetime), ...]
+ return res
+
+ @classmethod
+ def get_by_week(cls, object_type):
+ cls._object_type = object_type
+
+ def objects_by_week():
+ if cls._object_type == "new_packages":
+ objects = cls.get_new_packages()
+
+ def get_date(object_date):
+ return datetime.date.fromordinal(object_date)
+
+ elif cls._object_type == "deleted_packages":
+ objects = cls.get_deleted_packages()
+
+ def get_date(object_date):
+ return datetime.date.fromordinal(object_date)
+
+ elif cls._object_type == "package_revisions":
+ objects = cls.get_package_revisions()
+
+ def get_date(object_date):
+ return datetime2date(object_date)
+
+ else:
+ raise NotImplementedError()
+ first_date = (
+ get_date(objects[0][1]) if objects else datetime.date.today()
+ )
+ week_commences = cls.get_date_week_started(first_date)
+ week_ends = week_commences + datetime.timedelta(days=7)
+ week_index = 0
+ weekly_pkg_ids = [] # [(week_commences, [pkg_id1, pkg_id2, ...])]
+ pkg_id_stack = []
+ cls._cumulative_num_pkgs = 0
+
+ def build_weekly_stats(week_commences, pkg_ids):
+ num_pkgs = len(pkg_ids)
+ cls._cumulative_num_pkgs += num_pkgs
+ return (
+ week_commences.strftime(DATE_FORMAT),
+ pkg_ids,
+ num_pkgs,
+ cls._cumulative_num_pkgs,
+ )
+
+ for pkg_id, date_field in objects:
+ date_ = get_date(date_field)
+ if date_ >= week_ends:
+ weekly_pkg_ids.append(
+ build_weekly_stats(week_commences, pkg_id_stack)
+ )
+ pkg_id_stack = []
+ week_commences = week_ends
+ week_ends = week_commences + datetime.timedelta(days=7)
+ pkg_id_stack.append(pkg_id)
+ weekly_pkg_ids.append(
+ build_weekly_stats(week_commences, pkg_id_stack)
+ )
+ today = datetime.date.today()
+ while week_ends <= today:
+ week_commences = week_ends
+ week_ends = week_commences + datetime.timedelta(days=7)
+ weekly_pkg_ids.append(build_weekly_stats(week_commences, []))
+ return weekly_pkg_ids
+
+ if cache_enabled:
+ log.warn(
+ "ckanext.stats does not support caching in current\
+ implementations"
+ )
+ else:
+ objects_by_week_ = objects_by_week()
+ return objects_by_week_
+
+ @classmethod
+ def get_new_packages(cls):
+ """
+ @return: Returns list of new pkgs and date when they were created, in
+ format: [(id, date_ordinal), ...]
+ """
+
+ def new_packages():
+ # Can't filter by time in select because 'min' function has to
+ # be 'for all time' else you get first revision in the time period.
+ package = table("package")
+ activity = table("activity")
+ s = (
+ select(
+ [package.c.id, func.min(activity.c.timestamp)],
+ from_obj=[
+ activity.join(
+ package, activity.c.object_id == package.c.id
+ )
+ ],
+ )
+ .group_by(package.c.id)
+ .order_by(func.min(activity.c.timestamp))
+ )
+ res = model.Session.execute(s).fetchall() # [(id, datetime), ...]
+ res_pickleable = []
+ for pkg_id, created_datetime in res:
+ res_pickleable.append((pkg_id, created_datetime.toordinal()))
+ return res_pickleable
+
+ if cache_enabled:
+ log.warn(
+ "ckanext.stats does not support caching in current\
+ implementations"
+ )
+ else:
+ new_packages = new_packages()
+ return new_packages
+
+ @classmethod
+ def get_date_week_started(cls, date_):
+ assert isinstance(date_, datetime.date)
+ if isinstance(date_, datetime.datetime):
+ date_ = datetime2date(date_)
+ return date_ - datetime.timedelta(days=datetime.date.weekday(date_))
+
+ @classmethod
+ def get_num_packages_by_week(cls):
+ def num_packages():
+ new_packages_by_week = cls.get_by_week("new_packages")
+ deleted_packages_by_week = cls.get_by_week("deleted_packages")
+ first_date = (
+ min(
+ datetime.datetime.strptime(
+ new_packages_by_week[0][0], DATE_FORMAT
+ ),
+ datetime.datetime.strptime(
+ deleted_packages_by_week[0][0], DATE_FORMAT
+ ),
+ )
+ ).date()
+ cls._cumulative_num_pkgs = 0
+ new_pkgs = []
+ deleted_pkgs = []
+
+ def build_weekly_stats(
+ week_commences, new_pkg_ids, deleted_pkg_ids
+ ):
+ num_pkgs = len(new_pkg_ids) - len(deleted_pkg_ids)
+ new_pkgs.extend(
+ [
+ model.Session.query(model.Package).get(id).name
+ for id in new_pkg_ids
+ ]
+ )
+ deleted_pkgs.extend(
+ [
+ model.Session.query(model.Package).get(id).name
+ for id in deleted_pkg_ids
+ ]
+ )
+ cls._cumulative_num_pkgs += num_pkgs
+ return (
+ week_commences.strftime(DATE_FORMAT),
+ num_pkgs,
+ cls._cumulative_num_pkgs,
+ )
+
+ week_ends = first_date
+ today = datetime.date.today()
+ new_package_week_index = 0
+ deleted_package_week_index = 0
+ # [(week_commences, num_packages, cumulative_num_pkgs])]
+ weekly_numbers = []
+ while week_ends <= today:
+ week_commences = week_ends
+ week_ends = week_commences + datetime.timedelta(days=7)
+ if (
+ datetime.datetime.strptime(
+ new_packages_by_week[new_package_week_index][0],
+ DATE_FORMAT,
+ ).date()
+ == week_commences
+ ):
+ new_pkg_ids = new_packages_by_week[new_package_week_index][
+ 1
+ ]
+ new_package_week_index += 1
+ else:
+ new_pkg_ids = []
+ if (
+ datetime.datetime.strptime(
+ deleted_packages_by_week[deleted_package_week_index][
+ 0
+ ],
+ DATE_FORMAT,
+ ).date()
+ == week_commences
+ ):
+ deleted_pkg_ids = deleted_packages_by_week[
+ deleted_package_week_index
+ ][1]
+ deleted_package_week_index += 1
+ else:
+ deleted_pkg_ids = []
+ weekly_numbers.append(
+ build_weekly_stats(
+ week_commences, new_pkg_ids, deleted_pkg_ids
+ )
+ )
+ # just check we got to the end of each count
+ assert new_package_week_index == len(new_packages_by_week)
+ assert deleted_package_week_index == len(deleted_packages_by_week)
+ return weekly_numbers
+
+ if cache_enabled:
+ log.warn(
+ "ckanext.stats does not support caching in current\
+ implementations"
+ )
+ else:
+ num_packages = num_packages()
+ return num_packages
+
+ @classmethod
+ def get_deleted_packages(cls):
+ """
+ @return: Returns list of deleted pkgs and date when they were deleted,
+ in format: [(id, date_ordinal), ...]
+ """
+
+ def deleted_packages():
+ # Can't filter by time in select because 'min' function has to
+ # be 'for all time' else you get first revision in the time period.
+ package = table("package")
+ activity = table("activity")
+
+ s = (
+ select(
+ [package.c.id, func.min(activity.c.timestamp)],
+ from_obj=[
+ activity.join(
+ package, activity.c.object_id == package.c.id
+ )
+ ],
+ )
+ .where(activity.c.activity_type == "deleted package")
+ .group_by(package.c.id)
+ .order_by(func.min(activity.c.timestamp))
+ )
+ res = model.Session.execute(s).fetchall() # [(id, datetime), ...]
+ res_pickleable = []
+ for pkg_id, deleted_datetime in res:
+ res_pickleable.append((pkg_id, deleted_datetime.toordinal()))
+ return res_pickleable
+
+ if cache_enabled:
+ log.warn(
+ "ckanext.stats does not support caching in current\
+ implementations"
+ )
+ else:
+ deleted_packages = deleted_packages()
+ return deleted_packages
| diff --git a/ckanext/stats/tests/test_stats_lib.py b/ckanext/stats/tests/test_stats_lib.py
--- a/ckanext/stats/tests/test_stats_lib.py
+++ b/ckanext/stats/tests/test_stats_lib.py
@@ -1,35 +1,41 @@
# encoding: utf-8
import pytest
+import copy
+import datetime
from ckan import model
from ckan.tests import factories
+
from ckanext.stats.stats import Stats
@pytest.mark.ckan_config('ckan.plugins', 'stats')
@pytest.mark.usefixtures("with_plugins", "with_request_context")
[email protected]_time
class TestStatsPlugin(object):
@pytest.fixture(autouse=True)
- def initial_data(self, clean_db, with_request_context):
+ def initial_data(self, clean_db, with_request_context, freezer):
+ # week 1
+ freezer.move_to('2011-1-5')
user = factories.User(name="bob")
org_users = [{"name": user["name"], "capacity": "editor"}]
org1 = factories.Organization(name="org1", users=org_users)
group2 = factories.Group()
tag1 = {"name": "tag1"}
tag2 = {"name": "tag2"}
- factories.Dataset(
+ dataset1 = factories.Dataset(
name="test1", owner_org=org1["id"], tags=[tag1], user=user
)
- factories.Dataset(
+ dataset2 = factories.Dataset(
name="test2",
owner_org=org1["id"],
groups=[{"name": group2["name"]}],
tags=[tag1],
user=user,
)
- factories.Dataset(
+ dataset3 = factories.Dataset(
name="test3",
owner_org=org1["id"],
groups=[{"name": group2["name"]}],
@@ -37,21 +43,66 @@ def initial_data(self, clean_db, with_request_context):
user=user,
private=True,
)
- factories.Dataset(name="test4", user=user)
+ dataset4 = factories.Dataset(name="test4", user=user)
# week 2
- model.Package.by_name(u"test2").delete()
+ freezer.move_to('2011-1-12')
+ model.Package.by_name(u'test2').delete()
+ activity2 = factories.Activity(
+ user_id=user["id"],
+ object_id=dataset2["id"],
+ activity_type="deleted package",
+ data={"package": copy.deepcopy(
+ dataset1), "actor": "Mr Someone"},
+ )
model.repo.commit_and_remove()
# week 3
- model.Package.by_name(u"test3").title = "Test 3"
+ freezer.move_to('2011-1-19')
+ dataset3['title'] = "Test 3"
model.repo.commit_and_remove()
- model.Package.by_name(u"test4").title = "Test 4"
+ dataset1['title'] = 'Test 1'
+ factories.Activity(
+ user_id=user["id"],
+ object_id=dataset1["id"],
+ activity_type="changed package",
+ data={"package": copy.deepcopy(dataset1), "actor": "Mr Someone"},
+ )
+ freezer.move_to('2011-1-20')
+ model.repo.commit_and_remove()
+ dataset4['title'] = 'Test 4'
+ factories.Activity(
+ user_id=user["id"],
+ object_id=dataset4["id"],
+ activity_type="changed package",
+ data={"package": copy.deepcopy(dataset4), "actor": "Mr Someone"},
+ )
model.repo.commit_and_remove()
# week 4
- model.Package.by_name(u"test3").notes = "Test 3 notes"
+ freezer.move_to('2011-1-26')
+ dataset3['notes'] = "Test 3 notes"
model.repo.commit_and_remove()
+ dataset4['notes'] = 'test4 dataset'
+ factories.Activity(
+ user_id=user["id"],
+ object_id=dataset4["id"],
+ activity_type="changed package",
+ data={"package": copy.deepcopy(dataset4), "actor": "Mr Someone"},
+ )
+ model.repo.commit_and_remove()
+
+ def test_most_edited_packages(self):
+ pkgs = Stats.most_edited_packages()
+ pkgs = [(pkg.name, count) for pkg, count in pkgs]
+ # test2 does not come up because it was deleted
+ # test3 does not come up because it is private
+ test1 = 'test1', 1
+ test4 = 'test4', 2
+ assert len(pkgs[0]) == len(test1)
+ assert all([a == b for a, b in zip(pkgs[0], test4)])
+ assert len(pkgs[1]) == len(test4)
+ assert all([a == b for a, b in zip(pkgs[1], test1)])
def test_largest_groups(self):
grps = Stats.largest_groups()
@@ -73,3 +124,84 @@ def test_top_package_creators(self):
# Only 2 shown because one of them was deleted and the other one is
# private
assert creators == [("bob", 2)]
+
+ def test_new_packages_by_week(self):
+ new_packages_by_week = Stats.get_by_week('new_packages')
+ # only 3 shown because one of them is private
+ # private packages are not shown in activity table
+ data1 = ('2011-01-03', set((u'test1', u'test2', u'test4')),
+ 3, 3)
+ data2 = ('2011-01-10', set([]), 0, 3)
+ data3 = ('2011-01-17', set([]), 0, 3)
+ data4 = ('2011-01-24', set([]), 0, 3)
+
+ def get_results(week_number):
+ date, ids, num, cumulative = new_packages_by_week[week_number]
+ return (date, set([model.Session.query(model.Package).get(id).name
+ for id in ids]), num, cumulative)
+
+ assert len(get_results(0)) == len(data1)
+ assert all([a == b for a, b in zip(get_results(0), data1)])
+ assert len(get_results(1)) == len(data2)
+ assert all([a == b for a, b in zip(get_results(1), data2)])
+ assert len(get_results(2)) == len(data3)
+ assert all([a == b for a, b in zip(get_results(2), data3)])
+ assert len(get_results(3)) == len(data4)
+ assert all([a == b for a, b in zip(get_results(3), data4)])
+
+ def test_deleted_packages_by_week(self):
+ deleted_packages_by_week = Stats.get_by_week(
+ 'deleted_packages')
+ data1 = ('2011-01-10', ['test2'], 1, 1)
+ data2 = ('2011-01-17', [], 0, 1)
+ data3 = ('2011-01-24', [], 0, 1)
+
+ def get_results(week_number):
+ date, ids, num, cumulative = deleted_packages_by_week[week_number]
+ return (date, [model.Session.query(model.Package).get(id).name for
+ id in ids], num, cumulative)
+ assert len(get_results(0)) == len(data1)
+ assert all([a == b for a, b in zip(get_results(0), data1)])
+ assert len(get_results(1)) == len(data2)
+ assert all([a == b for a, b in zip(get_results(1), data2)])
+ assert len(get_results(2)) == len(data3)
+ assert all([a == b for a, b in zip(get_results(2), data3)])
+
+ def test_revisions_by_week(self):
+ revisions_by_week = Stats.get_by_week('package_revisions')
+
+ def get_results(week_number):
+ date, ids, num, cumulative = revisions_by_week[week_number]
+ return (date, num, cumulative)
+ num_setup_revs = revisions_by_week[0][2]
+ data1 = ('2011-01-03', num_setup_revs, num_setup_revs)
+ data2 = ('2011-01-10', 1, num_setup_revs + 1)
+ data3 = ('2011-01-17', 2, num_setup_revs + 3)
+ data4 = ('2011-01-24', 1, num_setup_revs + 4)
+ assert 6 > num_setup_revs > 2, num_setup_revs
+ assert len(get_results(0)) == len(data1)
+ assert all([a == b for a, b in zip(get_results(0), data1)])
+ assert len(get_results(1)) == len(data2)
+ assert all([a == b for a, b in zip(get_results(1), data2)])
+ assert len(get_results(2)) == len(data3)
+ assert all([a == b for a, b in zip(get_results(2), data3)])
+ assert len(get_results(3)) == len(data4)
+ assert all([a == b for a, b in zip(get_results(3), data4)])
+
+ def test_num_packages_by_week(self):
+ num_packages_by_week = Stats.get_num_packages_by_week()
+ # only 3 shown because one of them is private
+ # private packages are not shown in activity table
+ data1 = ('2011-01-03', 3, 3)
+ data2 = ('2011-01-10', -1, 2)
+ data3 = ('2011-01-17', 0, 2)
+ data4 = ('2011-01-24', 0, 2)
+ # e.g. [('2011-05-30', 3, 3)]
+ assert len(num_packages_by_week[0]) == len(data1)
+ assert all([a == b for a, b in zip(num_packages_by_week[0], data1)])
+ assert len(num_packages_by_week[1]) == len(data2)
+ assert all([a == b for a, b in zip(num_packages_by_week[1], data2)])
+ assert len(num_packages_by_week[2]) == len(data3)
+ assert all([a == b for a, b in zip(num_packages_by_week[2], data3)])
+ assert len(num_packages_by_week[3]) == len(data4)
+ assert all([a == b for a, b in zip(num_packages_by_week[3], data4)])
| Recreate removed stats functionality using Activity Streams
**CKAN version**
2.9.1
**Describe the bug**
When Revisions were deprecated, some dependent code in stats needed to be removed (#5215). However, these stats are necessary for the effective maintenance of CKAN installations by sysadmins/org admins - specifically:
- most_edited
- new_packages_by_week
- deleted_packages_by_week
- num_packages_by_week
- most_edited_by_week
**Steps to reproduce**
Go to `/stats` page.
**Expected behavior**
The detailed stats are restored by using activity streams.
| @jqnatividad @smotornyuk , I am interested to work on this issue. In this issue I understand that stats functionality needs to be recreated and rendered to activity stream (https://github.com/ckan/ckan/blob/2.9/ckan/templates/snippets/activity_stream.html). Please confirm my understanding. Thankyou : )
No. Stats functionality just needs to be recreated. Just forget about activity streams.
### stats functionality needs to be recreated SOMEHOW and rendered exactly as before(as much as possible)
@smotornyuk @jqnatividad , I have investigated the source code of stats (2.8 and 2.9). I am stuck at what to use in place of revisions. I am keeping this on hold from my end.
Use activities instead of revisions
@smotornyuk, Do I need to develop stats functionality here https://github.com/ckan/ckan/blob/master/ckan/views/dataset.py#L1127-L1166 and render it to https://github.com/ckan/ckan/blob/master/ckanext/stats/templates/ckanext/stats/index.html? Please confirm my understanding. Thanks :) | 2021-08-16T09:50:13 |
ckan/ckan | 6,338 | ckan__ckan-6338 | [
"5490"
] | 44c58ce81ce58d9a352e02b61e443a5bc84bef50 | diff --git a/ckan/logic/action/get.py b/ckan/logic/action/get.py
--- a/ckan/logic/action/get.py
+++ b/ckan/logic/action/get.py
@@ -1354,12 +1354,10 @@ def tag_show(context, data_dict):
def user_show(context, data_dict):
'''Return a user account.
- Either the ``id`` or the ``user_obj`` parameter must be given.
+ Either the ``id`` should be passed or the user should be logged in.
:param id: the id or name of the user (optional)
:type id: string
- :param user_obj: the user dictionary of the user (optional)
- :type user_obj: user dictionary
:param include_datasets: Include a list of datasets the user has created.
If it is the same user or a sysadmin requesting, it includes datasets
that are draft or private.
@@ -1386,13 +1384,13 @@ def user_show(context, data_dict):
'''
model = context['model']
+ if 'user' in context and 'id' not in data_dict:
+ data_dict['id'] = context.get('user')
+
id = data_dict.get('id', None)
- provided_user = data_dict.get('user_obj', None)
if id:
user_obj = model.User.get(id)
context['user_obj'] = user_obj
- elif provided_user:
- context['user_obj'] = user_obj = provided_user
else:
raise NotFound
| diff --git a/ckan/tests/logic/action/test_get.py b/ckan/tests/logic/action/test_get.py
--- a/ckan/tests/logic/action/test_get.py
+++ b/ckan/tests/logic/action/test_get.py
@@ -1207,6 +1207,20 @@ def test_user_show_include_datasets_includes_draft_sysadmin(self):
assert dataset_deleted["name"] not in datasets_got
assert got_user["number_created_packages"] == 3
+ def test_user_show_for_myself_without_passing_id(self):
+
+ user = factories.User()
+
+ got_user = helpers.call_action(
+ "user_show", context={"user": user["name"]}
+ )
+
+ assert got_user["name"] == user["name"]
+ assert got_user["email"] == user["email"]
+ assert got_user["apikey"] == user["apikey"]
+ assert "password" not in got_user
+ assert "reset_key" not in got_user
+
@pytest.mark.usefixtures("clean_db", "clean_index", "with_request_context")
class TestCurrentPackageList(object):
| There is no way to determine the user ID when connecting through the API
**CKAN version**
2.8
**Describe the bug**
It is not possible to determine a users ID when connecting through the API. In my opinion, this should be the default behavior of `user_show`, but the documentation states that *either the `id` or the `user_obj` parameter must be given*. I think it would be user-convenient to change this default behavior.
**Steps to reproduce**
Connect via API using an API key and call `user_show` without arguments.
**Expected behavior**
The information about the currently logged-in user is shown.
**Actual behavior**
```json
{"help": "https://dmoain.tld/api/3/action/help_show?name=user_show", "success": false, "error": {"message": "Not found", "__type": "Not Found Error"}}
```
| Note: A workaround is to iterate over `user_list` and check whether the API key matches the `apikey` value (which is only set if authorized).
Instead of changing `user_show` let's add a new action `id_for_current_user_show` or similar that returns just the user id when someone is logged in. IIUC this should be harder to abuse with XSS attacks because it requires another round-trip to get actual user details (security experts please weigh in if you know better)
@shubham-mahajan @wardi just pinging to see if PR #5504 is still WIP.
@jqnatividad From my end PR is done, let's wait @wardi to review.
Any updates on this one? The workaround I mentioned before does not anymore work with API tokens. A new workaround is to check whether "email" is set for a user in the user list.
@paulmueller It is agreed in (https://github.com/ckan/ckan/pull/5504#issuecomment-760974628) that we will not be using a separate method but will create a flag in the request for that.
I will create a PR soon for that | 2021-08-24T07:44:22 |
ckan/ckan | 6,339 | ckan__ckan-6339 | [
"5727"
] | 3dbda6193130f491daa919bb5e380767c4d576a9 | diff --git a/ckanext/datapusher/plugin.py b/ckanext/datapusher/plugin.py
--- a/ckanext/datapusher/plugin.py
+++ b/ckanext/datapusher/plugin.py
@@ -72,6 +72,10 @@ def after_resource_create(
self._submit_to_datapusher(resource_dict)
+ def after_update(self, context, resource_dict):
+
+ self._submit_to_datapusher(resource_dict)
+
def _submit_to_datapusher(self, resource_dict: dict[str, Any]):
context = cast(Context, {
u'model': model,
| Datapusher being triggered before file is uploaded (update)
**CKAN version**
v2.9, 2.8, 2.7
**Describe the bug**
The Datapusher is triggered before the file is uploaded and causing the file to use the old URL and the new data is not uploaded to filestore until clicked manually
**Steps to reproduce**
1. Create a resource
2. Check the preview
3. Update the resource with a new file.
4. The preview is same.
5. Click `Upload to Datapusher`. The resource will be updated
**Expected behavior**
The data from the new file should be updated to the datastore
**Additional details**
We can fix this by removing the `notify` method and using the `after_update` hook of the resource.
`notify` is triggered as soon the URL is changed and updated in DB and not committed to SOLR yet and the `resource_show` method use the SOLR to fetch the data so the datapusher is fetching from the old URL instead of new URL or a new resource
| would this also affect xloader?
@duttonw I am not sure
@shubham-mahajan , I am interested to work on this issue. I have tried to reproduce this issue on CKAN 2.9.2 , but this issue is not reproduced in my environment. It is working as per expected behavior.
@Gauravp-NEC Create a resource and upload a CSV, check the preview.
Now upload a completely different CSV and check the resource preview, it will not be updated until you manually click the `Upload the Datapusher`
@shubham-mahajan , I tried the same, but again this issue is not reproduced in my environment. | 2021-08-24T09:55:38 |
|
ckan/ckan | 6,345 | ckan__ckan-6345 | [
"6340"
] | c5c529d10ebe63d8573515483fdd46e0839477f0 | diff --git a/ckan/config/middleware/flask_app.py b/ckan/config/middleware/flask_app.py
--- a/ckan/config/middleware/flask_app.py
+++ b/ckan/config/middleware/flask_app.py
@@ -395,8 +395,9 @@ def ckan_after_request(response):
r_time = time.time() - g.__timer
url = request.environ['PATH_INFO']
+ status_code = response.status_code
- log.info(' %s render time %.3f seconds' % (url, r_time))
+ log.info(' %s %s render time %.3f seconds' % (status_code, url, r_time))
return response
@@ -525,8 +526,9 @@ def _register_error_handler(app):
u'''Register error handler'''
def error_handler(e):
- log.error(e, exc_info=sys.exc_info)
+ debug = asbool(config.get('debug', config.get('DEBUG', False)))
if isinstance(e, HTTPException):
+ log.error(e, exc_info=sys.exc_info) if debug else log.error(e)
extra_vars = {
u'code': e.code,
u'content': e.description,
@@ -535,6 +537,7 @@ def error_handler(e):
return base.render(
u'error_document_template.html', extra_vars), e.code
+ log.error(e, exc_info=sys.exc_info)
extra_vars = {u'code': [500], u'content': u'Internal server error'}
return base.render(u'error_document_template.html', extra_vars), 500
| Not authorized and Not found generates errors in logs even though the errors are shown correctly in the UI
**CKAN version**
2.8, 2.9, master
**Describe the bug**
When some flask route produces NotFound or NotAuthorized, error is generated in the logs even though the UI handles it correctly.
For example 404:

```
2021-08-24 11:41:47,135 ERROR [ckan.config.middleware.flask_app] 404 Not Found: The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.
Traceback (most recent call last):
File "/usr/lib/ckan/default/lib/python3.6/site-packages/flask/app.py", line 1949, in full_dispatch_request
rv = self.dispatch_request()
File "/usr/lib/ckan/default/lib/python3.6/site-packages/flask_debugtoolbar/__init__.py", line 125, in dispatch_request return view_func(**req.view_args)
File "/usr/lib/ckan/default/lib/python3.6/site-packages/flask_multistatic.py", line 96, in send_static_file
raise NotFound()
werkzeug.exceptions.NotFound: 404 Not Found: The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.
2021-08-24 11:41:47,153 INFO [ckan.config.middleware.flask_app] /foobar render time 0.024 seconds
```
403 (public user details are turned of to produce this):

```
2021-08-24 11:43:13,907 ERROR [ckan.config.middleware.flask_app] 403 Forbidden: Not authorized to see this page
Traceback (most recent call last):
File "/vagrant/ckan/config/middleware/../../views/user.py", line 58, in _extra_template_variables
user_dict = logic.get_action(u'user_show')(context, data_dict)
File "/vagrant/ckan/logic/__init__.py", line 499, in wrapped
result = _action(context, data_dict, **kw)
File "/vagrant/ckan/logic/action/get.py", line 1399, in user_show
_check_access('user_show', context, data_dict)
File "/vagrant/ckan/logic/__init__.py", line 317, in check_access
raise NotAuthorized(msg)
ckan.logic.NotAuthorized
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/lib/ckan/default/lib/python3.6/site-packages/flask/app.py", line 1949, in full_dispatch_request
rv = self.dispatch_request()
File "/usr/lib/ckan/default/lib/python3.6/site-packages/flask_debugtoolbar/__init__.py", line 125, in dispatch_request
return view_func(**req.view_args)
File "/vagrant/ckan/config/middleware/../../views/user.py", line 148, in read
extra_vars = _extra_template_variables(context, data_dict)
File "/vagrant/ckan/config/middleware/../../views/user.py", line 62, in _extra_template_variables
base.abort(403, _(u'Not authorized to see this page'))
File "/vagrant/ckan/lib/base.py", line 47, in abort
flask_abort(status_code, detail)
File "/usr/lib/ckan/default/lib/python3.6/site-packages/werkzeug/exceptions.py", line 822, in abort
return _aborter(status, *args, **kwargs)
File "/usr/lib/ckan/default/lib/python3.6/site-packages/werkzeug/exceptions.py", line 807, in __call__
raise self.mapping[code](*args, **kwargs)
werkzeug.exceptions.Forbidden: 403 Forbidden: Not authorized to see this page
2021-08-24 11:43:13,930 INFO [ckan.config.middleware.flask_app] /user/foobar render time 0.039 seconds
```
This would not be a problem as such but when you use error logging middlewares like sentry or just sending errors by email, you will be swamped by errors which actually should work correctly.
**Steps to reproduce**
Open nonexisting page, check logs for stacktrace.
**Expected behavior**
Logs should not have have stacktrace in them
| For both errors, capture and hide the exception, but add the status code to the `[ckan.config.middleware.flask_app] /user/foobar render time 0.039 seconds` line (check if that's added on API requests as well) | 2021-08-27T07:35:07 |
|
ckan/ckan | 6,356 | ckan__ckan-6356 | [
"6350",
"6350"
] | dfd17212901ac1f8c1cc5b62d1f6970f7849e17b | diff --git a/ckan/lib/helpers.py b/ckan/lib/helpers.py
--- a/ckan/lib/helpers.py
+++ b/ckan/lib/helpers.py
@@ -8,6 +8,7 @@
import email.utils
import datetime
import logging
+import numbers
import re
import os
import pytz
@@ -2291,7 +2292,11 @@ def format_resource_items(items):
reg_ex_int = r'^-?\d{1,}$'
reg_ex_float = r'^-?\d{1,}\.\d{1,}$'
for key, value in items:
- if not value or key in blacklist:
+ if (key in blacklist
+ or (not isinstance(value, numbers.Number) and not value)):
+ # Ignore blocked keys and values that evaluate to
+ # `bool(value) == False` (e.g. `""`, `[]` or `{}`),
+ # with the exception of numbers such as `False`, `0`,`0.0`.
continue
# size is treated specially as we want to show in MiB etc
if key == 'size':
@@ -2310,8 +2315,9 @@ def format_resource_items(items):
value = formatters.localised_number(float(value))
elif re.search(reg_ex_int, value):
value = formatters.localised_number(int(value))
- elif ((isinstance(value, int) or isinstance(value, float))
- and value not in (True, False)):
+ elif isinstance(value, bool):
+ value = str(value)
+ elif isinstance(value, numbers.Number):
value = formatters.localised_number(value)
key = key.replace('_', ' ')
output.append((key, value))
| diff --git a/ckan/tests/lib/test_helpers.py b/ckan/tests/lib/test_helpers.py
--- a/ckan/tests/lib/test_helpers.py
+++ b/ckan/tests/lib/test_helpers.py
@@ -8,6 +8,7 @@
import pytz
import tzlocal
from babel import Locale
+import flask_babel
import pytest
@@ -914,6 +915,25 @@ def test_date_str_to_datetime_invalid(string):
h.date_str_to_datetime(string)
[email protected]("dict_in,dict_out", [
+ ({"number_bool": True}, {"number bool": "True"}),
+ ({"number_bool": False}, {"number bool": "False"}),
+ ({"number_int": 0}, {"number int": "0"}),
+ ({"number_int": 42}, {"number int": "42"}),
+ ({"number_float": 0.0}, {"number float": "0"}),
+ ({"number_float": 0.1}, {"number float": "0.1"}),
+ ({"number_float": "0.10"}, {"number float": "0.1"}),
+ ({"string_basic": "peter"}, {"string basic": "peter"}),
+ ({"string_empty": ""}, {}), # empty strings are ignored
+ ({"name": "hans"}, {}), # blocked string
+])
+def test_format_resource_items_data_types(dict_in, dict_out, monkeypatch):
+ # set locale to en (formatting of decimals)
+ monkeypatch.setattr(flask_babel, "get_locale", lambda: "en")
+ items_out = h.format_resource_items(dict_in.items())
+ assert items_out == list(dict_out.items())
+
+
def test_gravatar():
email = "[email protected]"
expected = '<img src="//gravatar.com/avatar/7856421db6a63efa5b248909c472fbd2?s=200&d=mm"'
| `ckan.lib.helpers.format_resource_items` discards `False` boolean values
**CKAN version**
2.9
**Describe the bug**
I have boolean resource metadata keys defined via schemas in my DCOR instance. These are not written to the resources HTML page, because [format_resource_items](https://github.com/ckan/ckan/blob/c5c529d10ebe63d8573515483fdd46e0839477f0/ckan/lib/helpers.py#L2294) discards `False` boolean values.
**Steps to reproduce**
Set a value of a resource key to `False`.
**Expected behavior**
Value should be displayed on HTML resource page.
**Additional details**
This can be fixed by changing the line linked above
```python
if not value or key in blacklist:
continue
```
to
```python
if not isinstance(value, bool) and (not value or key in blacklist):
continue
```
**I can write a PR including a test for `format_resource_items` if you give me green light.**
`ckan.lib.helpers.format_resource_items` discards `False` boolean values
**CKAN version**
2.9
**Describe the bug**
I have boolean resource metadata keys defined via schemas in my DCOR instance. These are not written to the resources HTML page, because [format_resource_items](https://github.com/ckan/ckan/blob/c5c529d10ebe63d8573515483fdd46e0839477f0/ckan/lib/helpers.py#L2294) discards `False` boolean values.
**Steps to reproduce**
Set a value of a resource key to `False`.
**Expected behavior**
Value should be displayed on HTML resource page.
**Additional details**
This can be fixed by changing the line linked above
```python
if not value or key in blacklist:
continue
```
to
```python
if not isinstance(value, bool) and (not value or key in blacklist):
continue
```
**I can write a PR including a test for `format_resource_items` if you give me green light.**
| I think the helper expects strings, even though there are some handling for special cases like dates and numbers. But the actual type given to the function is still a string.
I thought `items` (what `format_resource_items` accepts) would be something like `dict.items()`, i.e. a list of `(key, value)` pairs.
And no, (while the keys are strings) the values are definitely not always strings. They can be floats, integers, and boolean. Otherwise it would not make sense to handle those cases in that function.
https://github.com/ckan/ckan/blob/c5c529d10ebe63d8573515483fdd46e0839477f0/ckan/lib/helpers.py#L2293-L2317
@paulmueller it makes sense to handle boolean as special case as well. A PR would be great!
I think the helper expects strings, even though there are some handling for special cases like dates and numbers. But the actual type given to the function is still a string.
I thought `items` (what `format_resource_items` accepts) would be something like `dict.items()`, i.e. a list of `(key, value)` pairs.
And no, (while the keys are strings) the values are definitely not always strings. They can be floats, integers, and boolean. Otherwise it would not make sense to handle those cases in that function.
https://github.com/ckan/ckan/blob/c5c529d10ebe63d8573515483fdd46e0839477f0/ckan/lib/helpers.py#L2293-L2317
@paulmueller it makes sense to handle boolean as special case as well. A PR would be great! | 2021-09-01T21:50:57 |
ckan/ckan | 6,357 | ckan__ckan-6357 | [
"6340"
] | 884a293366a0722ffad378980dcfa0d862d608b3 | diff --git a/ckan/config/middleware/flask_app.py b/ckan/config/middleware/flask_app.py
--- a/ckan/config/middleware/flask_app.py
+++ b/ckan/config/middleware/flask_app.py
@@ -528,7 +528,7 @@ def _register_error_handler(app):
def error_handler(e):
debug = asbool(config.get('debug', config.get('DEBUG', False)))
if isinstance(e, HTTPException):
- log.error(e, exc_info=sys.exc_info) if debug else log.error(e)
+ log.debug(e, exc_info=sys.exc_info) if debug else log.info(e)
extra_vars = {
u'code': e.code,
u'content': e.description,
| Not authorized and Not found generates errors in logs even though the errors are shown correctly in the UI
**CKAN version**
2.8, 2.9, master
**Describe the bug**
When some flask route produces NotFound or NotAuthorized, error is generated in the logs even though the UI handles it correctly.
For example 404:

```
2021-08-24 11:41:47,135 ERROR [ckan.config.middleware.flask_app] 404 Not Found: The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.
Traceback (most recent call last):
File "/usr/lib/ckan/default/lib/python3.6/site-packages/flask/app.py", line 1949, in full_dispatch_request
rv = self.dispatch_request()
File "/usr/lib/ckan/default/lib/python3.6/site-packages/flask_debugtoolbar/__init__.py", line 125, in dispatch_request return view_func(**req.view_args)
File "/usr/lib/ckan/default/lib/python3.6/site-packages/flask_multistatic.py", line 96, in send_static_file
raise NotFound()
werkzeug.exceptions.NotFound: 404 Not Found: The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.
2021-08-24 11:41:47,153 INFO [ckan.config.middleware.flask_app] /foobar render time 0.024 seconds
```
403 (public user details are turned of to produce this):

```
2021-08-24 11:43:13,907 ERROR [ckan.config.middleware.flask_app] 403 Forbidden: Not authorized to see this page
Traceback (most recent call last):
File "/vagrant/ckan/config/middleware/../../views/user.py", line 58, in _extra_template_variables
user_dict = logic.get_action(u'user_show')(context, data_dict)
File "/vagrant/ckan/logic/__init__.py", line 499, in wrapped
result = _action(context, data_dict, **kw)
File "/vagrant/ckan/logic/action/get.py", line 1399, in user_show
_check_access('user_show', context, data_dict)
File "/vagrant/ckan/logic/__init__.py", line 317, in check_access
raise NotAuthorized(msg)
ckan.logic.NotAuthorized
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/lib/ckan/default/lib/python3.6/site-packages/flask/app.py", line 1949, in full_dispatch_request
rv = self.dispatch_request()
File "/usr/lib/ckan/default/lib/python3.6/site-packages/flask_debugtoolbar/__init__.py", line 125, in dispatch_request
return view_func(**req.view_args)
File "/vagrant/ckan/config/middleware/../../views/user.py", line 148, in read
extra_vars = _extra_template_variables(context, data_dict)
File "/vagrant/ckan/config/middleware/../../views/user.py", line 62, in _extra_template_variables
base.abort(403, _(u'Not authorized to see this page'))
File "/vagrant/ckan/lib/base.py", line 47, in abort
flask_abort(status_code, detail)
File "/usr/lib/ckan/default/lib/python3.6/site-packages/werkzeug/exceptions.py", line 822, in abort
return _aborter(status, *args, **kwargs)
File "/usr/lib/ckan/default/lib/python3.6/site-packages/werkzeug/exceptions.py", line 807, in __call__
raise self.mapping[code](*args, **kwargs)
werkzeug.exceptions.Forbidden: 403 Forbidden: Not authorized to see this page
2021-08-24 11:43:13,930 INFO [ckan.config.middleware.flask_app] /user/foobar render time 0.039 seconds
```
This would not be a problem as such but when you use error logging middlewares like sentry or just sending errors by email, you will be swamped by errors which actually should work correctly.
**Steps to reproduce**
Open nonexisting page, check logs for stacktrace.
**Expected behavior**
Logs should not have have stacktrace in them
| For both errors, capture and hide the exception, but add the status code to the `[ckan.config.middleware.flask_app] /user/foobar render time 0.039 seconds` line (check if that's added on API requests as well)
@amercader @Zharktas I have implemented some changes. Handling using the debug flag and logging separation for HTTP Exceptions. | 2021-09-02T07:23:06 |
|
ckan/ckan | 6,400 | ckan__ckan-6400 | [
"6383"
] | da5dbd26da3f6d60d5ba4189b1f28619e6c2b835 | diff --git a/ckan/model/resource_view.py b/ckan/model/resource_view.py
--- a/ckan/model/resource_view.py
+++ b/ckan/model/resource_view.py
@@ -30,7 +30,6 @@ def get(cls, reference):
return None
view = meta.Session.query(cls).get(reference)
-
return view
@classmethod
diff --git a/ckan/views/resource.py b/ckan/views/resource.py
--- a/ckan/views/resource.py
+++ b/ckan/views/resource.py
@@ -819,72 +819,6 @@ def _parse_recline_state(params):
return recline_state
-def embedded_dataviewer(package_type, id, resource_id, width=500, height=500):
- """
- Embedded page for a read-only resource dataview. Allows
- for width and height to be specified as part of the
- querystring (as well as accepting them via routes).
- """
- context = {
- u'model': model,
- u'session': model.Session,
- u'user': g.user,
- u'auth_user_obj': g.userobj
- }
-
- try:
- resource = get_action(u'resource_show')(context, {u'id': resource_id})
- package = get_action(u'package_show')(context, {u'id': id})
- resource_json = h.json.dumps(resource)
-
- # double check that the resource belongs to the specified package
- if not resource[u'id'] in [r[u'id'] for r in package[u'resources']]:
- raise NotFound
- dataset_type = package[u'type'] or package_type
-
- except (NotFound, NotAuthorized):
- return base.abort(404, _(u'Resource not found'))
-
- # Construct the recline state
- state_version = int(request.args.get(u'state_version', u'1'))
- recline_state = _parse_recline_state(request.args)
- if recline_state is None:
- return base.abort(
- 400, (
- u'"state" parameter must be a valid recline '
- u'state (version %d)' % state_version
- )
- )
-
- recline_state = h.json.dumps(recline_state)
-
- width = max(int(request.args.get(u'width', width)), 100)
- height = max(int(request.args.get(u'height', height)), 100)
- embedded = True
-
- # TODO: remove
- g.resource = resource
- g.package = package
- g.resource_json = resource_json
- g.recline_state = recline_state
- g.width = width
- g.height = height
- g.embedded = embedded
-
- return base.render(
- u'package/resource_embedded_dataviewer.html', {
- u'dataset_type': dataset_type,
- u'resource': resource,
- u'package': package,
- u'resource_json': resource_json,
- u'width': width,
- u'height': height,
- u'embedded': embedded,
- u'recline_state': recline_state
- }
- )
-
-
def register_dataset_plugin_rules(blueprint):
blueprint.add_url_rule(u'/new', view_func=CreateView.as_view(str(u'new')))
blueprint.add_url_rule(
@@ -909,16 +843,6 @@ def register_dataset_plugin_rules(blueprint):
blueprint.add_url_rule(
u'/<resource_id>/edit_view/<view_id>', view_func=_edit_view
)
- blueprint.add_url_rule(
- u'/<resource_id>/embed', view_func=embedded_dataviewer)
- blueprint.add_url_rule(
- u'/<resource_id>/viewer',
- view_func=embedded_dataviewer,
- defaults={
- u'width': u"960",
- u'height': u"800"
- }
- )
register_dataset_plugin_rules(resource)
| Missing resource_embedded_dataviewer.html or misnamed template file
**CKAN version**
2.9.3
**Describe the bug**
Missing or incorrectly named template file
**Steps to reproduce**
Steps to reproduce the behavior:
Create a dataset with a resource and then go to the resource url and append `/embed` at the end, it causes an internal server error - `TemplateNotFound: package/resource_embedded_dataviewer.html`
**Expected behavior**
The resource to be correctly returned from the request.
**Additional details**
This is the line with the template filename -
https://github.com/ckan/ckan/blob/master/ckan/views/resource.py#L875
| 2021-09-15T13:09:13 |
||
ckan/ckan | 6,433 | ckan__ckan-6433 | [
"6432"
] | d20703f261c2f42fe034bbac7370943784b74e07 | diff --git a/ckan/lib/helpers.py b/ckan/lib/helpers.py
--- a/ckan/lib/helpers.py
+++ b/ckan/lib/helpers.py
@@ -1951,7 +1951,7 @@ def _create_url_with_params(
params=None, controller=None, action=None, extras=None
):
"""internal function for building urls with parameters."""
- if extras is None:
+ if not extras:
if not controller and not action:
# it's an url for the current page. Let's keep all interlal params,
# like <package_type>
| jinja2.exceptions.UndefinedError: 'extras' is undefined
**CKAN version**
master
**Describe the bug**
When trying to access `/dataset` i m getting this error: `jinja2.exceptions.UndefinedError: 'extras' is undefined`

| 2021-09-27T14:50:56 |
||
ckan/ckan | 6,466 | ckan__ckan-6466 | [
"5690"
] | 839948df408113d0d88a7e052f1489116743d7fe | diff --git a/ckan/migration/versions/101_d111f446733b_add_last_active_column_in_user_table.py b/ckan/migration/versions/101_d111f446733b_add_last_active_column_in_user_table.py
new file mode 100644
--- /dev/null
+++ b/ckan/migration/versions/101_d111f446733b_add_last_active_column_in_user_table.py
@@ -0,0 +1,26 @@
+# encoding: utf-8
+
+"""Add last_active column in user table
+
+Revision ID: d111f446733b
+Revises: ccd38ad5fced
+Create Date: 2021-09-22 00:44:40.777435
+
+"""
+from alembic import op
+import sqlalchemy as sa
+
+
+# revision identifiers, used by Alembic.
+revision = 'd111f446733b'
+down_revision = 'ccd38ad5fced'
+branch_labels = None
+depends_on = None
+
+
+def upgrade():
+ op.add_column('user', sa.Column('last_active', sa.TIMESTAMP))
+
+
+def downgrade():
+ op.remove_column('user', sa.Column('last_active'))
diff --git a/ckan/model/user.py b/ckan/model/user.py
--- a/ckan/model/user.py
+++ b/ckan/model/user.py
@@ -18,6 +18,14 @@
from ckan.model import core
from ckan.model import types as _types
from ckan.model import domain_object
+from ckan.common import config, asbool, asint, session
+
+
+def last_active_check():
+ last_active = asint(config.get('ckan.user.last_active_interval', 600))
+ calc_time = datetime.datetime.utcnow() - datetime.timedelta(seconds=last_active)
+
+ return calc_time
def set_api_key():
@@ -37,6 +45,7 @@ def set_api_key():
Column('created', types.DateTime, default=datetime.datetime.now),
Column('reset_key', types.UnicodeText),
Column('about', types.UnicodeText),
+ Column('last_active', types.TIMESTAMP),
Column('activity_streams_email_notifications', types.Boolean,
default=False),
Column('sysadmin', types.Boolean, default=False),
@@ -293,6 +302,16 @@ def user_ids_for_name_or_id(cls, user_list=[]):
cls.id.in_(user_list)))
return [user.id for user in query.all()]
+ def set_user_last_active(self):
+ if self.last_active:
+ session["last_active"] = self.last_active
+
+ if session["last_active"] < last_active_check():
+ self.last_active = datetime.datetime.utcnow()
+ meta.Session.commit()
+ else:
+ self.last_active = datetime.datetime.utcnow()
+ meta.Session.commit()
meta.mapper(User, user_table,
properties={'password': synonym('_password', map_column=True)},
diff --git a/ckan/views/__init__.py b/ckan/views/__init__.py
--- a/ckan/views/__init__.py
+++ b/ckan/views/__init__.py
@@ -141,6 +141,9 @@ def identify_user():
# general settings
if g.user:
+ if g.userobj:
+ userobj = g.userobj
+ userobj.set_user_last_active()
g.author = g.user
else:
g.author = g.remote_addr
| diff --git a/ckan/tests/model/test_user.py b/ckan/tests/model/test_user.py
--- a/ckan/tests/model/test_user.py
+++ b/ckan/tests/model/test_user.py
@@ -8,7 +8,6 @@
from passlib.hash import pbkdf2_sha512
-
import ckan.model as model
import ckan.tests.factories as factories
@@ -163,6 +162,7 @@ def test_basic(self):
assert len(user.apikey) == 36
assert user.fullname == data["fullname"]
assert user.email == data["email"]
+ assert user.last_active is None
def test_get(self):
factories.User(fullname="Brian", name="brian")
@@ -228,3 +228,30 @@ def test_number_of_administered_packages(self):
user1.number_created_packages() == 1
user2.number_created_packages() == 0
+
+ def test_user_last_active(self, app):
+ import datetime
+ from ckan.lib.helpers import url_for
+ from freezegun import freeze_time
+
+ frozen_time = datetime.datetime.utcnow()
+ data = factories.User()
+ dataset = factories.Dataset()
+ env = {"REMOTE_USER": str(data["name"])}
+
+ with freeze_time(frozen_time):
+ user = model.User.get(data["id"])
+ assert user.last_active is None
+ app.get(url_for("dataset.search"), extra_environ=env)
+ assert isinstance(user.last_active, datetime.datetime)
+ assert user.last_active == datetime.datetime.utcnow()
+
+ with freeze_time(frozen_time + datetime.timedelta(seconds=540)):
+ user = model.User.get(data["id"])
+ app.get(url_for("user.read", id=user.id), extra_environ=env)
+ assert user.last_active != datetime.datetime.utcnow()
+
+ with freeze_time(frozen_time + datetime.timedelta(seconds=660)):
+ user = model.User.get(data["id"])
+ app.get(url_for("dataset.read", id=dataset["id"]), extra_environ=env)
+ assert user.last_active == datetime.datetime.utcnow()
| There is no way to find out when a user last logged in
**CKAN version**
2.9.1
**Describe the bug**
The `user` table stores the `created` timestamp, but not last login. This information is needed to:
- purge idle users (#5658)
- enforce password aging policies
- help track utilization
- help implement brute force lockout? (perhaps, by adding another column - `last_login_attempt`?)
**Steps to reproduce**
Register a user.
**Expected behavior**
A `last_login` column is added to the `user` table, similar to the `last_accessed` column in the new `api_token` table.
| This is a valuable suggestion.
I implemented this in the past but with a `last_active` field, which is more granular, hooking into [`identify_user()`](https://github.com/ckan/ckan/blob/04cc84540ffd7b00e70a04de6f84f1b0721ca838/ckan/views/__init__.py#L122). If we wanted actual logins we could hook it in [`logged_in`](https://github.com/ckan/ckan/blob/04cc84540ffd7b00e70a04de6f84f1b0721ca838/ckan/views/user.py#L468) but that would not take API access into account.
`last_active` is even better! Will pull together a PR.
@amercader , I am interested to work on this issue. As you said that:
> If we wanted actual logins we could hook it in logged_in but that would not take API access into account.
What would be the correct approach to develop this feature?
| 2021-10-12T13:23:27 |
ckan/ckan | 6,532 | ckan__ckan-6532 | [
"6531"
] | ecd9ac6bc6cfb5bb4fcbec82c431f4564ef649ed | diff --git a/ckan/views/api.py b/ckan/views/api.py
--- a/ckan/views/api.py
+++ b/ckan/views/api.py
@@ -3,6 +3,7 @@
import os
import logging
import html
+import io
from flask import Blueprint, make_response
@@ -449,7 +450,7 @@ def i18n_js_translations(lang, ver=API_REST_DEFAULT_VERSION):
u'base', u'i18n', u'{0}.js'.format(lang)))
if not os.path.exists(source):
return u'{}'
- translations = json.load(open(source, u'r', encoding='utf-8'))
+ translations = json.load(io.open(source, u'r', encoding='utf-8'))
return _finish_ok(translations)
| CKAN 2.9.4 cannot load JS translations when using Python 2.7
This code is not Python 2.7 compatible:
https://github.com/ckan/ckan/blob/6731c5a821a6a5f4bdaa20f4e793e0b6ba44f823/ckan/views/api.py#L482
In Python 2, `encoding` is not a valid argument for the `open` function, but it is for the `json.load`.
Here is the commit which introduced the regression: https://github.com/ckan/ckan/commit/a280cf123748eb548a64242033aa41c0c67ee256
```python-traceback
2021-11-11 15:42:28,678 ERROR [ckan.config.middleware.flask_app] 'encoding' is an invalid keyword argument for this function
Traceback (most recent call last):
File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/flask/app.py", line 1949, in full_dispatch_request
rv = self.dispatch_request()
File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/flask/app.py", line 1935, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/usr/lib/ckan/venv/src/ckan/ckan/views/api.py", line 482, in i18n_js_translations
translations = json.load(open(source, u'r', encoding=u'utf-8'))
TypeError: 'encoding' is an invalid keyword argument for this function
```
It seems to have been fixed partially already in another file: https://github.com/ckan/ckan/commit/b2b92a478f9a96c908e214d33d7d8141c73343c7
Related issue: #6051
| 2021-11-11T16:17:00 |
||
ckan/ckan | 6,556 | ckan__ckan-6556 | [
"6555"
] | ace6850ddabb1bc533c6942cc434e806c62236e5 | diff --git a/ckan/config/middleware/common_middleware.py b/ckan/config/middleware/common_middleware.py
--- a/ckan/config/middleware/common_middleware.py
+++ b/ckan/config/middleware/common_middleware.py
@@ -11,6 +11,24 @@
from ckan.common import config
+class RootPathMiddleware(object):
+ '''
+ Prevents the SCRIPT_NAME server variable conflicting with the ckan.root_url
+ config. The routes package uses the SCRIPT_NAME variable and appends to the
+ path and ckan addes the root url causing a duplication of the root path.
+ This is a middleware to ensure that even redirects use this logic.
+ '''
+ def __init__(self, app, config):
+ self.app = app
+
+ def __call__(self, environ, start_response):
+ # Prevents the variable interfering with the root_path logic
+ if 'SCRIPT_NAME' in environ:
+ environ['SCRIPT_NAME'] = ''
+
+ return self.app(environ, start_response)
+
+
class TrackingMiddleware(object):
def __init__(self, app, config):
diff --git a/ckan/config/middleware/flask_app.py b/ckan/config/middleware/flask_app.py
--- a/ckan/config/middleware/flask_app.py
+++ b/ckan/config/middleware/flask_app.py
@@ -32,7 +32,8 @@
from ckan.lib import i18n
from ckan.common import config, g, request, ungettext
from ckan.config.middleware.common_middleware import (TrackingMiddleware,
- HostHeaderMiddleware)
+ HostHeaderMiddleware,
+ RootPathMiddleware)
import ckan.lib.app_globals as app_globals
import ckan.lib.plugins as lib_plugins
from ckan.lib.webassets_tools import get_webassets_path
@@ -205,6 +206,7 @@ def save_session(self, app, session, response):
session_opts['session.data_dir'] = '{data_dir}/sessions'.format(
data_dir=cache_dir)
+ app.wsgi_app = RootPathMiddleware(app.wsgi_app, session_opts)
app.wsgi_app = SessionMiddleware(app.wsgi_app, session_opts)
app.session_interface = BeakerSessionInterface()
| Non-root installs broken with python3
**CKAN version**
2.9.3
**Describe the bug**
Root path is added twice to any generated URLs on the site. For example `/data/data/dataset`
**Steps to reproduce**
Install CKAN 2.9.3 into root_path `/data`, see `data-site-root` body tag attribute when loading `/data/dataset`
**Expected behavior**
The URLs are generated correctly
**Additional details**
This is because the Python 3 app stack does not contain any step to remove the `SCRIPT_NAME` environment variable set by the WSGI host. For Pylons this is done in RootPathMiddleware and in Python 2 installs `flask_app` does it in `can_handle_request`.
The issue can be fixed by adding a RootPathMiddleware inclusion step to `make_flask_stack`. I'll make a PR later today.
| 2021-11-24T10:58:13 |
||
ckan/ckan | 6,578 | ckan__ckan-6578 | [
"6521"
] | 7ce679cf1fe9ac7362709eb68991d4202d458553 | diff --git a/ckan/lib/uploader.py b/ckan/lib/uploader.py
--- a/ckan/lib/uploader.py
+++ b/ckan/lib/uploader.py
@@ -122,12 +122,17 @@ def __init__(self, object_type, old_filename=None):
return
self.storage_path = os.path.join(path, 'storage',
'uploads', object_type)
- try:
- os.makedirs(self.storage_path)
- except OSError as e:
- # errno 17 is file already exists
- if e.errno != 17:
- raise
+ # check if the storage directory is already created by
+ # the user or third-party
+ if os.path.isdir(self.storage_path):
+ pass
+ else:
+ try:
+ os.makedirs(self.storage_path)
+ except OSError as e:
+ # errno 17 is file already exists
+ if e.errno != 17:
+ raise
self.object_type = object_type
self.old_filename = old_filename
if old_filename:
| Upload.__init__ relies too much on makedirs
**CKAN version**
2.8, 2.9
**Describe the bug**
`ckan.lib.uploader:Upload.__init__` relies on `os.makedirs` to create the storage directory. However, this is inadequate if, for example, the storage directory has been created by another process, with sufficient permissions for CKAN to use it, yet with insufficient permissions in the parent directory for CKAN to have created it.
It also adds extra OS calls on every creation of an Upload object.
| This code is used to create subdirectories for each uploader type, eg `groups` for group and org images, `admin` for the
admin UI logos, and others that extensions might want to create, which is really useful.
https://github.com/ckan/ckan/blob/master/ckan/lib/uploader.py#L123-L130
Perhaps it's not the most elegant one, what do you propose to improve it? Maybe checking if the directories exist before attempting `os.makedirs`?
> Maybe checking if the directories exist before attempting os.makedirs?
It would be a good check to add, yes.
Consider a CKAN system created by a configuration management tool like Chef. It might well have the storage directory created, with appropriate permissions for CKAN to use it, but without write access to the parent directory. | 2021-12-07T13:11:45 |
|
ckan/ckan | 6,598 | ckan__ckan-6598 | [
"6546"
] | 6150641b174a7a00d0e1c09a5894b89b2a7b2480 | diff --git a/ckan/config/declaration/load.py b/ckan/config/declaration/load.py
--- a/ckan/config/declaration/load.py
+++ b/ckan/config/declaration/load.py
@@ -83,9 +83,7 @@ def load_dict(declaration: "Declaration", definition: DeclarationDict):
if version == 1:
data, errors = validate(definition, config_declaration_v1())
- if any(
- options for item in errors["groups"] for options in item["options"]
- ):
+ if errors:
raise ValidationError(errors)
for group in data["groups"]:
if group["annotation"]:
diff --git a/ckan/lib/navl/dictization_functions.py b/ckan/lib/navl/dictization_functions.py
--- a/ckan/lib/navl/dictization_functions.py
+++ b/ckan/lib/navl/dictization_functions.py
@@ -247,16 +247,14 @@ def convert(converter, key, converted_data, errors, context):
def _remove_blank_keys(schema):
- schema_copy = copy.copy(schema)
-
- for key, value in schema.items():
+ for key, value in list(schema.items()):
if isinstance(value[0], dict):
for item in value:
_remove_blank_keys(item)
if not any(value):
- schema_copy.pop(key)
+ schema.pop(key)
- return schema_copy
+ return schema
def validate(data, schema, context=None):
@@ -297,7 +295,7 @@ def validate(data, schema, context=None):
if isinstance(value[0], dict):
dicts_to_process.extend(value)
- errors_unflattened = _remove_blank_keys(errors_unflattened)
+ _remove_blank_keys(errors_unflattened)
return converted_data, errors_unflattened
| validation error on resource subfields (regression) in 2.9
2.9.4, master
**Describe the bug**
ckanext-scheming demonstrates the failure in its tests https://github.com/ckan/ckanext-scheming/actions/runs/1464096741
**Steps to reproduce**
use ckan 2.9.4 or master branch with a ckanext-scheming dataset schema containing resource subfields
**Expected behavior**
not failing
**Additional details**
This is the traceback of the validation failure, see the form failures in https://github.com/ckan/ckanext-scheming/actions/runs/1464096741 as well
```python
ckanext/scheming/tests/test_validation.py:913:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
/usr/lib/python2.7/site-packages/ckanapi/common.py:51: in action
return self._ckan.call_action(name, data_dict=kwargs)
/usr/lib/python2.7/site-packages/ckanapi/localckan.py:72: in call_action
return self._get_action(action)(context, data_dict)
/srv/app/src/ckan/ckan/logic/__init__.py:504: in wrapped
result = _action(context, data_dict, **kw)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
context = {'__auth_audit': [], '__auth_user_obj_checked': True, 'auth_user_obj': <User id=0aa7be9e-0963-44ee-af27-70a04fbf504a n...age_url=None plugin_extras=None>, 'model': <module 'ckan.model' from '/srv/app/src/ckan/ckan/model/__init__.pyc'>, ...}
data_dict = {'name': 'c_sf_1', 'resources': [{'schedule': [{'frequency': '1m', 'impact': 'A'}, {'frequency': '7d', 'impact': 'P'}], 'url': 'http://example.com/data.csv'}], 'type': 'test-subfields'}
def package_create(context, data_dict):
'''Create a new dataset (package).
You must be authorized to create new datasets. If you specify any groups
for the new dataset, you must also be authorized to edit these groups.
Plugins may change the parameters of this function depending on the value
of the ``type`` parameter, see the
:py:class:`~ckan.plugins.interfaces.IDatasetForm` plugin interface.
:param name: the name of the new dataset, must be between 2 and 100
characters long and contain only lowercase alphanumeric characters,
``-`` and ``_``, e.g. ``'warandpeace'``
:type name: string
:param title: the title of the dataset (optional, default: same as
``name``)
:type title: string
:param private: If ``True`` creates a private dataset
:type private: bool
:param author: the name of the dataset's author (optional)
:type author: string
:param author_email: the email address of the dataset's author (optional)
:type author_email: string
:param maintainer: the name of the dataset's maintainer (optional)
:type maintainer: string
:param maintainer_email: the email address of the dataset's maintainer
(optional)
:type maintainer_email: string
:param license_id: the id of the dataset's license, see
:py:func:`~ckan.logic.action.get.license_list` for available values
(optional)
:type license_id: license id string
:param notes: a description of the dataset (optional)
:type notes: string
:param url: a URL for the dataset's source (optional)
:type url: string
:param version: (optional)
:type version: string, no longer than 100 characters
:param state: the current state of the dataset, e.g. ``'active'`` or
``'deleted'``, only active datasets show up in search results and
other lists of datasets, this parameter will be ignored if you are not
authorized to change the state of the dataset (optional, default:
``'active'``)
:type state: string
:param type: the type of the dataset (optional),
:py:class:`~ckan.plugins.interfaces.IDatasetForm` plugins
associate themselves with different dataset types and provide custom
dataset handling behaviour for these types
:type type: string
:param resources: the dataset's resources, see
:py:func:`resource_create` for the format of resource dictionaries
(optional)
:type resources: list of resource dictionaries
:param tags: the dataset's tags, see :py:func:`tag_create` for the format
of tag dictionaries (optional)
:type tags: list of tag dictionaries
:param extras: the dataset's extras (optional), extras are arbitrary
(key: value) metadata items that can be added to datasets, each extra
dictionary should have keys ``'key'`` (a string), ``'value'`` (a
string)
:type extras: list of dataset extra dictionaries
:param relationships_as_object: see :py:func:`package_relationship_create`
for the format of relationship dictionaries (optional)
:type relationships_as_object: list of relationship dictionaries
:param relationships_as_subject: see :py:func:`package_relationship_create`
for the format of relationship dictionaries (optional)
:type relationships_as_subject: list of relationship dictionaries
:param groups: the groups to which the dataset belongs (optional), each
group dictionary should have one or more of the following keys which
identify an existing group:
``'id'`` (the id of the group, string), or ``'name'`` (the name of the
group, string), to see which groups exist
call :py:func:`~ckan.logic.action.get.group_list`
:type groups: list of dictionaries
:param owner_org: the id of the dataset's owning organization, see
:py:func:`~ckan.logic.action.get.organization_list` or
:py:func:`~ckan.logic.action.get.organization_list_for_user` for
available values. This parameter can be made optional if the config
option :ref:`ckan.auth.create_unowned_dataset` is set to ``True``.
:type owner_org: string
:returns: the newly created dataset (unless 'return_id_only' is set to True
in the context, in which case just the dataset id will
be returned)
:rtype: dictionary
'''
model = context['model']
session = context['session']
user = context['user']
if 'type' not in data_dict:
package_plugin = lib_plugins.lookup_package_plugin()
try:
# use first type as default if user didn't provide type
package_type = package_plugin.package_types()[0]
except (AttributeError, IndexError):
package_type = 'dataset'
# in case a 'dataset' plugin was registered w/o fallback
package_plugin = lib_plugins.lookup_package_plugin(package_type)
data_dict['type'] = package_type
else:
package_plugin = lib_plugins.lookup_package_plugin(data_dict['type'])
if 'schema' in context:
schema = context['schema']
else:
schema = package_plugin.create_package_schema()
_check_access('package_create', context, data_dict)
if 'api_version' not in context:
# check_data_dict() is deprecated. If the package_plugin has a
# check_data_dict() we'll call it, if it doesn't have the method we'll
# do nothing.
check_data_dict = getattr(package_plugin, 'check_data_dict', None)
if check_data_dict:
try:
check_data_dict(data_dict, schema)
except TypeError:
# Old plugins do not support passing the schema so we need
# to ensure they still work
package_plugin.check_data_dict(data_dict)
data, errors = lib_plugins.plugin_validate(
package_plugin, context, data_dict, schema, 'package_create')
log.debug('package_create validate_errs=%r user=%s package=%s data=%r',
errors, context.get('user'),
data.get('name'), data_dict)
if errors:
model.Session.rollback()
> raise ValidationError(errors)
E ValidationError: None - {'resources': [{'schedule': [{}, {}]}]}
/srv/app/src/ckan/ckan/logic/action/create.py:182: ValidationError
```
| hey @amercader , @wardi , I found what causes the error...
[https://github.com/ckan/ckan/blob/ace6850ddabb1bc533c6942cc434e806c62236e5/ckan/lib/navl/dictization_functions.py#L290](url)
Here in this function somehow after all iteration are over, in `errors_unflattened` those items `{'citation': [{}], 'contact_address': [{}], 'resources': [{'schedule': [{}, {}, {}]}, {}]}` still lives... then we are calling `_remove_blank_keys()` and inside this func: `citation` and `contact_address` has no `value` so they are passing the validation: `if not any(value)` but not the `resources` because its `value` is `[{'schedule': [{}, {}, {}]}, {}]}` and is not empty so it didnt pass the validation .. and we are getting the error.
Should i modify `_remove_blank_keys()` and check `if key == 'resources'` and `if not any(value[0]['schedule'])` then remove the `key`?
Or if you have a better solution please let me know.
Thanks | 2021-12-15T09:01:27 |
|
ckan/ckan | 6,612 | ckan__ckan-6612 | [
"6605"
] | 775ab84565cc8b1c393ef4d163930c203a278ea2 | diff --git a/ckan/logic/validators.py b/ckan/logic/validators.py
--- a/ckan/logic/validators.py
+++ b/ckan/logic/validators.py
@@ -951,9 +951,9 @@ def email_is_unique(key, data, errors, context):
def one_of(list_of_value):
- ''' Checks if the provided value is present in a list '''
+ ''' Checks if the provided value is present in a list or is an empty string'''
def callable(value):
- if value not in list_of_value:
+ if value != "" and value not in list_of_value:
raise Invalid(_('Value must be one of {}'.format(list_of_value)))
return value
return callable
| diff --git a/ckan/tests/logic/test_validators.py b/ckan/tests/logic/test_validators.py
--- a/ckan/tests/logic/test_validators.py
+++ b/ckan/tests/logic/test_validators.py
@@ -869,6 +869,11 @@ def test_val_not_in_list(self):
func = validators.one_of(cont)
raises_invalid(func)(5)
+ def test_empty_val_accepted(self):
+ cont = [1, 2, 3, 4]
+ func = validators.one_of(cont)
+ assert func("") == ""
+
def test_tag_string_convert():
def convert(tag_string):
| OneOf validator does not accept empty value
**CKAN version**
2.9, master
**Describe the bug**
OneOf validator was added in https://github.com/ckan/ckan/issues/4800, it is used in for example scheming where there are select fields where selecting one is not required. 2.8 accepts it as is, 2.9 fails in validation error.
Simple test added to scheming here:
https://github.com/vrk-kpa/ckanext-scheming/blob/a4618a7c6dea180a125eaa52441ec9d1d528586a/ckanext/scheming/tests/test_validation.py#L71-L77
In 2.7 and 2.8 the test passes, on 2.9 it fails on validation error
https://github.com/vrk-kpa/ckanext-scheming/runs/4548504508?check_suite_focus=true#step:7:431

This results in optional fields becoming required fields when upgrading ckan to 2.9.
| 2021-12-20T12:06:19 |
|
ckan/ckan | 6,622 | ckan__ckan-6622 | [
"6621"
] | 50da8b9018c90b6158a678473f6a8504616186d3 | diff --git a/ckan/views/group.py b/ckan/views/group.py
--- a/ckan/views/group.py
+++ b/ckan/views/group.py
@@ -1064,7 +1064,7 @@ def _prepare(self, id, is_organization, data=None): # noqa
try:
_action(u'group_show')(context, data_dict)
- check_access(u'group_update', context)
+ _check_access(u'group_update', context, {u'id': id})
except NotAuthorized:
base.abort(403, _(u'Unauthorized to create a group'))
except NotFound:
| Wrong auth function used when editing organizations
**CKAN version**
2.9.4
**Describe the bug**
Organization edit view uses group_update auth function instead of organization_update
**Steps to reproduce**
Steps to reproduce the behavior:
- Override `group_update` auth function to always fail (allows only sysadmins)
- Attempt to edit an organization as a regular user
**Expected behavior**
Editing succeeds
**Additional details**
This is because `ckan.views.group.EditGroupView._prepare` calls `check_access` instead of the group type aware `_check_access`.
PR incoming
| 2021-12-29T07:13:26 |
||
ckan/ckan | 6,638 | ckan__ckan-6638 | [
"6631"
] | 86474733977828686e8fd1d1d0d3476b8cca2731 | diff --git a/ckan/config/environment.py b/ckan/config/environment.py
--- a/ckan/config/environment.py
+++ b/ckan/config/environment.py
@@ -227,6 +227,9 @@ def update_config():
except (sqlalchemy.exc.ProgrammingError, sqlalchemy.exc.OperationalError):
# The database is not yet initialised. It happens in `ckan db init`
pass
+ except sqlalchemy.exc.IntegrityError:
+ # Race condition, user already exists.
+ pass
# Close current session and open database connections to ensure a clean
# clean environment even if an error occurs later on
| Intermittent duplicate key errors when creating default sysadmin
**CKAN version**
CKAN 2.9.x. Does not appear to affect 2.8.
**Describe the bug**
When our continuous integration tests initialise a test CKAN 2.9 instance, they sometimes encounter a duplicate key exception when CKAN is attempting to create the 'default' sysadmin account. There does not appear to be any specific pattern to when the errors occur; re-running the build may resolve it, or not. This did not occur on CKAN 2.8.
**Steps to reproduce**
Our test scripts run the following CLI commands:
ckan -c /etc/ckan/default/production.ini db clean --yes
ckan -c /etc/ckan/default/production.ini db init
ckan -c /etc/ckan/default/production.ini comments initdb
ckan -c /etc/ckan/default/production.ini comments updatedb
ckan -c /etc/ckan/default/production.ini comments init_notifications_db
**Additional details**
Sample failed build:
https://github.com/qld-gov-au/ckanext-ytp-comments/runs/4480610398?check_suite_focus=true
(Search for "already exists" to locate the stack trace)
NB Although the error actually occurred on that run during a `ckanext-ytp-comments` command, it was not specific to the extension, as shown by an excerpt from the stack trace:
ckan_1 | File "/app/ckan/default/src/ckan/ckan/cli/cli.py", line 102, in _init_ckan_config
ckan_1 | ctx.obj = CkanCommand(value)
ckan_1 | File "/app/ckan/default/src/ckan/ckan/cli/cli.py", line 52, in __init__
ckan_1 | self.app = make_app(self.config)
ckan_1 | File "/app/ckan/default/src/ckan/ckan/config/middleware/__init__.py", line 56, in make_app
ckan_1 | load_environment(conf)
ckan_1 | File "/app/ckan/default/src/ckan/ckan/config/environment.py", line 123, in load_environment
ckan_1 | p.load_all()
ckan_1 | File "/app/ckan/default/src/ckan/ckan/plugins/core.py", line 161, in load_all
ckan_1 | unload_all()
ckan_1 | File "/app/ckan/default/src/ckan/ckan/plugins/core.py", line 208, in unload_all
ckan_1 | unload(*reversed(_PLUGINS))
ckan_1 | File "/app/ckan/default/src/ckan/ckan/plugins/core.py", line 236, in unload
ckan_1 | plugins_update()
ckan_1 | File "/app/ckan/default/src/ckan/ckan/plugins/core.py", line 153, in plugins_update
ckan_1 | environment.update_config()
ckan_1 | File "/app/ckan/default/src/ckan/ckan/config/environment.py", line 322, in update_config
ckan_1 | logic.get_action('get_site_user')({'ignore_auth': True}, None)
ckan_1 | File "/app/ckan/default/src/ckan/ckan/logic/__init__.py", line 477, in wrapped
ckan_1 | result = _action(context, data_dict, **kw)
ckan_1 | File "/app/ckan/default/src/ckan/ckan/logic/action/get.py", line 2398, in get_site_user
ckan_1 | model.Session.flush()
| Does `ckan.logic.action.get:get_site_user` need some kind of transaction lock, to prevent race conditions between checking the presence of a user, and trying to add that user? Something like https://stackoverflow.com/questions/14520340/sqlalchemy-and-explicit-locking | 2022-01-10T22:27:18 |
|
ckan/ckan | 6,658 | ckan__ckan-6658 | [
"6657"
] | f5ee41fc68fdcbd51153c35406790cdd81e5eb75 | diff --git a/ckan/lib/navl/validators.py b/ckan/lib/navl/validators.py
--- a/ckan/lib/navl/validators.py
+++ b/ckan/lib/navl/validators.py
@@ -60,14 +60,19 @@ def not_empty(key: FlattenKey, data: FlattenDataDict,
.. code-block::
data, errors = tk.navl_validate(
- {"hello": 0},
+ {"hello": None},
{"hello": [not_empty]}
)
assert errors == {"hello": [error_message]}
"""
value = data.get(key)
- if not value or value is missing:
+ valid_values = [False, 0, 0.0]
+
+ if value in valid_values:
+ return
+
+ if value is missing or not value:
errors[key].append(_('Missing value'))
raise StopOnError
| diff --git a/ckan/tests/lib/navl/test_validators.py b/ckan/tests/lib/navl/test_validators.py
--- a/ckan/tests/lib/navl/test_validators.py
+++ b/ckan/tests/lib/navl/test_validators.py
@@ -7,6 +7,7 @@
import pytest
import ckan.lib.navl.validators as validators
+from ckan.lib.navl.dictization_functions import StopOnError
def validator_data_dict():
@@ -343,3 +344,41 @@ def test_already_has_a_value(self):
dict_ = {"key": "original"}
validators.default("default_value")("key", dict_, {}, {})
assert dict_ == {"key": "original"}
+
+
+class TestNotEmpty(object):
+
+ def test_not_empty_passes(self):
+ dict_ = {"key": "some value"}
+ errors = {"key": []}
+ validators.not_empty("key", dict_, errors, {})
+ assert errors == {"key": []}
+
+ def test_not_empty_fails(self):
+ dict_ = {"key": ""}
+ errors = {"key": []}
+ with pytest.raises(StopOnError):
+ validators.not_empty("key", dict_, errors, {})
+ assert errors == {"key": ["Missing value"]}
+
+ @pytest.mark.parametrize('value', [True, 1, "False", "0"])
+ def test_not_empty_passes_truthy(self, value):
+ dict_ = {"key": value}
+ errors = {"key": []}
+ validators.not_empty("key", dict_, errors, {})
+ assert errors == {"key": []}
+
+ @pytest.mark.parametrize('value', [False, 0, 0.0])
+ def test_not_empty_passes_false_and_zero(self, value):
+ dict_ = {"key": value}
+ errors = {"key": []}
+ validators.not_empty("key", dict_, errors, {})
+ assert errors == {"key": []}
+
+ @pytest.mark.parametrize('value', [[], {}, set(), ()])
+ def test_not_empty_fails_empty_objects(self, value):
+ dict_ = {"key": value}
+ errors = {"key": []}
+ with pytest.raises(StopOnError):
+ validators.not_empty("key", dict_, errors, {})
+ assert errors == {"key": ["Missing value"]}
| not_empty validator does not support `False` or 0
**CKAN version**
All
**Describe the bug**
The `not_empty` validator raises an error when the value is any "[falsy](https://docs.python.org/3/library/stdtypes.html#truth-value-testing)" one , including `False` or `0`, which might be legitimately correct in a boolean or int field.
This is generally not an issue because the validators get data sent from an HTTP request so the incoming data_dict that is validated has all values defined as strings.
```python
{
"name": "my-dataset",
"visible_to_external_users": "False",
}
```
But if calling the actions directly from Python (eg in the tests with `call_action`) the value can be passed as a boolean and then validation fails:
```python
{
"name": "my-dataset",
"visible_to_external_users": False,
}
# raises ckan.logic.ValidationError: None - {'visible_to_external_users': ['Missing value']}
```
`not_empty` should allow `False` and `0` for numeric types.
| 2022-01-18T10:15:42 |
|
ckan/ckan | 6,660 | ckan__ckan-6660 | [
"6649"
] | 1565a9a11a77a9b4e24af2080b3800d0b38930ae | diff --git a/ckan/lib/helpers.py b/ckan/lib/helpers.py
--- a/ckan/lib/helpers.py
+++ b/ckan/lib/helpers.py
@@ -2748,8 +2748,7 @@ def get_translated(data_dict, field):
try:
return data_dict[field + u'_translated'][language]
except KeyError:
- val = data_dict.get(field, '')
- return _(val) if val and isinstance(val, str) else val
+ return data_dict.get(field, '')
@core_helper
| The title of a dataset is translated in some cases
**CKAN version**
2.8.4
**Describe the bug**
The title of a dataset is translated in some cases if you run ckan localized.
**Steps to reproduce**
Steps to reproduce the behavior:
- run ckan localized, choose the german language (de)
- create a new dataset with the title "private"
- review the created dataset in the detail page: It shows up as "Privat" in title and Breadcrumb
Same happens for example if you name the created dataset "Draft" - it will lead to the title "Entwurf".
**Expected behavior**
The dataset keeps it's given name (stays untranslated).
**Additional details**


| 2022-01-18T13:50:51 |
||
ckan/ckan | 6,682 | ckan__ckan-6682 | [
"6636"
] | dd787e2d372ff556af3deaa3cb39d38b4847ef26 | diff --git a/ckan/views/group.py b/ckan/views/group.py
--- a/ckan/views/group.py
+++ b/ckan/views/group.py
@@ -377,7 +377,11 @@ def pager_url(q=None, page=None): # noqa
def _update_facet_titles(facets, group_type):
for plugin in plugins.PluginImplementations(plugins.IFacets):
- facets = plugin.group_facets(facets, group_type, None)
+ facets = (
+ plugin.group_facets(facets, group_type, None)
+ if group_type == "group"
+ else plugin.organization_facets(facets, group_type, None)
+ )
return facets
| organization_facets not working, instead replaced by group_facets but no description given about the change
**CKAN version**
2.9
**Describe the bug**
[organization_facets](https://docs.ckan.org/en/2.9/extensions/plugin-interfaces.html#ckan.plugins.interfaces.IFacets.organization_facets) that were working in the 2.8 version of ckan are not working any more and there is no description in the documentation about changing of any thing. Instead group_facets function is being used to render facets on organization page, which was supposed to work on group page.
**Steps to reproduce**
I dig deep down into the framework code and got to know that upexpected and unnecessary changes have been made which are not even documented. I researching thoroughly I got to know that organization_facet is nowehere registering or updating our facets instead [group_facets](https://docs.ckan.org/en/2.9/extensions/plugin-interfaces.html#ckan.plugins.interfaces.IFacets.group_facets), which is supposed to work on groups page is being used to render facets on organization page
**Expected behavior**
The organization_facets function supposed to work as it used to work in ckan 2.8 version i.e. render the facets on organization page but now it is not updating the facet_dict that needs to be rendered.
**Additional details**
links have been attached and the necessary detail is provided regarding the issue
| @amercader any updates on this issue?
@amercader @hussnainwithss @mominimtiaz786
The issue exists because the [function](https://github.com/ckan/ckan/blob/2.8/ckan/controllers/organization.py#L27) for organizations was not migrated from pylons to flask correctly.
@TomeCirun was working on this and he would provide a PR later this week | 2022-02-02T10:05:36 |
|
ckan/ckan | 6,701 | ckan__ckan-6701 | [
"6672"
] | 06caebe23aaf9144bc1a7bc4aaee8aa14150421f | diff --git a/ckanext/datastore/logic/action.py b/ckanext/datastore/logic/action.py
--- a/ckanext/datastore/logic/action.py
+++ b/ckanext/datastore/logic/action.py
@@ -170,7 +170,7 @@ def datastore_create(context, data_dict):
log.debug(
'Setting datastore_active=True on resource {0}'.format(resobj.id)
)
- set_datastore_active_flag(model, data_dict, True)
+ set_datastore_active_flag(context, data_dict, True)
result.pop('id', None)
result.pop('connection_url', None)
@@ -423,7 +423,7 @@ def datastore_delete(context, data_dict):
'Setting datastore_active=False on resource {0}'.format(
resource.id)
)
- set_datastore_active_flag(model, data_dict, False)
+ set_datastore_active_flag(context, data_dict, False)
result.pop('id', None)
result.pop('connection_url', None)
@@ -622,7 +622,7 @@ def check_access(table_names):
return result
-def set_datastore_active_flag(model, data_dict, flag):
+def set_datastore_active_flag(context, data_dict, flag):
'''
Set appropriate datastore_active flag on CKAN resource.
@@ -631,6 +631,7 @@ def set_datastore_active_flag(model, data_dict, flag):
# We're modifying the resource extra directly here to avoid a
# race condition, see issue #3245 for details and plan for a
# better fix
+ model = context['model']
update_dict = {'datastore_active': flag}
# get extras(for entity update) and package_id(for search index update)
@@ -648,24 +649,20 @@ def set_datastore_active_flag(model, data_dict, flag):
model.Session.commit()
- # get package with updated resource from solr
+ # get package with updated resource from package_show
# find changed resource, patch it and reindex package
psi = search.PackageSearchIndex()
- solr_query = search.PackageSearchQuery()
- q = {
- 'q': 'id:"{0}"'.format(package_id),
- 'fl': 'data_dict',
- 'wt': 'json',
- 'fq': 'site_id:"%s"' % config.get_value('ckan.site_id'),
- 'rows': 1
- }
- for record in solr_query.run(q)['results']:
- solr_data_dict = json.loads(record['data_dict'])
- for resource in solr_data_dict['resources']:
+ try:
+ _data_dict = p.toolkit.get_action('package_show')(context, {
+ 'id': package_id
+ })
+ for resource in _data_dict['resources']:
if resource['id'] == data_dict['resource_id']:
resource.update(update_dict)
- psi.index_package(solr_data_dict)
+ psi.index_package(_data_dict)
break
+ except (logic.NotAuthorized, logic.NotFound) as e:
+ log.error(e.message)
def _check_read_only(context, resource_id):
| API option doesn't show when the multiple resources are added to the new datasets.
**CKAN version**
**2.9.5**
**Describe the bug**
Datastore won't get active when multiple resources are added to the newly created datasets.
**Steps to reproduce**
1. Create Datasets
2. Add New resource
3. Click `Save and add another` resource to add another resource.
4. Finally click `Save` to finish the dataset creation. You will see that only one dataset has an API option, even all files pushed to the datastore.
**Expected behavior**
datastore state should be active even when multiple resources are added.
**Additional details**
I think for some reason datastore state doesn't get updated for the draft dataset.
| Hey @smotornyuk, @sagargg, I was doing a bit of research about this problem, seems everything's fine except this query from `solr` which returns an empty list after we submit the first resource:
https://github.com/ckan/ckan/blob/d61a533cc330b6050f4957573f58ec912695ed0a/ckanext/datastore/logic/action.py#L662-L668
So our first resource never reaches for the update in line 666 which contains the `{'datastore': True}`
Seems like `solr` cannot find the package with the given id when we are adding two resources in a row with `save & add another` `button`... (This is valid for the first resource only.)
Do you have any idea why this happens?
Thanks
ps. One weird behavior I've noticed: accidentally forgot to remove breakpoints (which cause to stop the worker) and after submitting both resources in a row I noticed the worker stuck on the breakpoint after exiting it I can see now both resources are with Data API.
By default CKAN [filters out all draft datasets(non-active)](https://github.com/ckan/ckan/blob/master/ckan/lib/search/query.py#L339-L340). When created, the dataset remains in the draft state till the user clicks on the **Finish** button.
@smotornyuk instead of making a query on the `solr-side` and iterating over it, can we just do this?

Thanks
Generally, yes. Just don't forget to take into account the fact that `package_show` can throw NotAuthorized/NotFound exceptions if the context is misformed. Not sure if it's possible to get such an exception in this particular case(there person, who uploads a resource probably has full access to the given package), but it's better to check if any worth-case scenario can happen
@smotornyuk Thanks | 2022-02-11T13:56:00 |
|
ckan/ckan | 6,705 | ckan__ckan-6705 | [
"6694"
] | af3d1e852ef78a4c7c2dee15d66c0af4e4d3b9fe | diff --git a/ckan/lib/dictization/model_dictize.py b/ckan/lib/dictization/model_dictize.py
--- a/ckan/lib/dictization/model_dictize.py
+++ b/ckan/lib/dictization/model_dictize.py
@@ -35,6 +35,7 @@
import ckan.lib.munge as munge
import ckan.model as model
from ckan.types import Context, Query
+from ckan.common import config
## package save
@@ -360,13 +361,15 @@ def get_packages_for_this_group(group_: model.Group,
else:
q['fq'] = '+groups:"{0}"'.format(group_.name)
- # Allow members of organizations to see private datasets.
if group_.is_organization:
is_group_member = (context.get('user') and
authz.has_user_permission_for_group_or_org(
group_.id, context.get('user'), 'read'))
if is_group_member:
q['include_private'] = True
+ else:
+ if config.get('ckan.auth.allow_dataset_collaborators'):
+ q['include_private'] = True
if not just_the_count:
# package_search limits 'rows' anyway, so this is only if you
| diff --git a/ckan/tests/lib/dictization/test_model_dictize.py b/ckan/tests/lib/dictization/test_model_dictize.py
--- a/ckan/tests/lib/dictization/test_model_dictize.py
+++ b/ckan/tests/lib/dictization/test_model_dictize.py
@@ -317,6 +317,33 @@ def test_group_dictize_for_org_with_package_count(self):
assert org["package_count"] == 1
+ @pytest.mark.ckan_config("ckan.auth.allow_dataset_collaborators", True)
+ def test_group_dictize_for_org_with_private_package_count_collaborator(
+ self,
+ ):
+ import ckan.tests.helpers as helpers
+
+ org_obj = factories.Organization.model()
+ user_obj = factories.User.model()
+ private_dataset = factories.Dataset(owner_org=org_obj.id, private=True)
+ factories.Dataset(owner_org=org_obj.id)
+ context = {
+ "model": model,
+ "session": model.Session,
+ "auth_user_obj": user_obj,
+ }
+ org = model_dictize.group_dictize(org_obj, context)
+ assert org["package_count"] == 1
+
+ helpers.call_action(
+ "package_collaborator_create",
+ id=private_dataset["id"],
+ user_id=user_obj.id,
+ capacity="member",
+ )
+ org = model_dictize.group_dictize(org_obj, context)
+ assert org["package_count"] == 2
+
@pytest.mark.usefixtures("non_clean_db")
class TestPackageDictize:
| /Organization package count incorrect, Collaborator private packages aren't included.
**CKAN 2.9**
Packages that you are a collaborator of are not included in the dataset count on the /organization view page but then are included on the organizations/<organistion_name> page.
I'm not sure whether this is the intended functionality? But it seems like packages you are a collaborator of should be included.
Thanks in advance.
| Hey, @n00dl3nate I've just tested this out, works fine for me, the only dataset that didn't count in the `/organization` page are those set to private...
If the core team agree to count the private datasets for collaborators on the `/organization` page I will make a PR
Hello, Thanks for your response, Apologies I left out that piece of information that it is private datasets that you are a collaborator of isn't being included in the dataset count on but private datasets that are owned by an organisation that you are a member of are included in the count. is there a reason why they shouldn't be included in the count?
@TomeCirun @n00dl3nate Yes, these two counts should have the same value. Also compare it to the Organization facet on the dataset search page to make sure they match | 2022-02-15T15:56:38 |
ckan/ckan | 6,709 | ckan__ckan-6709 | [
"6665"
] | 8fa76894f3c5d9a6bce3c0a28da55e60e434f7e0 | diff --git a/ckan/lib/search/index.py b/ckan/lib/search/index.py
--- a/ckan/lib/search/index.py
+++ b/ckan/lib/search/index.py
@@ -52,6 +52,7 @@ def clear_index() -> None:
query = "+site_id:\"%s\"" % (config.get_value('ckan.site_id'))
try:
conn.delete(q=query)
+ conn.commit()
except socket.error as e:
err = 'Could not connect to SOLR %r: %r' % (conn.url, e)
log.error(err)
| Obsolete requirements
**CKAN version**
2.9.5
**Describe the bug**
Obsolete requirements:
* pytz is pinned to 2016, https://github.com/ckan/ckan/blob/2.9/requirements.in#L23
* Zope.interface is pinned to a version from 2016, prior to python 3.6 support. https://github.com/ckan/ckan/blob/2.9/requirements.in#L38 (ref: https://pypi.org/project/zope.interface/)
Specifically, (at least on python 3) the zope.interface pin is the one that's preventing us from using modern setuptools and requiring a pin. (at least, until one installs ckanext-dcat, which is limited to setuptools<58.0 due to rdflib-jsonld)
**Proposed fix**
Unpin pytz. Update zope.interface to <5.0
| :+1: from me, these seem like sensible requirements to upgrade even for a point release. | 2022-02-18T12:28:24 |
|
ckan/ckan | 6,729 | ckan__ckan-6729 | [
"6727"
] | 5381d3c691019807d839d3b80477cf51ac74165f | diff --git a/ckan/lib/helpers.py b/ckan/lib/helpers.py
--- a/ckan/lib/helpers.py
+++ b/ckan/lib/helpers.py
@@ -2695,6 +2695,9 @@ def resource_formats() -> dict[str, list[str]]:
global _RESOURCE_FORMATS
if not _RESOURCE_FORMATS:
format_file_path = config.get_value('ckan.resource_formats')
+ if not format_file_path:
+ format_file_path = resource_formats_default_file()
+
with open(format_file_path, encoding='utf-8') as format_file:
try:
file_resource_formats = json.loads(format_file.read())
| error [500] - when providing template-bs3 in the config
**CKAN version**
Master
**Describe the bug**

**Steps to reproduce**
Go to `ckan.ini` file and change the default option for `ckan.base_templates_folder` to `templates-bs3` and when you run `CKAN` you will get `500`
The problem occurs because `CKAN Master` could not find `flask.pop_message()` it was removed in #6239.
I will make `PR` by the end of the day and will replace it with the built-in `h.get_flashed_messages`.
| 2022-03-01T14:28:24 |
||
ckan/ckan | 6,742 | ckan__ckan-6742 | [
"5807"
] | 8fa76894f3c5d9a6bce3c0a28da55e60e434f7e0 | diff --git a/ckan/cli/notify.py b/ckan/cli/notify.py
--- a/ckan/cli/notify.py
+++ b/ckan/cli/notify.py
@@ -1,23 +1,44 @@
# encoding: utf-8
+from logging import getLogger
import click
from ckan.model import Session, Package, DomainObjectOperation
from ckan.model.modification import DomainObjectModificationExtension
+from ckan.logic import NotAuthorized, ValidationError
[email protected](
- name=u'notify',
- short_help=u'Send out modification notifications.'
-)
+log = getLogger(__name__)
+
+
[email protected](name="notify", short_help="Send out modification notifications.")
def notify():
pass
[email protected](
- name=u'replay',
- short_help=u'Send out modification signals.'
-)
[email protected](name="replay", short_help="Send out modification signals.")
def replay():
dome = DomainObjectModificationExtension()
for package in Session.query(Package):
dome.notify(package, DomainObjectOperation.changed)
+
+
[email protected](name="send_emails", short_help="Send out Email notifications.")
+def send_emails():
+ """ Sends an email to users notifying about new activities.
+
+ As currently implemented, it will only send notifications from dashboard
+ activity list if users have `activity_streams_email_notifications` set
+ in their profile. It will send emails with updates depending
+ on the `ckan.email_notifications_since` config. (default: 2 days.)
+ """
+ import ckan.logic as logic
+ import ckan.lib.mailer as mailer
+ from ckan.types import Context
+ from typing import cast
+
+ site_user = logic.get_action("get_site_user")({"ignore_auth": True}, {})
+ context = cast(Context, {"user": site_user["name"]})
+ try:
+ logic.get_action("send_email_notifications")(context, {})
+ except (NotAuthorized, ValidationError, mailer.MailerException) as e:
+ log.error(e)
diff --git a/ckan/lib/email_notifications.py b/ckan/lib/email_notifications.py
--- a/ckan/lib/email_notifications.py
+++ b/ckan/lib/email_notifications.py
@@ -11,12 +11,13 @@
import datetime
import re
from typing import Any, cast
+from jinja2 import Environment
import ckan.model as model
import ckan.logic as logic
-import ckan.lib.base as base
+import ckan.lib.jinja_extensions as jinja_extensions
-from ckan.common import ungettext, config
+from ckan.common import ungettext, ugettext, config
from ckan.types import Context
@@ -77,6 +78,18 @@ def string_to_timedelta(s: str) -> datetime.timedelta:
return delta
+def render_activity_email(activities: list[dict[str, Any]]) -> str:
+ globals = {'site_title': config.get_value('ckan.site_title')}
+ template_name = 'activity_streams/activity_stream_email_notifications.text'
+
+ env = Environment(**jinja_extensions.get_jinja_env_options())
+ # Install the given gettext, ngettext callables into the environment
+ env.install_gettext_callables(ugettext, ungettext) # type: ignore
+
+ template = env.get_template(template_name, globals=globals)
+ return template.render({'activities': activities})
+
+
def _notifications_for_activities(
activities: list[dict[str, Any]],
user_dict: dict[str, Any]) -> list[dict[str, str]]:
@@ -105,15 +118,15 @@ def _notifications_for_activities(
# say something about the contents of the activities, or single out
# certain types of activity to be sent in their own individual emails,
# etc.
+
subject = ungettext(
"{n} new activity from {site_title}",
"{n} new activities from {site_title}",
len(activities)).format(
site_title=config.get_value('ckan.site_title'),
n=len(activities))
- body = base.render(
- 'activity_streams/activity_stream_email_notifications.text',
- extra_vars={'activities': activities})
+
+ body = render_activity_email(activities)
notifications = [{
'subject': subject,
'body': body
@@ -214,7 +227,6 @@ def get_and_send_notifications_for_user(user: dict[str, Any]) -> None:
email_last_sent = model.Dashboard.get(user['id']).email_last_sent
activity_stream_last_viewed = (
model.Dashboard.get(user['id']).activity_stream_last_viewed)
-
since = max(email_notifications_since, email_last_sent,
activity_stream_last_viewed)
diff --git a/ckan/logic/action/update.py b/ckan/logic/action/update.py
--- a/ckan/logic/action/update.py
+++ b/ckan/logic/action/update.py
@@ -1140,8 +1140,8 @@ def dashboard_mark_activities_old(
def send_email_notifications(context: Context, data_dict: DataDict) -> ActionResult.SendEmailNotifications:
'''Send any pending activity stream notification emails to users.
- You must provide a sysadmin's API key in the Authorization header of the
- request, or call this action from the command-line via a `paster post ...`
+ You must provide a sysadmin's API key/token in the Authorization header of the
+ request, or call this action from the command-line via a `ckan notify send_emails ...`
command.
'''
| Email notifications documentation not working on CKAN 2.9.x
**CKAN version: 2.9.x**
**Describe the bug**
The documentation regarding email notifications https://docs.ckan.org/en/2.9/maintaining/email-notifications.html#email-notifications is not working on 2.9.x due to nothing replacing `paster post`
**Steps to reproduce**
Try running `ckan post`, command post not available.
**Expected behavior**
An authenticated API request to the send_email_notifications action is made.
| @amercader also struggling with the same issue. I think the 'ckan post' command has been replaced with the 'ckan notify' but unable to find any info on usage.
Could you assist with this issue?
Cheers,
Ammar
@mbocevski have you been able to sort this issue yet? I am also trying to work this one out. I think the 'ckan post' command has been replaced with the 'ckan notify' but unable to find any info on usage.
Notify is a different thing. Post was internal functionality of paster, which needs to implemented in ckan cli as paster was removed.
> Notify is a different thing. Post was internal functionality of paster, which needs to implemented in ckan cli as paster was removed.
@Zharktas thanks for the quick response. Any work around for sending email notifications until this is implemented by the ckan team?
There is no workaround, someone needs to implement it.
>have you been able to sort this issue yet?
>There is no workaround
@ammarfmg yes there is a workaround. What `ckan post` does is basically sends a sysadmin authenticated request to the `/api/action/send_email_notifications` endpoint. So you can implement it simply by registering a sysadmin account, generating an API token and then using that token you can call something like:
`curl -s -H "Authorization: SYSADMIN_API_TOKEN" -d {} http://<ckan_url>/api/action/send_email_notifications`
You can see how we've implemented it on our ckan helm package here: https://github.com/keitaroinc/ckan-helm/blob/master/templates/cronjob.yaml#L19-L26
> > have you been able to sort this issue yet?
>
> > There is no workaround
>
> @ammarfmg yes there is a workaround. What `ckan post` does is basically sends a sysadmin authenticated request to the `/api/action/send_email_notifications` endpoint. So you can implement it simply by registering a sysadmin account, generating an API token and then using that token you can call something like:
> `curl -s -H "Authorization: SYSADMIN_API_TOKEN" -d {} http://<ckan_url>/api/action/send_email_notifications`
>
> You can see how we've implemented it temporarily on our ckan helm package here: https://github.com/keitaroinc/ckan-helm/blob/master/templates/cronjob.yaml#L19-L26
@mbocevski thanks a lot for this. I will give it a try.
@mbocevski after generating an API key, can I add the curl command to my crontab file with an @hourly keyword?
@hourly curl -s -H "Authorization: SYSADMIN_API_TOKEN" -d {} http://<ckan_url>/api/action/send_email_notifications
>can I add the curl command to my crontab file
Of course.
Thanks again. It is running but giving this message:
"Bad request - JSON Error: Invalid request. Please use POST method for your request"
I will try to solve it.
>"Bad request - JSON Error: Invalid request. Please use POST method for your request"
Did you include the `-d {}` that means to send empty data with the request which will automatically send a POST request. You can always add `-X POST` if you want to explicitly set the request method.
Try running the curl command from the shell to see that all works fine. You don't need to use `sudo`. It shouldn't matter but you have double forward-slashes `//api`. If it works fine from the shell, and doesn't work from cron then check whether you need to quote the command or something depends on your systems cron.
Ok sure. I am getting the following output in shell:
{"help": "http://x.x.x.x/api/3/action/help_show?name=send_email_notifications", "success": true, "result": null}
Is this the expected behavior?
>{"help": "http://x.x.x.x/api/3/action/help_show?name=send_email_notifications", "success": true, "result": null}
>Is this the expected behavior?
Yes! Great.
> > {"help": "http://x.x.x.x/api/3/action/help_show?name=send_email_notifications", "success": true, "result": null}
> > Is this the expected behavior?
>
> Yes! Great.
Thank you and have a good day.
> There is no workaround, someone needs to implement it.
@Zharktas What do you think to implement it in the [notify CLI](https://github.com/ckan/ckan/blob/master/ckan/cli/notify.py) itself with the new click command as `send_email_notifications` which will trigger the notifications
Something like this
```python
@notify.command(
name=u'send_email_notifications',
short_help=u'Send out Email notifications.'
)
def send_email_notifications():
if not converters.asbool(
config.get('ckan.activity_streams_email_notifications')):
raise ValidationError('ckan.activity_streams_email_notifications'
' is not enabled in config')
email_notifications.get_and_send_notifications_for_all_users()
```
WDYT about the above approach?
> WDYT about the above approach?
I mostly like it, but if it's already getting filed under 'notify', maybe it can have a shorter name?
NB Putting it inside a Click command would move the overhead from the CKAN server to the location where the command is being run; often they are the same, but they don't have to be. | 2022-03-09T12:48:03 |
|
ckan/ckan | 6,746 | ckan__ckan-6746 | [
"4933"
] | 22faf9a2b355f8df44e8c01a46e840276077f209 | diff --git a/ckan/views/home.py b/ckan/views/home.py
--- a/ckan/views/home.py
+++ b/ckan/views/home.py
@@ -2,9 +2,10 @@
from __future__ import annotations
+from urllib.parse import urlencode
from typing import Any, Optional, cast, List, Tuple
-from flask import Blueprint, abort, redirect
+from flask import Blueprint, abort, redirect, request
import ckan.model as model
import ckan.logic as logic
@@ -90,7 +91,12 @@ def about() -> str:
def redirect_locale(target_locale: str, path: Optional[str] = None) -> Any:
+
target = f'/{target_locale}/{path}' if path else f'/{target_locale}'
+
+ if request.args:
+ target += f'?{urlencode(request.args)}'
+
return redirect(target, code=308)
@@ -104,6 +110,7 @@ def redirect_locale(target_locale: str, path: Optional[str] = None) -> Any:
locales_mapping: List[Tuple[str, str]] = [
('zh_TW', 'zh_Hant_TW'),
('zh_CN', 'zh_Hans_CN'),
+ ('no', 'nb_NO'),
]
for locale in locales_mapping:
| diff --git a/ckan/tests/controllers/test_home.py b/ckan/tests/controllers/test_home.py
--- a/ckan/tests/controllers/test_home.py
+++ b/ckan/tests/controllers/test_home.py
@@ -136,10 +136,10 @@ def test_redirects_legacy_locales(self, app):
f'http://test.ckan.net/{new_locale}'
)
- response = app.get(f'/{legacy_locale}/dataset', follow_redirects=False)
+ response = app.get(f'/{legacy_locale}/dataset?some=param', follow_redirects=False)
assert response.status_code == 308
assert (
response.headers['Location'] ==
- f'http://test.ckan.net/{new_locale}/dataset'
+ f'http://test.ckan.net/{new_locale}/dataset?some=param'
)
| Norwegian language is not working with Flask blueprints
### CKAN Version
2.8, master
### Expected behaviour
When changing language to Norwegian, it should translate the pages. (Implementation from views, not controllers)
### Actual behaviour
When changing language to Norwegian nothing happens
### Steps to reproduce
1. Setup pure CKAN 2.8 or master.
2. Change language to Norwegian or homepage or about page.
| Hi @amercader , I added a link to 'no' folder translations in order to add new Norwegian option 'nb_NO'. As far as I understand 'no' is an old format, but pylons support both 'no' and 'nb_NO' while Flask babel doesn't.
In order to fix this for 100% we need to update the transifex code from 'no' to 'nb_NO' on https://www.transifex.com/okfn/ckan/. But not sure if it is critical right now.
There might be other languages that has same issue.
As a second option, if I understand correctly, we can modify the '.tx/config' file by adding "trans.no = ckan/i18n/nb_NO/LC_MESSAGES/ckan.po" and pull the languages again, as a result it will save translations from transifex for 'no' to 'nb_NO' folder. Not sure if it works that way.
Another issue for CKAN 2.8 that https://github.com/ckan/ckan/commit/56fb0b19db735c4583309fe1e9fdc8eb06364189#diff-d89c6cc9bc6f95acbc9906e48b946eb0 is not backported, as a result some laguages still not shown as an active.
Hi. I've installed CKAN 2.9, and Norwegian is still not working. It would be nice if the issue got fixed.
However, I got around it by using this hack: Renaming some files, folders and config options.
```
cd /usr/lib/ckan/default/src/ckan/ckan/i18n/
sudo mv no/ nb_NO
```
```
cd /usr/lib/ckan/default/src/ckan/ckan/public/base/i18n
sudo mv no.js nb_NO.js
```
In /etc/ckan/default/ckan.ini
```
## Internationalisation Settings
ckan.locale_default = nb_NO
ckan.locale_order = nb_NO sv en pt_BR ja it cs_CZ ca es fr el sr sr@latin sk fi ru de pl nl bg ko_KR hu sa sl lv
ckan.locales_offered = nb_NO sv en
ckan.locales_filtered_out = en_GB
```
@tsmaavik could you please test the proposed fix?
@engerrs is it possible to make such a change on Transifex? | 2022-03-11T14:32:41 |
ckan/ckan | 6,748 | ckan__ckan-6748 | [
"6165"
] | 22faf9a2b355f8df44e8c01a46e840276077f209 | diff --git a/ckan/lib/authenticator.py b/ckan/lib/authenticator.py
--- a/ckan/lib/authenticator.py
+++ b/ckan/lib/authenticator.py
@@ -23,9 +23,11 @@ def authenticate(
login = identity['login']
user = User.by_name(login)
+ if not user:
+ user = User.by_email(login)
if user is None:
- log.debug('Login failed - username %r not found', login)
+ log.debug('Login failed - username or email %r not found', login)
elif not user.is_active():
log.debug('Login as %r failed - user isn\'t active', login)
elif not user.validate_password(identity['password']):
diff --git a/ckan/model/user.py b/ckan/model/user.py
--- a/ckan/model/user.py
+++ b/ckan/model/user.py
@@ -9,7 +9,7 @@
import six
import passlib.utils
-from passlib.hash import pbkdf2_sha512 # type: ignore
+from passlib.hash import pbkdf2_sha512 # type: ignore
from sqlalchemy.sql.expression import or_
from sqlalchemy.orm import synonym
from sqlalchemy import types, Column, Table, func
@@ -87,8 +87,8 @@ class User(core.StatefulObjectMixin,
DOUBLE_SLASH = re.compile(r':\/([^/])')
@classmethod
- def by_email(cls: Type[TUser], email: str) -> list["TUser"]:
- return meta.Session.query(cls).filter_by(email=email).all()
+ def by_email(cls: Type[TUser], email: str) -> Optional["User"]:
+ return meta.Session.query(cls).filter_by(email=email).first()
@classmethod
def get(cls, user_reference: Optional[str]) -> Optional["User"]:
| diff --git a/ckan/tests/controllers/test_group.py b/ckan/tests/controllers/test_group.py
--- a/ckan/tests/controllers/test_group.py
+++ b/ckan/tests/controllers/test_group.py
@@ -416,10 +416,8 @@ def test_membership_add_by_email(self, app, mail_server):
status=200
)
assert len(mail_server.get_smtp_messages()) == 1
- users = model.User.by_email(email)
- assert len(users) == 1, users
- user = users[0]
- assert user.email == email, user
+ user = model.User.by_email(email)
+ assert user.email == email
assert group["id"] in user.get_group_ids(capacity="member")
def test_membership_edit_page(self, app):
diff --git a/ckan/tests/lib/test_authenticator.py b/ckan/tests/lib/test_authenticator.py
--- a/ckan/tests/lib/test_authenticator.py
+++ b/ckan/tests/lib/test_authenticator.py
@@ -7,27 +7,26 @@
@pytest.mark.usefixtures("non_clean_db")
class TestUsernamePasswordAuthenticator(object):
- def test_succeeds_if_login_and_password_are_correct(self):
- password = "somepass"
- user = factories.User(password=password)
- identity = {"login": user["name"], "password": password}
+ password = 'somepass'
+
+ def test_succeeds_if_username_and_password_are_correct(self):
+ user = factories.User(password=self.password)
+ identity = {"login": user["name"], "password": self.password}
assert (
UsernamePasswordAuthenticator().authenticate({}, identity)
== user["name"]
)
def test_fails_if_user_is_deleted(self):
- password = "somepass"
- user = factories.User(password=password, state="deleted")
- identity = {"login": user["name"], "password": password}
+ user = factories.User(password=self.password, state="deleted")
+ identity = {"login": user["name"], "password": self.password}
assert (
UsernamePasswordAuthenticator().authenticate({}, identity) is None
)
def test_fails_if_user_is_pending(self):
- password = "somepass"
- user = factories.User(password=password, state="pending")
- identity = {"login": user["name"], "password": password}
+ user = factories.User(password=self.password, state="pending")
+ identity = {"login": user["name"], "password": self.password}
assert (
UsernamePasswordAuthenticator().authenticate({}, identity) is None
)
@@ -51,3 +50,11 @@ def test_fails_if_received_no_login_or_pass(self, identity):
assert (
UsernamePasswordAuthenticator().authenticate({}, identity) is None
)
+
+ def test_succeeds_if_email_and_password_are_correct(self):
+ user = factories.User(password=self.password)
+ identity = {"login": user["email"], "password": self.password}
+ assert (
+ UsernamePasswordAuthenticator().authenticate({}, identity)
+ == user["name"]
+ )
diff --git a/ckan/tests/lib/test_signals.py b/ckan/tests/lib/test_signals.py
--- a/ckan/tests/lib/test_signals.py
+++ b/ckan/tests/lib/test_signals.py
@@ -102,3 +102,8 @@ def test_login(self, app):
app.post(url, data=data)
assert success.call_count == 1
assert fail.call_count == 3
+
+ data = {u"login": user["email"], u"password": "correct123"}
+ app.post(url, data=data)
+ assert success.call_count == 2
+ assert fail.call_count == 3
| Users should be able to login with email address
**CKAN version**
master
Email addresses have been unique since 2.9 and password resets can be done with email addresses. Currently it's confusing for users who reset their passwords using email address but need to know their user names when logging in. There should not be any issues enabling login with email address.
| 2022-03-13T21:19:48 |
|
ckan/ckan | 6,752 | ckan__ckan-6752 | [
"6579"
] | 5899ab0866ae098fa7655f60a4bb9476371d93c3 | diff --git a/ckan/logic/action/get.py b/ckan/logic/action/get.py
--- a/ckan/logic/action/get.py
+++ b/ckan/logic/action/get.py
@@ -339,7 +339,7 @@ def _group_or_org_list(
if errors:
raise ValidationError(errors)
sort = data_dict.get('sort') or config.get_value('ckan.default_group_sort')
- q = data_dict.get('q')
+ q = data_dict.get('q', '').strip()
all_fields = asbool(data_dict.get('all_fields', None))
| Searching organization with trailing space failed
**CKAN version**
2.9
**Describe the bug**
When doing an organization search, the search terms are not trimmed. Searching with `GSA ` will not find organization **GSA**.
**Steps to reproduce**
https://demo.ckan.org/organization/?q=organization+
It gives no results.
**Expected behavior**
Show results including **Sample Organization**.
**Additional details**
Search terms need to be trimmed.
| @FuhuXia I am interested to work in this issue. | 2022-03-15T13:00:59 |
|
ckan/ckan | 6,774 | ckan__ckan-6774 | [
"6258"
] | 6456ecccfc5118c743963d14dd77d8abf3cdc693 | diff --git a/ckan/views/api.py b/ckan/views/api.py
--- a/ckan/views/api.py
+++ b/ckan/views/api.py
@@ -478,7 +478,7 @@ def snippet(snippet_path, ver=API_REST_DEFAULT_VERSION):
def i18n_js_translations(lang, ver=API_REST_DEFAULT_VERSION):
if lang not in get_locales_from_config():
- return _finish_bad_request('Unknown locale: {}'.format(lang))
+ return _finish_bad_request(u'Unknown locale: {}'.format(lang))
ckan_path = os.path.join(os.path.dirname(__file__), u'..')
source = os.path.abspath(os.path.join(ckan_path, u'public',
| diff --git a/ckan/tests/controllers/test_api.py b/ckan/tests/controllers/test_api.py
--- a/ckan/tests/controllers/test_api.py
+++ b/ckan/tests/controllers/test_api.py
@@ -274,6 +274,7 @@ def test_jsonp_does_not_work_on_post_requests(self, app):
[dataset1["name"], dataset2["name"]]
)
+
def test_i18n_only_known_locales_are_accepted(app):
url = url_for("api.i18n_js_translations", ver=2, lang="fr")
| remove extra comma
Because typo of additional comma we see:
`jinja2.exceptions.TemplateSyntaxError: invalid syntax for function call expression`
- [ ] includes tests covering changes
- [ ] includes updated documentation
- [ ] includes user-visible changes
- [ ] includes API changes
- [ ] includes bugfix for possible backport
Please [X] all the boxes above that apply
| 2022-03-28T15:06:10 |
|
ckan/ckan | 6,797 | ckan__ckan-6797 | [
"6512"
] | c408daf24e4bed7403952b38dacb8ae2e115ce4b | diff --git a/ckan/cli/server.py b/ckan/cli/server.py
--- a/ckan/cli/server.py
+++ b/ckan/cli/server.py
@@ -19,6 +19,8 @@
@click.option(u"-p", u"--port", help=u"Port number")
@click.option(u"-r", u"--disable-reloader", is_flag=True,
help=u"Disable reloader")
[email protected](u"-E", u"--passthrough-errors", is_flag=True,
+ help=u"Disable error caching (useful to hook debuggers)")
@click.option(
u"-t", u"--threaded", is_flag=True,
help=u"Handle each request in a separate thread"
@@ -40,10 +42,16 @@
help=u"Key file to use to enable SSL. Passing 'adhoc' will "
" automatically generate a new one (on each server reload).")
@click.pass_context
-def run(ctx, host, port, disable_reloader, threaded, extra_files, processes,
- ssl_cert, ssl_key):
+def run(ctx, host, port, disable_reloader, passthrough_errors, threaded,
+ extra_files, processes, ssl_cert, ssl_key):
u"""Runs the Werkzeug development server"""
+ # passthrough_errors overrides conflicting options
+ if passthrough_errors:
+ disable_reloader = True
+ threaded = False
+ processes = 1
+
# Reloading
use_reloader = not disable_reloader
config_extra_files = tk.aslist(
@@ -95,4 +103,5 @@ def run(ctx, host, port, disable_reloader, threaded, extra_files, processes,
processes=processes,
extra_files=extra_files,
ssl_context=ssl_context,
+ passthrough_errors=passthrough_errors,
)
| Support for pdb and debuggers
### Proposed fixes:
It is now possible to debug ckan with pdb/ipdb/PyCharm debugger and others, both outside Docker and inside Docker.
I just exposed a `werkzeug` option to the CKAN CLI, called `passthrough_errors`. Enabling that, together with `--disable-reloader` (which should be the default in my opinion, like it was in the past), allow to run pdb without making other changes to the source code.
`threads` should not be enabled and `processes` should be set to 1. These are the defaults already.
> passthrough_errors (bool) – set this to True to disable the error catching. This means that the server will die on errors but it can be useful to hook debuggers in (pdb etc.)
-- https://werkzeug.palletsprojects.com/en/2.0.x/serving/
Example:
```
$ cd contrib/docker
$ docker-compose up --build -d
$ # wait...
$ docker-compose exec ckan bash
root@f6a71d0b7686:/# python3 -m pdb /usr/lib/ckan/venv/bin/ckan -c /etc/ckan/production.ini run --host 0.0.0.0 -E --disable-reloader
> /usr/lib/ckan/venv/bin/ckan(3)<module>()
-> import re
(Pdb) b ckan/views/api.py:215
Breakpoint 1 at /usr/lib/ckan/venv/src/ckan/ckan/views/api.py:215
(Pdb) c
2021-11-01 17:00:50,832 INFO [ckan.cli] Using configuration file /etc/ckan/production.ini
2021-11-01 17:00:50,832 INFO [ckan.config.environment] Loading static files from public
2021-11-01 17:00:50,954 INFO [ckan.config.environment] Loading templates from /usr/lib/ckan/venv/src/ckan/ckan/templates
2021-11-01 17:00:51,552 INFO [ckan.config.environment] Loading templates from /usr/lib/ckan/venv/src/ckan/ckan/templates
2021-11-01 17:00:52,173 INFO [ckan.cli.server] Running CKAN on http://0.0.0.0:5000
2021-11-01 17:00:52,174 WARNI [werkzeug] * Running on all addresses.
WARNING: This is a development server. Do not use it in a production deployment.
```
...then `http://localhost:5000/api/3/action/package_search` can be opened in the web browser to trigger the breakpoint:
```
> /usr/lib/ckan/venv/src/ckan/ckan/views/api.py(215)action()
-> try:
(Pdb)
```
### Features:
- [ ] includes tests covering changes
- [x] includes updated documentation
- [X] includes user-visible changes
- [ ] includes API changes
- [ ] includes bugfix for possible backport
| It could be improved by having a `--debug` option which is mutually exclusive with everything else, but it would require a bigger change, and it would clash with the current nomenclature (debugging on CKAN today is mostly done on the web server, which is very limiting).
Any comment on this PR?
@frafra can you give an example on how this new option is used (`passthrough_errors`) or why it is useful?
> @frafra can you give an example on how this new option is used (`passthrough_errors`) or why it is useful?
Sure. I thought that it was that werkzeug documentation was good enough to explain what such option does.
It is not possible to debug CKAN with regular Python tools and IDE if the server is executed with certain options: automatic reload, multithread/multiprocessing, and error catching. This last behaviour cannot be controlled from CKAN CLI, so I exposed that via the `--passthrough_error` option. Enabling such options disables werkzeug error-catching, which hides all the errors from the user, by catching them, and allows it to just fail.
As reported initially, from the werkzeug documentation:
> passthrough_errors (bool) – set this to True to disable the error catching. This means that the server will die on errors but it can be useful to hook debuggers in (pdb etc.)
If CKAN CLI is executed using `--disable-reloader --passthrough_error`, and if `ckan.devserver.threaded` is set to `False` (default) and `ckan.devserver.multiprocess` is set to 1 (default), then CKAN can be debugged with normal tools, like pdb, ipdb, IDEs and such.
To make things even easier to set up (especially for IDEs), there is a draft PR open which I will propose as soon as this one gets merged: https://github.com/ckan/ckan/pull/6458
It could be interesting to have it as environmental variable, like the other parameters: http://docs.ckan.org/en/2.9/maintaining/configuration.html
Any feedback on that?
I have been using this patch regularly for the last month combined with Docker (I run CKAN with these special options) and it made the development of CKAN extensions so much easier. I catch all the exceptions, I am able to run step by step, set breakpoints, list the source code, skip a line, print a value, execute a statement just once, and such.
Is there anything else I should do to see this option merged? Write some documentation, maybe?
Meeting notes 10/02/2020: the new option should override the other options which it depends on; documentation should be also added. | 2022-04-06T12:39:09 |
|
ckan/ckan | 6,828 | ckan__ckan-6828 | [
"6827"
] | bcffdbc7334e06593144a94bf086d3ba1a17052a | diff --git a/ckan/lib/mailer.py b/ckan/lib/mailer.py
--- a/ckan/lib/mailer.py
+++ b/ckan/lib/mailer.py
@@ -13,8 +13,7 @@
from email.message import EmailMessage
from email import utils
-from ckan.common import config
-import ckan.common
+from ckan.common import _, config
import ckan
@@ -22,8 +21,6 @@
import ckan.lib.helpers as h
from ckan.lib.base import render
-from ckan.common import _
-
log = logging.getLogger(__name__)
AttachmentWithType = Union[
Tuple[str, IO[str], str],
@@ -70,7 +67,8 @@ def _mail_recipient(
msg['From'] = _("%s <%s>") % (sender_name, mail_from)
msg['To'] = u"%s <%s>" % (recipient_name, recipient_email)
msg['Date'] = utils.formatdate(time())
- msg['X-Mailer'] = "CKAN %s" % ckan.__version__
+ if not config.get_value('ckan.hide_version'):
+ msg['X-Mailer'] = "CKAN %s" % ckan.__version__
if reply_to and reply_to != '':
msg['Reply-to'] = reply_to
diff --git a/ckan/logic/action/get.py b/ckan/logic/action/get.py
--- a/ckan/logic/action/get.py
+++ b/ckan/logic/action/get.py
@@ -1900,7 +1900,7 @@ def package_search(context: Context, data_dict: DataDict) -> ActionResult.Packag
include_private = asbool(data_dict.pop('include_private', False))
include_drafts = asbool(data_dict.pop('include_drafts', False))
include_deleted = asbool(data_dict.pop('include_deleted', False))
-
+
if not include_private:
data_dict['fq'] = '+capacity:public ' + data_dict['fq']
@@ -2435,15 +2435,17 @@ def status_show(context: Context, data_dict: DataDict) -> ActionResult.StatusSho
'''
extensions = config.get_value('ckan.plugins')
- return {
+ site_info = {
'site_title': config.get_value('ckan.site_title'),
'site_description': config.get_value('ckan.site_description'),
'site_url': config.get_value('ckan.site_url'),
- 'ckan_version': ckan.__version__,
'error_emails_to': config.get_value('email_to'),
'locale_default': config.get_value('ckan.locale_default'),
'extensions': extensions,
}
+ if not config.get_value('ckan.hide_version') or authz.is_sysadmin(context['user']):
+ site_info['ckan_version'] = ckan.__version__
+ return site_info
def vocabulary_list(
| diff --git a/ckan/tests/lib/test_mailer.py b/ckan/tests/lib/test_mailer.py
--- a/ckan/tests/lib/test_mailer.py
+++ b/ckan/tests/lib/test_mailer.py
@@ -34,6 +34,39 @@ def get_email_subject(self, msg):
class TestMailer(MailerBase):
def test_mail_recipient(self, mail_server):
user = factories.User()
+
+ msgs = mail_server.get_smtp_messages()
+ assert msgs == []
+
+ # send email
+ test_email = {
+ "recipient_name": "Bob",
+ "recipient_email": user["email"],
+ "subject": "Meeting",
+ "body": "The meeting is cancelled.\n",
+ "headers": {"header1": "value1"},
+ }
+ mailer.mail_recipient(**test_email)
+
+ # check it went to the mock smtp server
+ msgs = mail_server.get_smtp_messages()
+ assert len(msgs) == 1
+ msg = msgs[0]
+ assert msg[1] == config["smtp.mail_from"]
+ assert msg[2] == [test_email["recipient_email"]]
+ assert list(test_email["headers"].keys())[0] in msg[3], msg[3]
+ assert list(test_email["headers"].values())[0] in msg[3], msg[3]
+ assert test_email["subject"] in msg[3], msg[3]
+ assert "X-Mailer" in msg[3], "Missing X-Mailer header"
+ expected_body = self.mime_encode(
+ test_email["body"], test_email["recipient_name"]
+ )
+ assert expected_body in msg[3]
+
+ @pytest.mark.ckan_config('ckan.hide_version', True)
+ def test_mail_recipient_hiding_mailer(self, mail_server):
+ user = factories.User()
+
msgs = mail_server.get_smtp_messages()
assert msgs == []
@@ -57,6 +90,8 @@ def test_mail_recipient(self, mail_server):
assert list(test_email["headers"].values())[0] in msg[3], msg[3]
assert test_email["subject"] in msg[3], msg[3]
assert msg[3].startswith('Content-Type: text/plain'), msg[3]
+ assert "X-Mailer" not in msg[3], \
+ "Should have skipped X-Mailer header"
expected_body = self.mime_encode(
test_email["body"], test_email["recipient_name"]
)
diff --git a/ckan/tests/logic/action/test_get.py b/ckan/tests/logic/action/test_get.py
--- a/ckan/tests/logic/action/test_get.py
+++ b/ckan/tests/logic/action/test_get.py
@@ -2917,6 +2917,36 @@ def test_status_show(self):
assert type(status["extensions"]) == list
assert status["extensions"] == ["stats"]
+ @pytest.mark.ckan_config("ckan.plugins", "stats")
+ @pytest.mark.ckan_config('ckan.hide_version', True)
+ def test_status_show_hiding_version(self):
+
+ status = helpers.call_action("status_show")
+
+ assert "ckan_version" not in status, "Should have skipped CKAN version"
+ assert status["site_url"] == "http://test.ckan.net"
+ assert status["site_title"] == "CKAN"
+ assert status["site_description"] == ""
+ assert status["locale_default"] == "en"
+
+ assert type(status["extensions"]) == list
+ assert status["extensions"] == ["stats"]
+
+ @pytest.mark.ckan_config("ckan.plugins", "stats")
+ @pytest.mark.ckan_config('ckan.hide_version', True)
+ def test_status_show_version_to_sysadmins(self):
+ sysadmin = factories.Sysadmin()
+ status = helpers.call_action("status_show", context={"user": sysadmin["name"]})
+
+ assert status["ckan_version"] == __version__
+ assert status["site_url"] == "http://test.ckan.net"
+ assert status["site_title"] == "CKAN"
+ assert status["site_description"] == ""
+ assert status["locale_default"] == "en"
+
+ assert type(status["extensions"]) == list
+ assert status["extensions"] == ["stats"]
+
class TestJobList(helpers.FunctionalRQTestBase):
def test_all_queues(self):
| CKAN version is exposed to the public
**CKAN version**
2.8, 2.9
**Describe the bug**
The exact version of CKAN is visible to the public in the status_show API call and as a header on all emails. This makes reconnaissance by malicious third parties easier.
**Steps to reproduce**
Visit /api/action/status_show
**Expected behavior**
There should be an option to hide the CKAN version in use.
**Additional details**
Will raise a pull request soon.
| 2022-04-28T01:40:30 |
|
ckan/ckan | 6,836 | ckan__ckan-6836 | [
"6833"
] | c00891b0a35c7c334701bbcb56cfad61dbfedabe | diff --git a/ckan/logic/action/get.py b/ckan/logic/action/get.py
--- a/ckan/logic/action/get.py
+++ b/ckan/logic/action/get.py
@@ -2433,6 +2433,7 @@ def status_show(context: Context, data_dict: DataDict) -> ActionResult.StatusSho
:rtype: dictionary
'''
+ _check_access('status_show', context, data_dict)
extensions = config.get_value('ckan.plugins')
return {
diff --git a/ckan/logic/auth/get.py b/ckan/logic/auth/get.py
--- a/ckan/logic/auth/get.py
+++ b/ckan/logic/auth/get.py
@@ -487,3 +487,8 @@ def package_collaborator_list_for_user(context: Context,
if user_obj and data_dict.get('id') in (user_obj.name, user_obj.id):
return {'success': True}
return {'success': False}
+
+
+def status_show(context: Context, data_dict: DataDict) -> AuthResult:
+ '''Show information about the site's configuration. Visible to all by default.'''
+ return {'success': True}
| diff --git a/ckan/tests/logic/auth/test_get.py b/ckan/tests/logic/auth/test_get.py
--- a/ckan/tests/logic/auth/test_get.py
+++ b/ckan/tests/logic/auth/test_get.py
@@ -621,3 +621,11 @@ def test_sysadmin_can_list_followees(self, func):
sysadmin = factories.Sysadmin()
context = {"user": sysadmin["name"], "model": model}
assert helpers.call_auth(func, context=context)
+
+
[email protected]("non_clean_db")
+class TestStatusShow:
+
+ def test_status_show_is_visible_to_anonymous(self):
+ context = {"user": "", "model": model}
+ assert helpers.call_auth("status_show", context)
diff --git a/ckan/tests/test_coding_standards.py b/ckan/tests/test_coding_standards.py
--- a/ckan/tests/test_coding_standards.py
+++ b/ckan/tests/test_coding_standards.py
@@ -326,7 +326,6 @@ class TestActionAuth(object):
"get: recently_changed_packages_activity_list",
"get: resource_search",
"get: roles_show",
- "get: status_show",
"get: tag_search",
"get: term_translation_show",
"get: user_followee_count",
| Action status_show has no corresponding auth function
**CKAN version**
2.9.5
**Describe the bug**
The Action-API function `status_show` does not call a corresponding auth function (there is none). This means that, if a plugin _does_ register an auth function for `status_show`, there will be an error when the action is called.
**Steps to reproduce**
* Implement IAuthFunctions in a plugin and add `status_show` to `get_auth_functions()`.
* Call `status_show` as a non-sysadmin user.
* This leads to the exception above.
**Expected behavior**
If a plugin _does_ registers an auth function for `status_show`, I expect it to be called when the action is called.
**Additional details**
Stacktrace:
```
2022-04-28 08:06:19,368 ERROR [ckan.views.api] Action function status_show did not call its auth function
Traceback (most recent call last):
File "/usr/lib/ckan/default/src/ckan/ckan/config/middleware/../../views/api.py", line 292, in action
result = function(context, request_data)
File "/usr/lib/ckan/default/src/ckan/ckan/logic/__init__.py", line 511, in wrapped
raise Exception(
Exception: Action function status_show did not call its auth function
```
Action function:
https://github.com/ckan/ckan/blob/ca537ad25e13320b6fbf91f41031eadc30500f12/ckan/logic/action/get.py#L2406
| 2022-04-29T15:06:28 |
|
ckan/ckan | 6,879 | ckan__ckan-6879 | [
"6878"
] | a18603ec182e279488c0e91b78cd957a3ed49d30 | diff --git a/ckan/plugins/interfaces.py b/ckan/plugins/interfaces.py
--- a/ckan/plugins/interfaces.py
+++ b/ckan/plugins/interfaces.py
@@ -1267,8 +1267,9 @@ def resource_form(self, package_type: str) -> str:
'''
return ''
- def validate(self, context: Context, data_dict: DataDict, schema: Schema,
- action: str) -> tuple[dict[str, Any], dict[str, Any]]:
+ def validate(
+ self, context: Context, data_dict: DataDict, schema: Schema,
+ action: str) -> Optional[tuple[dict[str, Any], dict[str, Any]]]:
u'''Customize validation of datasets.
When this method is implemented it is used to perform all validation
@@ -1298,7 +1299,7 @@ def validate(self, context: Context, data_dict: DataDict, schema: Schema,
and lists-of-string-error-messages as values
:rtype: (dictionary, dictionary)
'''
- return {}, {}
+ return
def prepare_dataset_blueprint(self, package_type: str,
blueprint: Blueprint) -> Blueprint:
@@ -1483,8 +1484,9 @@ def setup_template_variables(self, context: Context,
Add variables to c just prior to the template being rendered.
'''
- def validate(self, context: Context, data_dict: DataDict, schema: Schema,
- action: str) -> tuple[dict[str, Any], dict[str, Any]]:
+ def validate(
+ self, context: Context, data_dict: DataDict, schema: Schema,
+ action: str) -> Optional[tuple[dict[str, Any], dict[str, Any]]]:
u'''Customize validation of groups.
When this method is implemented it is used to perform all validation
@@ -1515,7 +1517,7 @@ def validate(self, context: Context, data_dict: DataDict, schema: Schema,
and lists-of-string-error-messages as values
:rtype: (dictionary, dictionary)
'''
- return {}, {}
+ return
def prepare_group_blueprint(self, group_type: str,
blueprint: Blueprint) -> Blueprint:
diff --git a/ckanext/example_idatasetform/plugin.py b/ckanext/example_idatasetform/plugin.py
--- a/ckanext/example_idatasetform/plugin.py
+++ b/ckanext/example_idatasetform/plugin.py
@@ -190,3 +190,15 @@ def package_form(self) -> Any:
# legacy support for the deprecated method works.
def check_data_dict(self, data_dict: dict[str, Any], schema: Any = None):
ExampleIDatasetFormPlugin.num_times_check_data_dict_called += 1
+
+
+class ExampleIDatasetFormInheritPlugin(plugins.SingletonPlugin,
+ tk.DefaultDatasetForm):
+ """An example IDatasetForm CKAN plugin, inheriting all methods
+ from the default interface.
+ """
+ plugins.implements(plugins.IDatasetForm, inherit=True)
+
+ def package_types(self):
+
+ return ["custom_dataset"]
| diff --git a/ckan/tests/logic/action/test_create.py b/ckan/tests/logic/action/test_create.py
--- a/ckan/tests/logic/action/test_create.py
+++ b/ckan/tests/logic/action/test_create.py
@@ -666,6 +666,7 @@ def test_resource_create_for_update(self):
helpers.call_action('resource_create', package_id=dataset['id'], url='http://example.com', description='hey')
assert mock_package_show.call_args_list[0][0][0].get('for_update') is True
+
@pytest.mark.usefixtures("non_clean_db")
class TestMemberCreate(object):
def test_group_member_creation(self):
diff --git a/ckanext/example_idatasetform/tests/test_example_idatasetform.py b/ckanext/example_idatasetform/tests/test_example_idatasetform.py
--- a/ckanext/example_idatasetform/tests/test_example_idatasetform.py
+++ b/ckanext/example_idatasetform/tests/test_example_idatasetform.py
@@ -526,3 +526,12 @@ def test_template_with_options(self, type_, app):
url = url_for(type_ + '.read', id=dataset['name'])
resp = app.get(url, status=200)
assert resp.body == 'Hello, {}!'.format(type_)
+
+
[email protected]_config("ckan.plugins", u"example_idatasetform_inherit")
[email protected]("with_plugins")
+def test_validation_works_on_default_validate():
+
+ dataset = factories.Dataset(name="my_dataset", type="custom_dataset")
+
+ assert dataset["name"] == "my_dataset"
| Validation doesn't work on plugins inheriting the core `IDatasetForm` methods
**CKAN version**
Current master (2.10)
**Describe the bug**
Consider the following test:
```python
import ckan.plugins as plugins
import ckan.plugins.toolkit as tk
class CustomDatasetType(plugins.SingletonPlugin, tk.DefaultDatasetForm):
plugins.implements(plugins.IDatasetForm, inherit=True)
def package_types(self):
return ["custom_dataset"]
@pytest.mark.ckan_config("ckan.auth.create_unowned_dataset", True)
def test_search_datasets_returns_only_datasts(self, app):
factories.Dataset(type="custom_dataset")
```
This will fail with an SQLAlchemy error
```
sqlalchemy.exc.IntegrityError: (psycopg2.errors.NotNullViolation) null value in column "name" violates not-null constraint
```
Upon further investigation, when calling the NAVL validation function from `package_create`:
https://github.com/ckan/ckan/blob/a18603ec182e279488c0e91b78cd957a3ed49d30/ckan/logic/action/create.py#L178-L179
`data` is an empty dict!
I'll send a proposed fix as PR
| 2022-05-27T11:29:45 |
|
ckan/ckan | 6,891 | ckan__ckan-6891 | [
"6884"
] | 89c7b6063a9cf0e0198ce2c4aa04030f2ed9be8b | diff --git a/ckan/views/dataset.py b/ckan/views/dataset.py
--- a/ckan/views/dataset.py
+++ b/ckan/views/dataset.py
@@ -566,13 +566,27 @@ def post(self, package_type: str) -> Union[Response, str]:
data_dict[u'type'] = package_type
pkg_dict = get_action(u'package_create')(context, data_dict)
+ create_on_ui_requires_resources = config.get_value(
+ 'ckan.dataset.create_on_ui_requires_resources'
+ )
if ckan_phase:
- # redirect to add dataset resources
- url = h.url_for(
- u'{}_resource.new'.format(package_type),
- id=pkg_dict[u'name']
+ if create_on_ui_requires_resources:
+ # redirect to add dataset resources if
+ # create_on_ui_requires_resources is set to true
+ url = h.url_for(
+ u'{}_resource.new'.format(package_type),
+ id=pkg_dict[u'name']
+ )
+ return h.redirect_to(url)
+
+ get_action(u'package_update')(
+ cast(Context, dict(context, allow_state_change=True)),
+ dict(pkg_dict, state=u'active')
+ )
+ return h.redirect_to(
+ u'{}.read'.format(package_type),
+ id=pkg_dict["id"]
)
- return h.redirect_to(url)
return _form_save_redirect(
pkg_dict[u'name'], u'new', package_type=package_type
| Documented form setting create_on_ui_requires_resources not implemented
**CKAN 2.9**
**Describe the bug**
The form setting `ckan.dataset.create_on_ui_requires_resources` [is documented](https://ckan.readthedocs.io/en/2.9/maintaining/configuration.html#ckan-dataset-create-on-ui-requires-resources), but does not appear to be implemented.
**Steps to reproduce**
Set `ckan.dataset.create_on_ui_requires_resources` to `False` in `ckan.ini`, restart CKAN, observe that resources are still required to be added when adding a new dataset.
**Expected behavior**
Setting `ckan.dataset.create_on_ui_requires_resources` to `False` should make the adding of resources optional.
**Additional details**
As of this writing, it appears not to be implemented at all. Running `grep -Ri create_on_ui_requires_resources` on the master branch of the ckan repository only returns a hit in `ckan/config/config_declaration.yaml`, which describes the expected behaviour but does not implement it.
| 2022-06-01T21:22:35 |
||
ckan/ckan | 6,892 | ckan__ckan-6892 | [
"6886"
] | 89c7b6063a9cf0e0198ce2c4aa04030f2ed9be8b | diff --git a/ckan/views/group.py b/ckan/views/group.py
--- a/ckan/views/group.py
+++ b/ckan/views/group.py
@@ -545,7 +545,7 @@ def member_delete(id: str, group_type: str,
})
h.flash_notice(_(u'Group member has been deleted.'))
return h.redirect_to(u'{}.members'.format(group_type), id=id)
- user_dict = _action(u'group_show')(context, {u'id': user_id})
+ user_dict = _action(u'user_show')(context, {u'id': user_id})
# TODO: Remove
# ckan 2.9: Adding variables that were removed from c object for
@@ -561,7 +561,8 @@ def member_delete(id: str, group_type: str,
extra_vars: dict[str, Any] = {
u"user_id": user_id,
u"user_dict": user_dict,
- u"group_id": id
+ u"group_id": id,
+ u"group_type": group_type
}
return base.render(_replace_group_org(u'group/confirm_delete_member.html'),
extra_vars)
| diff --git a/ckan/tests/controllers/test_organization.py b/ckan/tests/controllers/test_organization.py
--- a/ckan/tests/controllers/test_organization.py
+++ b/ckan/tests/controllers/test_organization.py
@@ -575,3 +575,23 @@ def test_anonymous_users_cannot_add_members(self, app):
},
status=403,
)
+
+ def test_member_delete(self, app):
+ sysadmin = factories.Sysadmin()
+ user = factories.User()
+ org = factories.Organization(
+ users=[{"name": user["name"], "capacity": "member"}]
+ )
+ env = {"REMOTE_USER": six.ensure_str(sysadmin["name"])}
+ # our user + test.ckan.net
+ assert len(org["users"]) == 2
+ with app.flask_app.test_request_context():
+ app.post(
+ url_for("organization.member_delete", id=org["id"], user=user["id"]),
+ extra_environ=env,
+ )
+ org = helpers.call_action('organization_show', id=org['id'])
+
+ # only test.ckan.net
+ assert len(org['users']) == 1
+ assert user["id"] not in org["users"][0]["id"]
| Member_delete causes not found errors even though everything should be present
**CKAN version**
2.9, master
**Describe the bug**
Clicking delete member from organization results in not found.
**Steps to reproduce**
Create an organization.
Add an user to it.
Delete the user from it.
**Expected behavior**
Member is deleted and the UI returns to member view
**Additional details**
Most likely bug resides in this line https://github.com/ckan/ckan/blob/91c9366cf8df0dc4e12a9a043756eda5e40534b0/ckan/views/group.py#L548 as it calls `group_show` with user id.
| Add a test that prevents this failure
I can not reproduce the error...
CKAN master
<img width="1314" alt="image" src="https://user-images.githubusercontent.com/72216462/171497285-78db82e7-037b-4038-b281-555d56133690.png">
CKAN 2.9.5
<img width="1624" alt="image" src="https://user-images.githubusercontent.com/72216462/171498236-ff92b63c-c48d-4f16-a123-382ce651cbc6.png">
This actually requires that javascript is disabled for whatever reason, which is why it wasn't caught before. The modal works, but the url from the delete button does not. Can be reproduced by copying the url from the button and pasting it to the browser url bar. | 2022-06-02T08:16:27 |
ckan/ckan | 6,897 | ckan__ckan-6897 | [
"4986"
] | c7e946c0b144c1de7157b0cc3f6414ec8927e4c8 | diff --git a/ckan/logic/action/create.py b/ckan/logic/action/create.py
--- a/ckan/logic/action/create.py
+++ b/ckan/logic/action/create.py
@@ -34,7 +34,7 @@
import ckan.model
from ckan.common import _
-from ckan.types import Context, DataDict, ErrorDict, Schema, FlattenErrorDict
+from ckan.types import Context, DataDict, ErrorDict, Schema
# FIXME this looks nasty and should be shared better
from ckan.logic.action.update import _update_package_relationship
@@ -1046,7 +1046,6 @@ def user_invite(context: Context,
:returns: the newly created user
:rtype: dictionary
'''
- import string
_check_access('user_invite', context, data_dict)
schema = context.get('schema',
@@ -1061,24 +1060,16 @@ def user_invite(context: Context,
raise NotFound()
name = _get_random_username_from_email(data['email'])
- # Choose a password. However it will not be used - the invitee will not be
- # told it - they will need to reset it
- while True:
- password = ''.join(random.SystemRandom().choice(
- string.ascii_lowercase + string.ascii_uppercase + string.digits)
- for _ in range(12))
- # Occasionally it won't meet the constraints, so check
- validation_errors: FlattenErrorDict = {}
- ckan.logic.validators.user_password_validator(
- ('password', ), {('password', ): password},
- validation_errors, context)
- if not validation_errors:
- break
data['name'] = name
- data['password'] = password
+ # send the proper schema when creating a user from here
+ # so the password field would be ignored.
+ invite_schema = ckan.logic.schema.create_user_for_user_invite_schema()
+
data['state'] = model.State.PENDING
- user_dict = _get_action('user_create')(context, data)
+ user_dict = _get_action('user_create')(
+ cast(Context, dict(context, schema=invite_schema)),
+ data)
user = model.User.get(user_dict['id'])
assert user
member_dict = {
@@ -1087,14 +1078,11 @@ def user_invite(context: Context,
'role': data['role']
}
- if group.is_organization:
- _get_action('organization_member_create')(context, member_dict)
- group_dict = _get_action('organization_show')(context,
- {'id': data['group_id']})
- else:
- _get_action('group_member_create')(context, member_dict)
- group_dict = _get_action('group_show')(context,
- {'id': data['group_id']})
+ org_or_group = 'organization' if group.is_organization else 'group'
+ _get_action(f'{org_or_group}_member_create')(context, member_dict)
+ group_dict = _get_action(f'{org_or_group}_show')(
+ context, {'id': data['group_id']})
+
try:
mailer.send_invite(user, group_dict, data['role'])
except (socket_error, mailer.MailerException) as error:
diff --git a/ckan/logic/schema.py b/ckan/logic/schema.py
--- a/ckan/logic/schema.py
+++ b/ckan/logic/schema.py
@@ -441,6 +441,13 @@ def default_user_schema(
})
+@validator_args
+def create_user_for_user_invite_schema(ignore_missing: Validator):
+ schema = default_user_schema()
+ schema['password'] = [ignore_missing]
+ return schema
+
+
@validator_args
def user_new_form_schema(
unicode_safe: Validator, user_both_passwords_entered: Validator,
| diff --git a/ckan/tests/controllers/test_organization.py b/ckan/tests/controllers/test_organization.py
--- a/ckan/tests/controllers/test_organization.py
+++ b/ckan/tests/controllers/test_organization.py
@@ -5,6 +5,7 @@
from bs4 import BeautifulSoup
import ckan.authz as authz
+import ckan.model as model
from ckan.lib.helpers import url_for
from ckan.tests import factories, helpers
@@ -576,6 +577,24 @@ def test_anonymous_users_cannot_add_members(self, app):
status=403,
)
+ def test_create_user_for_user_invite(self, mail_server):
+ group = factories.Group()
+ sysadmin = factories.Sysadmin()
+ context = {"user": sysadmin["name"]}
+
+ user_form = {
+ "email": "[email protected]",
+ "group_id": group["id"],
+ "role": "member"
+ }
+
+ user_dict = helpers.call_action("user_invite", context, **user_form)
+ user_obj = model.User.get(user_dict["id"])
+
+ assert user_obj.password is None
+ assert user_obj.state == 'pending'
+ assert user_obj.last_active is None
+
def test_member_delete(self, app):
sysadmin = factories.Sysadmin()
user = factories.User()
| user_invite crashes if generated password does not validate
The `user_invite` function generates a hidden password that will pass the built-in validators, but if custom validators are supplied and the generated password fails, the function will crash with a KeyError ('password' does not exist in the error dict).
Furthermore, code review suggests that if the crash were fixed, it would be in danger of an infinite loop, constantly generating passwords that are not accepted.
### CKAN Version if known (or site URL)
CKAN 2.8.3
### Please describe the expected behaviour
Inviting a new member, identified by email address, to join an organisation, should result in an email to that address.
### Please describe the actual behaviour
Internal server error. Stack trace shows that this is a `KeyError: ('password',)` in `user_password_validator`.
### What steps can be taken to reproduce the issue?
- Add a password validator that requires non-alphanumeric symbols.
- Go to an organisation, select Manage-Members.
- Select an email address and Add Member.
| It seems to me that there are several fixes that should be applied:
- `user_password_validator` should initialize the `password` error key if it does not exist.
- Alternatively, `user_invite` should populate the `errors` dict with a blank `password` key before passing it to the validator function.
- The `test_validators` class should be updated with tests that pass in empty `errors` dictionaries.
- `user_invite` should limit the number of times it will retry password generation if validation fails.
- `user_invite` should use a stronger password generation mechanism; the current implementation never uses non-alphanumeric symbols, so it will always fail some types of custom validation.
Note that CKAN 2.7 handled the error somewhat more gracefully, displaying the validation failure on-screen, but still had no way to fix the problem if the validators were too strict for the password generation code.
Two proposals from our developer call on resolving this one:
1. Change the way invites work so that they send a token that allows the user to create a new account with specific permissions (don't create the user with a fake password and reuse the password reset tokens)
2. Add a "password_disabled" option to `user_create` and `user_update` to allow creating a user with no password set (stored as an invalid hash that no password would match) This could also be used for other accounts that don't need a password, such as the site user and users authenticated through other services.
Those would be good fixes too.
@ThrawnCA marked as good for contribution, if you have time to work on either approach I'm happy to review and merge. :-)
@wardi @ThrawnCA
We would like to work on this issue. Please me know if no one is working on this.
@Chandradeep-NEC No, no progress here. Go ahead.
@ThrawnCA, I am trying to reproduce the issue. I am facing issue related to SMTP server. I have configure SMTP server on my local machine. When I tried to add a member via email, Internal server error appear on GUI and invitation is not received on the entered email address, but user is created on GUI. To confirm the same I have configure external SMTP server and tried to add a member, Internal sever error did not appear on GUI this time and invitation is received on the entered email address and user is created. Which SMTP server approach you have taken while producing the issue?
Are you using a custom password validator? If you use the standard built-in validator, then it will work.
@ThrawnCA Please confirm as have you written a new function for user_password_validator to get custom password validator?
@Gauravp-NEC Yes; see https://github.com/qld-gov-au/ckan-ex-qgov/blob/master/ckanext/qgov/common/intercepts.py (probably not the most elegant way to implement it, but the same problem would arise with any other implementation that imposed stricter complexity requirements).
@wardi , as you suggested the way to solve this issue in comment https://github.com/ckan/ckan/issues/4986#issuecomment-533128823 no work have been done till now by anyone and this issue is open for so long.
I suggest that we should change the logic of def user_invite() in such a way that generated random password should contain at least 1 Upper case, 1 Lower case, 1 Special character and 1 Digit. so that it will never fail for any standard custom validation. Please let me know your opinion. If you agree I will raise the PR for it.
@Gauravp-NEC that would fix the problem only until someone comes up with a new password validation that doesn't work with these generated passwords. So it doesn't really fix the problem. | 2022-06-07T09:10:55 |
ckan/ckan | 6,928 | ckan__ckan-6928 | [
"6925"
] | a355d79e5df563c0af5bc557733b4bdc910058c9 | diff --git a/ckan/logic/action/update.py b/ckan/logic/action/update.py
--- a/ckan/logic/action/update.py
+++ b/ckan/logic/action/update.py
@@ -71,13 +71,13 @@ def resource_update(context, data_dict):
data_dict['url'] = ''
resource = model.Resource.get(id)
- context["resource"] = resource
- old_resource_format = resource.format
-
if not resource:
log.debug('Could not find resource %s', id)
raise NotFound(_('Resource was not found.'))
+ context["resource"] = resource
+ old_resource_format = resource.format
+
_check_access('resource_update', context, data_dict)
del context["resource"]
| Updating a non-existing resource causes an internal sever error
**CKAN version**
master
**Describe the bug**
Trying to update a resource that does not exist causes an internal server error instead of a not found error
**Steps to reproduce**
- using `httpie`: `http POST https://demo.ckan.org/api/action/resource_update id=doesnotexist`
- Causes an internal server error
**Expected behavior**
- "Not found" error
**Additional details**
Caused by [this line](https://github.com/ckan/ckan/blob/master/ckan/logic/action/update.py#L76) being placed before [these lines](https://github.com/ckan/ckan/blob/master/ckan/logic/action/update.py#L78-L80).
| Hey, @bzar, I just tested this via curl, I sent an id that doesn't exist, and it gives me the proper error message: 404 not found.
https://github.com/ckan/ckan/blob/7586d78682c30f205027522214f33ee2bf413055/ckan/logic/action/update.py#L73-L76
if you look at the code you can see in line 73 we have another check
```python
if resource is None
```
and here are my logs:


It's actually 2.9 and earlier issue, master has a check for it. 2.9 does not https://github.com/ckan/ckan/blob/ca537ad25e13320b6fbf91f41031eadc30500f12/ckan/logic/action/update.py#L73-L79 | 2022-06-20T20:46:14 |
|
ckan/ckan | 6,933 | ckan__ckan-6933 | [
"6793"
] | bfcc37596bf37113c2ad3774dd3a0b5002e071ed | diff --git a/ckanext/datastore/backend/postgres.py b/ckanext/datastore/backend/postgres.py
--- a/ckanext/datastore/backend/postgres.py
+++ b/ckanext/datastore/backend/postgres.py
@@ -1162,37 +1162,48 @@ def upsert_data(context: Context, data_dict: dict[str, Any]):
elif method in [_UPDATE, _UPSERT]:
unique_keys = _get_unique_key(context, data_dict)
- if len(unique_keys) < 1:
- raise ValidationError({
- 'table': [u'table does not have a unique key defined']
- })
for num, record in enumerate(records):
- # all key columns have to be defined
- missing_fields = [field for field in unique_keys
- if field not in record]
- if missing_fields:
+ if not unique_keys and '_id' not in record:
raise ValidationError({
- 'key': [u'''fields "{fields}" are missing
- but needed as key'''.format(
- fields=', '.join(missing_fields))]
+ 'table': [u'unique key must be passed for update/upsert']
})
+ elif '_id' not in record:
+ # all key columns have to be defined
+ missing_fields = [field for field in unique_keys
+ if field not in record]
+ if missing_fields:
+ raise ValidationError({
+ 'key': [u'''fields "{fields}" are missing
+ but needed as key'''.format(
+ fields=', '.join(missing_fields))]
+ })
+
for field in fields:
value = record.get(field['id'])
if value is not None and field['type'].lower() == 'nested':
# a tuple with an empty second value
record[field['id']] = (json.dumps(value), '')
- non_existing_filed_names = [field for field in record
- if field not in field_names]
- if non_existing_filed_names:
+ non_existing_field_names = [
+ field for field in record
+ if field not in field_names and field != '_id'
+ ]
+ if non_existing_field_names:
raise ValidationError({
'fields': [u'fields "{0}" do not exist'.format(
- ', '.join(non_existing_filed_names))]
+ ', '.join(non_existing_field_names))]
})
- unique_values = [record[key] for key in unique_keys]
+ if '_id' in record:
+ unique_values = [record['_id']]
+ pk_sql = '"_id"'
+ pk_values_sql = '%s'
+ else:
+ unique_values = [record[key] for key in unique_keys]
+ pk_sql = ','.join([identifier(part) for part in unique_keys])
+ pk_values_sql = ','.join(['%s'] * len(unique_keys))
used_fields = [field for field in fields
if field['id'] in record]
@@ -1203,19 +1214,18 @@ def upsert_data(context: Context, data_dict: dict[str, Any]):
if method == _UPDATE:
sql_string = u'''
- UPDATE "{res_id}"
+ UPDATE {res_id}
SET ({columns}, "_full_text") = ({values}, NULL)
WHERE ({primary_key}) = ({primary_value});
'''.format(
- res_id=data_dict['resource_id'],
+ res_id=identifier(data_dict['resource_id']),
columns=u', '.join(
[identifier(field)
for field in used_field_names]).replace('%', '%%'),
values=u', '.join(
['%s' for _ in used_field_names]),
- primary_key=u','.join(
- [u'"{0}"'.format(part) for part in unique_keys]),
- primary_value=u','.join(["%s"] * len(unique_keys))
+ primary_key=pk_sql.replace('%', '%%'),
+ primary_value=pk_values_sql,
)
try:
results = context['connection'].execute(
@@ -1233,24 +1243,23 @@ def upsert_data(context: Context, data_dict: dict[str, Any]):
elif method == _UPSERT:
sql_string = u'''
- UPDATE "{res_id}"
+ UPDATE {res_id}
SET ({columns}, "_full_text") = ({values}, NULL)
WHERE ({primary_key}) = ({primary_value});
- INSERT INTO "{res_id}" ({columns})
+ INSERT INTO {res_id} ({columns})
SELECT {values}
- WHERE NOT EXISTS (SELECT 1 FROM "{res_id}"
+ WHERE NOT EXISTS (SELECT 1 FROM {res_id}
WHERE ({primary_key}) = ({primary_value}));
'''.format(
- res_id=data_dict['resource_id'],
- columns=u', '.join([
- u'"{0}"'.format(field.replace('%', '%%'))
- for field in used_field_names]),
+ res_id=identifier(data_dict['resource_id']),
+ columns=u', '.join(
+ [identifier(field)
+ for field in used_field_names]).replace('%', '%%'),
values=u', '.join(['%s::nested'
if field['type'] == 'nested' else '%s'
for field in used_fields]),
- primary_key=u','.join([u'"{0}"'.format(part)
- for part in unique_keys]),
- primary_value=u','.join(["%s"] * len(unique_keys))
+ primary_key=pk_sql.replace('%', '%%'),
+ primary_value=pk_values_sql,
)
try:
context['connection'].execute(
diff --git a/ckanext/datastore/logic/action.py b/ckanext/datastore/logic/action.py
--- a/ckanext/datastore/logic/action.py
+++ b/ckanext/datastore/logic/action.py
@@ -219,14 +219,14 @@ def datastore_upsert(context: Context, data_dict: dict[str, Any]):
*upsert*
Update if record with same key already exists, otherwise insert.
- Requires unique key.
+ Requires unique key or _id field.
*insert*
Insert only. This method is faster that upsert, but will fail if any
inserted record matches an existing one. Does *not* require a unique
key.
*update*
Update only. An exception will occur if the key that should be updated
- does not exist. Requires unique key.
+ does not exist. Requires unique key or _id field.
:param resource_id: resource id that the data is going to be stored under.
| diff --git a/ckanext/datastore/tests/test_upsert.py b/ckanext/datastore/tests/test_upsert.py
--- a/ckanext/datastore/tests/test_upsert.py
+++ b/ckanext/datastore/tests/test_upsert.py
@@ -552,6 +552,67 @@ def test_calculate_record_count(self):
last_analyze = when_was_last_analyze(resource["id"])
assert last_analyze is not None
+ @pytest.mark.ckan_config("ckan.plugins", "datastore")
+ @pytest.mark.usefixtures("clean_datastore", "with_plugins")
+ def test_no_pk_update(self):
+ resource = factories.Resource()
+ data = {
+ "resource_id": resource["id"],
+ "force": True,
+ "fields": [
+ {"id": "book", "type": "text"},
+ ],
+ "records": [{"book": u"El Niño"}],
+ }
+ helpers.call_action("datastore_create", **data)
+
+ data = {
+ "resource_id": resource["id"],
+ "force": True,
+ "method": "upsert",
+ "records": [
+ {"_id": "1", "book": u"The boy"}
+ ],
+ }
+ helpers.call_action("datastore_upsert", **data)
+
+ search_result = _search(resource["id"])
+ assert search_result["total"] == 1
+ assert search_result["records"][0]["book"] == "The boy"
+
+ @pytest.mark.ckan_config("ckan.plugins", "datastore")
+ @pytest.mark.usefixtures("clean_datastore", "with_plugins")
+ def test_id_instead_of_pk_update(self):
+ resource = factories.Resource()
+ data = {
+ "resource_id": resource["id"],
+ "force": True,
+ "primary_key": "pk",
+ "fields": [
+ {"id": "pk", "type": "text"},
+ {"id": "book", "type": "text"},
+ {"id": "author", "type": "text"},
+ ],
+ "records": [{"pk": "1000", "book": u"El Niño", "author": "Torres"}],
+ }
+ helpers.call_action("datastore_create", **data)
+
+ data = {
+ "resource_id": resource["id"],
+ "force": True,
+ "method": "upsert",
+ "records": [
+ {"_id": "1", "book": u"The boy", "author": u"F Torres"}
+ ],
+ }
+ helpers.call_action("datastore_upsert", **data)
+
+ search_result = _search(resource["id"])
+ assert search_result["total"] == 1
+ assert search_result["records"][0]["pk"] == "1000"
+ assert search_result["records"][0]["book"] == "The boy"
+ assert search_result["records"][0]["author"] == "F Torres"
+
@pytest.mark.usefixtures("with_request_context")
class TestDatastoreInsert(object):
@@ -829,3 +890,64 @@ def test_update_non_existing_field(self):
with pytest.raises(ValidationError) as context:
helpers.call_action("datastore_upsert", **data)
assert u'fields "dummy" do not exist' in str(context.value)
+
+ @pytest.mark.ckan_config("ckan.plugins", "datastore")
+ @pytest.mark.usefixtures("clean_datastore", "with_plugins")
+ def test_no_pk_update(self):
+ resource = factories.Resource()
+ data = {
+ "resource_id": resource["id"],
+ "force": True,
+ "fields": [
+ {"id": "book", "type": "text"},
+ ],
+ "records": [{"book": u"El Niño"}],
+ }
+ helpers.call_action("datastore_create", **data)
+
+ data = {
+ "resource_id": resource["id"],
+ "force": True,
+ "method": "update",
+ "records": [
+ {"_id": "1", "book": u"The boy"}
+ ],
+ }
+ helpers.call_action("datastore_upsert", **data)
+
+ search_result = _search(resource["id"])
+ assert search_result["total"] == 1
+ assert search_result["records"][0]["book"] == "The boy"
+
+ @pytest.mark.ckan_config("ckan.plugins", "datastore")
+ @pytest.mark.usefixtures("clean_datastore", "with_plugins")
+ def test_id_instead_of_pk_update(self):
+ resource = factories.Resource()
+ data = {
+ "resource_id": resource["id"],
+ "force": True,
+ "primary_key": "pk",
+ "fields": [
+ {"id": "pk", "type": "text"},
+ {"id": "book", "type": "text"},
+ {"id": "author", "type": "text"},
+ ],
+ "records": [{"pk": "1000", "book": u"El Niño", "author": "Torres"}],
+ }
+ helpers.call_action("datastore_create", **data)
+
+ data = {
+ "resource_id": resource["id"],
+ "force": True,
+ "method": "update",
+ "records": [
+ {"_id": "1", "book": u"The boy", "author": u"F Torres"}
+ ],
+ }
+ helpers.call_action("datastore_upsert", **data)
+
+ search_result = _search(resource["id"])
+ assert search_result["total"] == 1
+ assert search_result["records"][0]["pk"] == "1000"
+ assert search_result["records"][0]["book"] == "The boy"
+ assert search_result["records"][0]["author"] == "F Torres"
| Datastore upsert update not working with index _id
**CKAN version** 2.9.5
**Describe the bug**
A clear and concise description of what the bug is.
datastore/upsert method=update does not work with _id
**Steps to reproduce**
Steps to reproduce the behavior:
Create resource in datastore
insert values
read values => resulting records have unique field _id, as expected
update command with _id fails on "undefined primary_key"
{
"error": {
"__type": "Validation Error",
"table": [
"table does not have a unique key defined"
]
},
**Expected behavior**
A clear and concise description of what you expected to happen.
Record number _id can be used as primary key, as in regular SQL database
**Additional details**
If possible, please provide the full stack trace of the error raised, or add screenshots to help explain your problem.
Use case: update resource with timeseries data which by design do not come with an inherent primary key. So primary key must be database id. However, this cannot be enforced on datastore_create()
Maybe you consider this not a bug - but we have an id in the data, so not allowing to use it is quite close ...
| Hey, @digital-codes, I've tested this and it doesn't work as you think.
When using `datastore_create` action, you have `param: primary_key` this `primary_key` is optional.
When you set your `fields/columns` e.g like this: `"fields": [{"id": "name"}, {"id": "age"}, {"id": "email"} ]` and your records like: `"records": [ {"name": "Andreas", "age": 30, "email": "[email protected]"} ]` you can set `primary_key` to be your `"email"` this would be your `unique_key` in your `fields/columns`.
Then you can use `datastore_upsert` (lets say you want to update your name) like this:
curl -X POST http://localhost:5000/api/3/action/datastore_upsert -H "Authorization: your-key" -d '{"resource_id": "{resource.id}", "force": "True", "records": [{"name": "Kugel", "email": "[email protected]"}], "method": "update" }'.
If you don’t set your `primary_key` when creating, you cannot use `datastore_upsert` as all three methods require a `unique key`.
Thanks
I agree with the reporter. The `_id` field should be usable as a primary key for `datastore_upsert`. I'm happy to review a PR or help work on a fix for this issue.
Thanks for taking this issue. I'm not too familiar with CKAN internals nor Postgres, but if I'll try to help. I looked at backend/postgres.py and there is
```
elif method in [_UPDATE, _UPSERT]:
unique_keys = _get_unique_key(context, data_dict)
if len(unique_keys) < 1:
raise ValidationError({
'table': [u'table does not have a unique key defined']
})
```
which is probably giving the error. But I don't know why postgres doesn't accept the _id as a unique key.
I looked further and *create_table* goes like:
```
def create_table(context: Context, data_dict: dict[str, Any]):
...
datastore_fields = [
{'id': '_id', 'type': 'serial primary key'},
{'id': '_full_text', 'type': 'tsvector'},
]
```
Which seems to set _id as a primary key. Or is this a typo and it should be _primary_key_ instead of _primary_ and _key_ ?
Hmmm, maybe it's the way how the unique keys are looked up:
```
def _get_unique_key(context: Context, data_dict: dict[str, Any]) -> list[str]:
sql_get_unique_key = '''
SELECT
a.attname AS column_names
FROM
pg_class t,
pg_index idx,
pg_attribute a
WHERE
t.oid = idx.indrelid
AND a.attrelid = t.oid
AND a.attnum = ANY(idx.indkey)
AND t.relkind = 'r'
AND idx.indisunique = true
AND idx.indisprimary = false
AND t.relname = %s
'''
```
The line
AND idx.indisprimary = false
will probably exclude the _id ...
> The line AND idx.indisprimary = false will probably exclude the _id ...
Yep thats true
So how do we proceed? Do you consider it safe to just remove that line?
I don't have a running local installation, just access to a production system, so I can't really test the modification and create a PR. Can one of you do that?
Hey @wardi, I'd like to work on this issue, currently, I have a fix though might not seem the best solution, if you don't agree with this please give me some pointers.
Here is what I've done:
I removed this line: `AND idx.indisprimary = false` from `_get_unique_key()`
with that line removed, from now we will always receive the `_id` when calling `_get_unique_key()`
i will comment my changes with `# this line is added by me` so you will know what has been added
```python
for num, record in enumerate(records):
# remove the _id if not provided when calling update method
if '_id' in unique_keys and '_id' not in record: # this line is added by me
unique_keys.remove('_id') # this line is added by me
# all key columns have to be defined
missing_fields = [field for field in unique_keys
if field not in record]
if missing_fields:
raise ValidationError({
'key': [u'''fields "{fields}" are missing
but needed as key'''.format(
fields=', '.join(missing_fields))]
})
for field in fields:
value = record.get(field['id'])
if value is not None and field['type'].lower() == 'nested':
# a tuple with an empty second value
record[field['id']] = (json.dumps(value), '')
if "_id" in record: # this line is added by me
# _id is not a field_name so we need to append
field_names.append('_id') # this line is added by me
non_existing_filed_names = [field for field in record
if field not in field_names]
````
the original code you can find here https://github.com/ckan/ckan/blob/2e63e7fbaf7208f122e8c90a419f7c71485423b9/ckanext/datastore/backend/postgres.py#L1170
Thanks
@TomeCirun thanks, would you mind creating a pull request instead? | 2022-06-23T20:37:55 |
ckan/ckan | 6,953 | ckan__ckan-6953 | [
"6930"
] | df50c365351aafbf6c929abe999d45aa08751bcb | diff --git a/ckan/views/home.py b/ckan/views/home.py
--- a/ckan/views/home.py
+++ b/ckan/views/home.py
@@ -5,7 +5,7 @@
from urllib.parse import urlencode
from typing import Any, Optional, cast, List, Tuple
-from flask import Blueprint, abort, redirect, request
+from flask import Blueprint, make_response, abort, redirect, request
import ckan.model as model
import ckan.logic as logic
@@ -14,7 +14,7 @@
import ckan.lib.helpers as h
from ckan.common import g, config, current_user, _
-from ckan.types import Context
+from ckan.types import Context, Response
CACHE_PARAMETERS = [u'__cache', u'__no_cache__']
@@ -95,6 +95,13 @@ def about() -> str:
return base.render(u'home/about.html', extra_vars={})
+def robots_txt() -> Response:
+ '''display robots.txt'''
+ resp = make_response(base.render('home/robots.txt'))
+ resp.headers['Content-Type'] = "text/plain; charset=utf-8"
+ return resp
+
+
def redirect_locale(target_locale: str, path: Optional[str] = None) -> Any:
target = f'/{target_locale}/{path}' if path else f'/{target_locale}'
@@ -107,7 +114,8 @@ def redirect_locale(target_locale: str, path: Optional[str] = None) -> Any:
util_rules: List[Tuple[str, Any]] = [
(u'/', index),
- (u'/about', about)
+ (u'/about', about),
+ (u'/robots.txt', robots_txt)
]
for rule, view_func in util_rules:
home.add_url_rule(rule, view_func=view_func)
| Robots.txt can no longer be easily customised
**CKAN version**
2.9
**Describe the bug**
`robots.txt` was moved back to the `public` directory as part of #4801. However, this reverts the implementation of https://github.com/ckan/ideas-and-roadmap/issues/178 and makes it harder to customise the file (it can still be overridden with a different version, but not using Jinja syntax).
| In case it's relevant to anyone, serving `robots.txt` from the templates directory can be re-enabled with a blueprint rule similar to:
blueprint.add_url_rule(u'/robots.txt', 'robots', view_func=lambda: render('robots.txt'))
(Also, if the `robots.txt` file contains `{% ckan_extends %}`, that directive will need to be removed.)
yes very strange
routing removed here: https://github.com/ckan/ckan/commit/8ee21484d3ceb6c0f0d9eb8d239a3a97baf2e5ac
jinja template parts removed here: https://github.com/ckan/ckan/commit/4a05d5cd09ada5abde1dd74ae545679eef61aad8
@amercader was there a reason for serving robots.txt from the public directory instead of a view?
I can't remember about the reasoning behind this. I guess that reducing complexity by just having a single robots.txt file in the public folder that users can override from their extension.
But it seems like the old implementation gave more flexibility so happy to revert it. This should be easy to put back following the commits that @duttonw linked to. | 2022-07-02T14:26:57 |
|
ckan/ckan | 6,954 | ckan__ckan-6954 | [
"6948"
] | 5efeb6cd0acf8421ffa113a6c00e71976da84dd5 | diff --git a/ckan/config/middleware/flask_app.py b/ckan/config/middleware/flask_app.py
--- a/ckan/config/middleware/flask_app.py
+++ b/ckan/config/middleware/flask_app.py
@@ -10,7 +10,7 @@
import logging
from logging.handlers import SMTPHandler
-from typing import Any, Iterable, Optional, Union, cast
+from typing import Any, Iterable, Optional, Union, cast, Dict
from flask import Blueprint, send_from_directory
from flask.ctx import _AppCtxGlobals
@@ -126,6 +126,29 @@ def _ungettext_alias():
return dict(ungettext=ungettext)
+class BeakerSessionInterface(SessionInterface):
+ def open_session(self, app: Any, request: Any):
+ if 'beaker.session' in request.environ:
+ return request.environ['beaker.session']
+
+ def save_session(self, app: Any, session: Any, response: Any):
+ session.save()
+
+ def is_null_session(self, obj: Dict[str, Any]) -> bool:
+
+ is_null = super(BeakerSessionInterface, self).is_null_session(obj)
+
+ if not is_null:
+ # Beaker always adds these keys on each request, so if these are
+ # the only keys present we assume it's an empty session
+ is_null = (
+ sorted(obj.keys()) == [
+ "_accessed_time", "_creation_time", "_domain", "_path"]
+ )
+
+ return is_null
+
+
def make_flask_stack(conf: Union[Config, CKANConfig]) -> CKANApp:
""" This has to pass the flask app through all the same middleware that
Pylons used """
@@ -200,15 +223,6 @@ def make_flask_stack(conf: Union[Config, CKANConfig]) -> CKANApp:
from werkzeug.debug import DebuggedApplication
app.wsgi_app = DebuggedApplication(app.wsgi_app, True)
- # Use Beaker as the Flask session interface
- class BeakerSessionInterface(SessionInterface):
- def open_session(self, app: Any, request: Any):
- if 'beaker.session' in request.environ:
- return request.environ['beaker.session']
-
- def save_session(self, app: Any, session: Any, response: Any):
- session.save()
-
namespace = 'beaker.session.'
session_opts = {k.replace('beaker.', ''): v
for k, v in config.items()
| diff --git a/ckan/tests/config/test_middleware.py b/ckan/tests/config/test_middleware.py
--- a/ckan/tests/config/test_middleware.py
+++ b/ckan/tests/config/test_middleware.py
@@ -1,8 +1,9 @@
# encoding: utf-8
import pytest
-import six
+from unittest import mock
from flask import Blueprint
+from ckan.config.middleware.flask_app import BeakerSessionInterface
import ckan.plugins as p
from ckan.common import config, _
@@ -53,7 +54,7 @@ def test_flask_core_route_is_served(patched_app):
assert res.status_code == 200
res = patched_app.get(u"/flask_core")
- assert six.ensure_text(res.data) == u"This was served from Flask"
+ assert res.get_data(as_text=True) == "This was served from Flask"
@pytest.mark.ckan_config(u"SECRET_KEY", u"super_secret_stuff")
@@ -75,3 +76,20 @@ def test_no_beaker_secret_crashes(make_app):
# RuntimeError instead (thrown on `make_flask_stack`)
with pytest.raises(RuntimeError):
make_app()
+
+
+def test_no_session_stored_by_default(app, monkeypatch, test_request_context):
+
+ save_session_mock = mock.Mock()
+
+ class CustomBeakerSessionInterface(BeakerSessionInterface):
+
+ save_session = save_session_mock
+
+ monkeypatch.setattr(
+ app.flask_app, 'session_interface', CustomBeakerSessionInterface())
+
+ with test_request_context():
+ app.get("/")
+
+ save_session_mock.assert_not_called()
| Unsustainable Beaker cache growth on CKAN 2.9
**CKAN version**
2.9 (tested on 2.9.0 and 2.9.5)
Does not occur on 2.8.8.
**Describe the bug**
Beaker session cache files are created on every unauthenticated request to non-API URLs. This did not occur under CKAN 2.8.
**Steps to reproduce**
* Create a CKAN 2.9 instance on a Linux system.
* Check total inode usage with `df -i`
* Send a request to /dataset, eg `curl http://my-site/dataset/`
* Check total inode usage again and confirm that it has risen by 2.
* Check the session files in `/tmp/*/sessions` to confirm that two new files have been created, `find /tmp/*/sessions -type f -cmin -5`
**Expected behavior**
Unauthenticated requests should not create Beaker session files, as per CKAN 2.8 behaviour.
**Additional details**
This can easily lead to hundreds of thousands of files being created per day, rapidly reaching the inode limit of the hard disk. It could also be deliberately exploited as a Denial of Service attack.
| Further testing shows that CKAN 2.8 does create session files for requests that go to Flask, such as `/user` or `/ckan-admin`
We're looking at resolving this on our own system by using Redis as our Beaker storage backend, with a suitable session expiry.
beaker.session.timeout = 3600
beaker.session.type = ext:redis
beaker.session.url = <same as ckan.redis.url>
something from https://github.com/ckan/ckan/issues/3196
and looking at
https://flask-session.readthedocs.io/en/latest/#quickstart
it seems a 'session' is created on each request and anon is for the single request and thrown. Since flask session has beaker backing it, it still creates a file, from what i can see, ckan could be tweaked to give anon a cookie/session that sticks around and reduces this.
I think for @ThrawnCA problem, with the 2.8.x to 2.9.x upgrade, search engines are now doing a massive re-crawl and generating heaps of hits and doing active probing compared to the usual passive (check if page changed etc)
Found the culprit!
Here's the step by step rundown:
* At the end of each request, Flask checks if there is something in the session, and if so, saves it (in our case this means that Beaker will store a session file):
https://github.com/pallets/flask/blob/0305d31cb8c62b26c1e073995114963c88ca962e/src/flask/app.py#L1887-L1888
* We would assume that in an anonymous request where nothing has been stored in the session, calling `self.session_interface.is_null_session(ctx.session)` would return True, but that is not the case. If we inspect the session we see it contains data:
```
{'_accessed_time': 1656666227.368082, '_creation_time': 1656666227.368082}
```
* These entries are _always_ added by Beaker when initializing the session class:
https://github.com/bbangert/beaker/blob/d4ab7d37387feddd0d544792d9e32533e39ff868/beaker/session.py#L222-L224
* The cleanest approach I can think of is to override the `is_null_session()` method in our custom `SessionInterface` class to take this into account:
```diff
diff --git a/ckan/config/middleware/flask_app.py b/ckan/config/middleware/flask_app.py
index eb9ff8155..ef6b8b63e 100644
--- a/ckan/config/middleware/flask_app.py
+++ b/ckan/config/middleware/flask_app.py
@@ -174,6 +174,17 @@ def make_flask_stack(conf):
def save_session(self, app, session, response):
session.save()
+ def is_null_session(self, obj):
+
+ is_null = super(BeakerSessionInterface, self).is_null_session(obj)
+
+ if not is_null:
+ # Beaker always adds these keys on each request, so if these are
+ # the only keys present we assume it's an empty session
+ is_null = sorted(obj.keys()) == ["_accessed_time", "_creation_time"]
+
+ return is_null
+
namespace = 'beaker.session.'
session_opts = {k.replace('beaker.', ''): v
for k, v in six.iteritems(config)
```
This was already happening on CKAN 2.8 but because there weren't many Flask-based endpoints the issue was not made apparent. On CKAN 2.9 where everything goes trough Flask the sesssions were being stored in every single request. We definitely need to backport this. I'll send a PR
Good trouble shooting. Sounds like an easy fix 😊 | 2022-07-04T10:27:01 |
ckan/ckan | 6,958 | ckan__ckan-6958 | [
"6957"
] | 5efeb6cd0acf8421ffa113a6c00e71976da84dd5 | diff --git a/doc/conf.py b/doc/conf.py
--- a/doc/conf.py
+++ b/doc/conf.py
@@ -355,7 +355,7 @@ def write_substitutions_file(**kwargs):
latest_release_tag_value = get_latest_release_tag()
latest_release_version = get_latest_release_version()
latest_minor_version = latest_release_version[:latest_release_version.find(".", 3)]
-is_master = release.endswith('a')
+is_master = "a" in release.split(".")[-1]
is_supported = get_status_of_this_version() == 'supported'
is_latest_version = version == latest_release_version
| Incorrect disclaimer displayed in latest docs
It's showing this:

When it should be showing this:

| 2022-07-05T09:49:30 |
||
ckan/ckan | 6,961 | ckan__ckan-6961 | [
"6172"
] | 5fd2a072242d03ddc1411569088b1f93c65a8d98 | diff --git a/ckanext/datastore/backend/postgres.py b/ckanext/datastore/backend/postgres.py
--- a/ckanext/datastore/backend/postgres.py
+++ b/ckanext/datastore/backend/postgres.py
@@ -1901,6 +1901,8 @@ def datastore_search(
elif fields and fts_q:
field_ids = datastore_helpers.get_list(fields)
all_field_ids = list(fields_types.keys())
+ if "rank" not in fields:
+ all_field_ids.remove("rank")
field_intersect = [x for x in field_ids
if x not in all_field_ids]
field_ids = all_field_ids + field_intersect
| diff --git a/ckanext/datastore/tests/test_search.py b/ckanext/datastore/tests/test_search.py
--- a/ckanext/datastore/tests/test_search.py
+++ b/ckanext/datastore/tests/test_search.py
@@ -2089,10 +2089,8 @@ def test_fts_on_field_calculates_ranks_specific_field_and_all_fields(self):
}
result = helpers.call_action("datastore_search", **search_data)
ranks_from = [r["rank from"] for r in result["records"]]
- ranks = [r["rank"] for r in result["records"]]
assert len(result["records"]) == 2
assert len(set(ranks_from)) == 1
- assert len(set(ranks)) == 2
@pytest.mark.ckan_config("ckan.plugins", "datastore")
@pytest.mark.usefixtures("clean_datastore", "with_plugins")
| datastore_search full_text and fields parameters not processed properly
**CKAN version**
master
**Describe the bug**
When the new `full_text` parameter is used along with the `fields` parameter, `datastore_search` always returns the entire record, along with the "hidden" rank column (used for relevance in fts search)
**Steps to reproduce**
Use `datastore_search` `full_text` and `fields` in the same call.
**Expected behavior**
`datastore_search` will process `fields` properly when `full_text` is specified, and the hidden rank value should not be returned.
| @jqnatividad , I am interested to work on this issue. At present I am trying to reproduce this issue but unable to reproduce it. Can you please tell how to use **datastore_search full_text** and **fields** in the same call?
Hi @jqnatividad , I would like to work on this issue.
Hi @jqnatividad , I'm unable to reproduce the issue.
I also checked the API documentation for [datastore_search](https://docs.ckan.org/en/2.9/maintaining/datastore.html#ckanext.datastore.logic.action.datastore_search), but there is no reference for `full_text` in it.
Hi @jqnatividad , I'm able to reproduce the issue. Are we trying to remove the `rank` column from the records response when we hit the API, i.e. from `'records': [{'_id': 2, 'a': 2, 'b': 'zzz', 'rank': 0.057308756}]. Please confirm my understanding.
| 2022-07-06T08:27:42 |
ckan/ckan | 6,973 | ckan__ckan-6973 | [
"2628"
] | 0a596b8394dbf9582902853ad91450d2c0d7959b | diff --git a/ckan/logic/action/get.py b/ckan/logic/action/get.py
--- a/ckan/logic/action/get.py
+++ b/ckan/logic/action/get.py
@@ -2723,14 +2723,20 @@ def am_following_group(context: Context,
def _followee_count(
context: Context, data_dict: DataDict,
- FollowerClass: Type['ModelFollowingModel[Any ,Any]']) -> int:
+ FollowerClass: Type['ModelFollowingModel[Any ,Any]'],
+ is_org: bool = False
+ ) -> int:
if not context.get('skip_validation'):
schema = context.get('schema',
ckan.logic.schema.default_follow_user_schema())
data_dict, errors = _validate(data_dict, schema, context)
if errors:
raise ValidationError(errors)
- return FollowerClass.followee_count(data_dict['id'])
+
+ followees = _group_or_org_followee_list(context, data_dict, is_org)
+
+ return len(followees)
+
def followee_count(context: Context,
@@ -2807,8 +2813,24 @@ def group_followee_count(
'''
return _followee_count(
context, data_dict,
- context['model'].UserFollowingGroup)
+ context['model'].UserFollowingGroup,
+ is_org = False)
+def organization_followee_count(
+ context: Context,
+ data_dict: DataDict) -> ActionResult.OrganizationFolloweeCount:
+ '''Return the number of organizations that are followed by the given user.
+
+ :param id: the id of the user
+ :type id: string
+
+ :rtype: int
+
+ '''
+ return _followee_count(
+ context, data_dict,
+ context['model'].UserFollowingGroup,
+ is_org = True)
@logic.validate(ckan.logic.schema.default_follow_user_schema)
def followee_list(
diff --git a/ckan/model/follower.py b/ckan/model/follower.py
--- a/ckan/model/follower.py
+++ b/ckan/model/follower.py
@@ -106,7 +106,8 @@ def _get_followers(
@classmethod
def _get(
- cls, follower_id: Optional[str] = None,
+ cls,
+ follower_id: Optional[str] = None,
object_id: Optional[str] = None
) -> Query[tuple[Self, Follower, Followed]]:
follower_alias = sqlalchemy.orm.aliased(cls._follower_class())
diff --git a/ckan/types/logic/action_result.py b/ckan/types/logic/action_result.py
--- a/ckan/types/logic/action_result.py
+++ b/ckan/types/logic/action_result.py
@@ -64,6 +64,7 @@
UserFolloweeCount = int
DatasetFolloweeCount = int
GroupFolloweeCount = int
+OrganizationFolloweeCount = int
FolloweeList = List[AnyDict]
UserFolloweeList = List[AnyDict]
DatasetFolloweeList = List[AnyDict]
| diff --git a/ckan/tests/logic/action/test_get.py b/ckan/tests/logic/action/test_get.py
--- a/ckan/tests/logic/action/test_get.py
+++ b/ckan/tests/logic/action/test_get.py
@@ -2877,6 +2877,30 @@ def test_followee_list_with_q(self):
assert len(followee_list) == 1
assert followee_list[0]["display_name"] == "Environment"
+ def test_followee_count_for_org_or_group(self):
+ group = factories.Group(title="Finance")
+ group2 = factories.Group(title="Environment")
+ org = factories.Organization(title="Acme")
+
+ user = factories.User()
+
+ context = {"user": user["name"]}
+
+ helpers.call_action("follow_group", context, id=group["id"])
+ helpers.call_action("follow_group", context, id=group2["id"])
+ helpers.call_action("follow_group", context, id=org["id"])
+
+ group_followee_count = helpers.call_action(
+ "group_followee_count", context, id=user["name"]
+ )
+
+ organization_followee_count = helpers.call_action(
+ "organization_followee_count", context, id=user["name"]
+ )
+
+ assert group_followee_count == 2
+ assert organization_followee_count == 1
+
class TestStatusShow(object):
@pytest.mark.ckan_config("ckan.plugins", "stats")
diff --git a/ckan/tests/test_coding_standards.py b/ckan/tests/test_coding_standards.py
--- a/ckan/tests/test_coding_standards.py
+++ b/ckan/tests/test_coding_standards.py
@@ -319,6 +319,7 @@ class TestActionAuth(object):
"get: dataset_follower_count",
"get: followee_count",
"get: group_followee_count",
+ "get: organization_followee_count",
"get: group_follower_count",
"get: group_package_show",
"get: member_list",
| group_followee_count returns incorrect amount
The function `logic.action.get.group_followee_count` returns the amount of groups **and** organization the user follows. This is incorrect because according to the documentation (and function name) it should **only** return organisations.
This is because organisations are also groups and the function `logic.action.get._followee_count` doesn't filter the groups like `logic.action.get.group_followee_list` and `logic.action.get.organization_followee_list` do.
| Do you want to submit a quick PR @trickvi ? Seems pretty easy to fix
I'll fix
Made [PR](https://github.com/ckan/ckan/pull/3458)
The associated PR looks okay, but needs tests. | 2022-07-14T21:52:38 |
ckan/ckan | 6,978 | ckan__ckan-6978 | [
"6004"
] | 0a596b8394dbf9582902853ad91450d2c0d7959b | diff --git a/ckan/logic/action/update.py b/ckan/logic/action/update.py
--- a/ckan/logic/action/update.py
+++ b/ckan/logic/action/update.py
@@ -652,7 +652,12 @@ def _group_or_org_update(
raise NotFound('Group was not found.')
context["group"] = group
- data_dict['type'] = group.type
+ data_dict_type = data_dict.get('type')
+ if data_dict_type is None:
+ data_dict['type'] = group.type
+ else:
+ if data_dict_type != group.type:
+ raise ValidationError({"message": "Type cannot be updated"})
# get the schema
group_plugin = lib_plugins.lookup_group_plugin(group.type)
| diff --git a/ckan/tests/logic/action/test_update.py b/ckan/tests/logic/action/test_update.py
--- a/ckan/tests/logic/action/test_update.py
+++ b/ckan/tests/logic/action/test_update.py
@@ -379,19 +379,14 @@ def test_update_organization_cant_change_type(self):
context = {"user": user["name"]}
org = factories.Organization(type="organization", user=user)
- org = helpers.call_action(
- "organization_update",
- context=context,
- id=org["id"],
- name=org["name"],
- type="ragtagband",
- )
-
- assert org["type"] == "organization"
- assert (
- helpers.call_action("organization_show", id=org["name"])["type"]
- == "organization"
- )
+ with pytest.raises(logic.ValidationError):
+ helpers.call_action(
+ "organization_update",
+ context=context,
+ id=org["id"],
+ name=org["name"],
+ type="ragtagband",
+ )
@pytest.mark.usefixtures("non_clean_db")
@@ -1472,19 +1467,14 @@ def test_group_update_cant_change_type(self):
context = {"user": user["name"]}
group = factories.Group(type="group", user=user)
- group = helpers.call_action(
- "group_update",
- context=context,
- name=group["name"],
- id=group["id"],
- type="favouritecolour",
- )
-
- assert group["type"] == "group"
- assert (
- helpers.call_action("group_show", id=group["name"])["type"]
- == "group"
- )
+ with pytest.raises(logic.ValidationError):
+ helpers.call_action(
+ "group_update",
+ context=context,
+ name=group["name"],
+ id=group["id"],
+ type="favouritecolour",
+ )
@pytest.mark.usefixtures("non_clean_db")
| Can't change group type with organization/group update/patch operations
## CKAN version
CKAN 2.8, CKAN 2.9
## Describe the bug
I recently wanted to change the type of an organisation on a CKAN instance via the API. I made an API call like this:
```
curl -X POST http://my-ckan-server.com/api/3/action/organization_patch -H "Authorization: <my-api-key>" -H "Content-Type: application/json" -H "Accept: application/json" --data '{"id": "<org-id>", "type": "new-type"}'
```
This returned a response:
```
200 OK
{
"success": true,
"result": {
...
"type": "old-type",
}
}
```
and did not update the type field.
This happens because the `type` field in the request body is ignored here:
https://github.com/ckan/ckan/blob/170556a97f38d42b94474943ccab4cef19fd9d49/ckan/logic/action/update.py#L645
It would be useful if it were possible to change the group type using the API for appropriately authorized users.
If it is impossible to do this by design, it would be much clearer what is going on if this request failed with a response like:
```
400 Bad Request
{
"success": false,
"error": {
"message": "type can't be updated via the API",
}
}
```
instead of reporting success but not making the change.
## Steps to reproduce
Steps to reproduce the behavior:
```
curl -X POST http://my-ckan-server.com/api/3/action/organization_patch -H "Authorization: <my-api-key>" -H "Content-Type: application/json" -H "Accept: application/json" --data '{"id": "<org-id>", "type": "new-type"}'
```
## Expected behavior
Either the object should be updated, or a useful error response should be returned
| Summary from our discussion in the dev meeting:
* If not allowed and the field value is always overridden the API call should fail with an error as suggested
* We could allow type changes on orgs/groups and datasets but:
* we need to ensure that the schema for the new type is used for validation
* it's up to the user to provide a data_dict that passes validation according to the new schema
* We need to check the effect of a `organization` -> `group` change
> Summary from our discussion in the dev meeting:
>
> * If not allowed and the field value is always overridden the API call should fail with an error as suggested
>
> * We could allow type changes on orgs/groups and datasets but:
>
> * we need to ensure that the schema for the new type is used for validation
> * it's up to the user to provide a data_dict that passes validation according to the new schema
>
> * We need to check the effect of a `organization` -> `group` change
Hi @amercader , I agree with your first suggestion. I've create a error response when the `type` is different by replacing
`data_dict['type'] = group.type` with:
```
if data_dict['type'] != group.type:
raise ValidationError({"message": "type cannot be updated via API"})
```
The response is as below when the request is made for the type change:
```
{
"help": "http://127.0.0.1:5000/api/3/action/help_show?name=organization_patch",
"error": {
"message": "type cannot be updated via API",
"__type": "Validation Error"
},
"success": false
}
```
But getting the following errors when running the test cases:
```
def _group_or_org_update(
context: Context, data_dict: DataDict, is_org: bool = False):
model = context['model']
session = context['session']
id = _get_or_bust(data_dict, 'id')
group = model.Group.get(id)
if group is None:
raise NotFound('Group was not found.')
context["group"] = group
print(group.type)
# print(data_dict['type'])
# data_dict['type'] = group.type
# print(group.type)
if data_dict['type'] != group.type:
> raise ValidationError({"message": "type cannot be updated via API"})
E ckan.logic.ValidationError: None - {'message': 'type cannot be updated via API'}
ckan/logic/action/update.py:663: ValidationError
----------------------------- Captured stdout call -----------------------------
2022-07-15 14:09:46,992 CRITI [ckan.lib.uploader] Please specify a ckan.storage_path in your config
for your uploads
2022-07-15 14:09:47,046 CRITI [ckan.lib.uploader] Please specify a ckan.storage_path in your config
for your uploads
organization
------------------------------ Captured log call -------------------------------
CRITICAL ckan.lib.uploader:uploader.py:85 Please specify a ckan.storage_path in your config
for your uploads
CRITICAL ckan.lib.uploader:uploader.py:85 Please specify a ckan.storage_path in your config
for your uploads
______________ TestGroupUpdate.test_group_update_cant_change_type ______________
self = <ckan.tests.logic.action.test_update.TestGroupUpdate object at 0x7f829b11e6a0>
def test_group_update_cant_change_type(self):
user = factories.User()
context = {"user": user["name"]}
group = factories.Group(type="group", user=user)
> group = helpers.call_action(
"group_update",
context=context,
name=group["name"],
id=group["id"],
type="favouritecolour",
)
ckan/tests/logic/action/test_update.py:1475:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
ckan/tests/helpers.py:128: in call_action
return logic.get_action(action_name)(context, kwargs)
ckan/logic/__init__.py:527: in wrapped
result = _action(context, data_dict, **kw)
ckan/logic/action/update.py:753: in group_update
return _group_or_org_update(context, data_dict)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
context = {'__auth_audit': [('group_update', 140198910762576)], 'group': <Group group-wefg-7245-ecux>, 'ignore_auth': True, 'model': <module 'ckan.model' from '/usr/lib/ckan/master/src/ckan/ckan/model/__init__.py'>, ...}
data_dict = {'id': 'e8b83f50-38c0-4c6a-8758-2328b12ea669', 'name': 'group-wefg-7245-ecux', 'type': 'favouritecolour'}
is_org = False
def _group_or_org_update(
context: Context, data_dict: DataDict, is_org: bool = False):
model = context['model']
session = context['session']
id = _get_or_bust(data_dict, 'id')
group = model.Group.get(id)
if group is None:
raise NotFound('Group was not found.')
context["group"] = group
print(group.type)
# print(data_dict['type'])
# data_dict['type'] = group.type
# print(group.type)
if data_dict['type'] != group.type:
> raise ValidationError({"message": "type cannot be updated via API"})
E ckan.logic.ValidationError: None - {'message': 'type cannot be updated via API'}
ckan/logic/action/update.py:663: ValidationError
```
Please let me know if my approach is correct or I should take a different approach for this problem:
Thanks. | 2022-07-20T12:23:23 |
ckan/ckan | 6,989 | ckan__ckan-6989 | [
"6795"
] | ed155dca25265562e1a9125ee6917b832d514b10 | diff --git a/ckan/views/dataset.py b/ckan/views/dataset.py
--- a/ckan/views/dataset.py
+++ b/ckan/views/dataset.py
@@ -446,7 +446,10 @@ def read(package_type: str, id: str) -> Union[Response, str]:
pkg_dict = get_action(u'package_show')(context, data_dict)
pkg = context[u'package']
except (NotFound, NotAuthorized):
- return base.abort(404, _(u'Dataset not found'))
+ return base.abort(
+ 404,
+ _(u'Dataset not found or you have no permission to view it')
+ )
g.pkg_dict = pkg_dict
g.pkg = pkg
| Overwriting package_show auth function raises dataset not found
**CKAN version**
2.9.3
**Describe the bug**
Overwriting the package_show auth function in an extension produces dataset not found error for anonymous users when they attempt to access a package's webpage. This occurs both with code to limit access to remove access restrictions. Other auth overwrites seem to work as expected.
If the user is logged in, access is granted.
**Steps to reproduce**
1. Create an extension with a function that overwrites the package_show function with a custom one (such as the one included in the code below).
2. in the extension, overwrite the `get_auth_functions()` as below
```
# outside plugin class
def package_show(context, data_dict):
return {'success': True}
# Inside the plugin class
def get_auth_functions(self):
return {
"package_show": package_show
}
```
3. install extension
4. make sure you are logged out
5. attempt to open a dataset's webpage
**Expected behavior**
Users should be able to access package pages regardless of permissions. Alternatively, if access is restricted, the package_show function should return custom error message or redirect.
**Additional details**
ERROR [ckan.config.middleware.flask_app] 404 Not Found: Dataset not found
Traceback (most recent call last):
File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/flask/app.py", line 1949, in full_dispatch_request
rv = self.dispatch_request()
File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/flask/app.py", line 1935, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/usr/lib/ckan/venv/src/ckan/ckan/views/dataset.py", line 438, in read
return base.abort(404, _(u'Dataset not found'))
File "/usr/lib/ckan/venv/src/ckan/ckan/lib/base.py", line 66, in abort
flask_abort(status_code, detail)
File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/werkzeug/exceptions.py", line 774, in abort
return _aborter(status, *args, **kwargs)
File "/usr/lib/ckan/venv/local/lib/python2.7/site-packages/werkzeug/exceptions.py", line 755, in __call__
raise self.mapping[code](*args, **kwargs)
| This happens because, by default all auth function in `ckan/logic/auth/get` has an attribute `auth_allow_anonymous_access`.
https://github.com/ckan/ckan/blob/2e63e7fbaf7208f122e8c90a419f7c71485423b9/ckan/authz.py#L84-L95
If you track down your `auth_function` you will see it will fail here:
https://github.com/ckan/ckan/blob/2e63e7fbaf7208f122e8c90a419f7c71485423b9/ckan/authz.py#L233
to avoid this you can use decorator on your auth_func:
```
import ckan.plugins as p
@p.toolkit.auth_allow_anonymous_access
def package_show()
```
If you would call the api directly, it would so the reason for failure which in this case is that it requires authenticated user. The UI shows 404 Not found for both non-existing datasets and those where user does not have permission due to security reasons.
Thank you for clarifying about the decorator and for the explanation about why it occurs. Using the decorator prevents the error when overwriting the function to allow access to packages.
Is there anyway to customize the error message thrown when access is not allowed for security reasons? There are some cases where I would like to have custom code to restrict access to packages; however, "dataset not found" might lead some end users to think that there's an error with the site's ability to serve the package instead of realizing that they need to log in (or have elevated permissions) to view it.
Take this as an example (in my actual implementation there would be more if statements but for replication purposes I'm keeping it simple)
```
# I tried putting the p.toolkit.auth_disallow_anonymous_access decorator here, to no effect. Would I need to allow anonymous
# access with a decorator first and then later restrict it?
def package_show(context, data_dict):
if context.get("auth_user_obj") is not None:
return {"success": True}
return {"success": False, "message": "You must be signed in to view this page"}
```
> s there anyway to customize the error message thrown when access is not allowed for security reasons?
You can change the core code in your project.
Instead of this:
https://github.com/ckan/ckan/blob/2e63e7fbaf7208f122e8c90a419f7c71485423b9/ckan/views/dataset.py#L447-L451
you can change to this:

and you would get the proper message
<img width="493" alt="image" src="https://user-images.githubusercontent.com/72216462/162228643-2bd87787-53e4-4b01-8bc5-b4d224291707.png">
Currently it's not possible to customize the error messages except by changing the localizations. One improvement for this could be that instead of "Dataset not found" the error message would "Dataset not found or you've no permission to view it"
Thank you for the help, the provided code addresses my immediate need. Additionally, something like the error message @Zharktas wrote might have preempted the user feedback that preceded my attempt to change the error message.
@jannettim @Zharktas , I am interested to work on this issue. | 2022-07-28T12:22:04 |
|
ckan/ckan | 6,991 | ckan__ckan-6991 | [
"6987"
] | 34401f000846aa59559c77e755e56656cf1355f9 | diff --git a/ckan/config/middleware/flask_app.py b/ckan/config/middleware/flask_app.py
--- a/ckan/config/middleware/flask_app.py
+++ b/ckan/config/middleware/flask_app.py
@@ -31,7 +31,7 @@
from beaker.middleware import SessionMiddleware
from flask_login import LoginManager
from flask_wtf.csrf import CSRFProtect
-from ckan.common import CKANConfig, asbool, session
+from ckan.common import CKANConfig, asbool, session, current_user
import ckan.model as model
from ckan.lib import base
@@ -39,7 +39,7 @@
from ckan.lib import jinja_extensions
from ckan.lib import uploader
from ckan.lib import i18n
-from ckan.common import config, g, request, ungettext, current_user, _
+from ckan.common import config, g, request, ungettext
from ckan.config.middleware.common_middleware import (TrackingMiddleware,
HostHeaderMiddleware,
RootPathMiddleware)
@@ -551,41 +551,20 @@ def error_handler(e: Exception) -> Union[
]:
debug = config.get_value('debug')
if isinstance(e, HTTPException):
- # If the current_user.is_anonymous and the
- # Exception code is 401(Unauthorized)/403(Forbidden)
- # redirect the users to login page before trying to access it again
- # If you want to raise a 401 or 403 error instead,
- # set this setting to `False`
- if config.get_value('ckan.redirect_to_login_if_not_authorized'):
- # if the url is not local we dont want to redirect the user
- # instead, we want to show the actual 403(Forbidden)...
- # same for user.perform_reset if the current_user.is_deleted()
- # the view returns 403 hence we want to show the exception.
- endpoints = tuple(
- ['util.internal_redirect', 'user.perform_reset']
- )
- if request.endpoint not in endpoints:
- if current_user.is_anonymous and type(e) in (
- Unauthorized, Forbidden
- ):
- login_url = h.url_for('user.login', qualified=True)
- next_url = request.url
- redirect_url = h.make_login_url(
- login_url, next_url=next_url
- )
- h.flash_error(_('Please log in to access this page.'))
- return h.redirect_to(redirect_url)
-
if debug:
log.debug(e, exc_info=sys.exc_info) # type: ignore
else:
log.info(e)
+
+ show_login_redirect_link = current_user.is_anonymous and type(
+ e
+ ) in (Unauthorized, Forbidden)
extra_vars = {
u'code': e.code,
u'content': e.description,
- u'name': e.name
+ u'name': e.name,
+ u'show_login_redirect_link': show_login_redirect_link
}
-
return base.render(
u'error_document_template.html', extra_vars), e.code
| diff --git a/ckan/tests/controllers/test_admin.py b/ckan/tests/controllers/test_admin.py
--- a/ckan/tests/controllers/test_admin.py
+++ b/ckan/tests/controllers/test_admin.py
@@ -43,9 +43,7 @@ def test_index(app, user_env, sysadmin_env):
url = url_for("admin.index")
# Anonymous User
- response = app.get(url, status=302, follow_redirects=False)
- # Anonymous users are redirected to login page
- assert "user/login?next=%2Fckan-admin%2F" in response
+ response = app.get(url, status=403)
# Normal User
response = app.get(url, extra_environ=user_env, status=403)
@@ -233,10 +231,8 @@ class TestTrashView(object):
def test_trash_view_anon_user(self, app):
"""An anon user shouldn't be able to access trash view."""
trash_url = url_for("admin.trash")
- trash_response = app.get(trash_url, follow_redirects=False)
-
- # Anonymous users are redirected to login page
- assert "user/login?next=%2Fckan-admin%2Ftrash" in trash_response
+ trash_response = app.get(trash_url)
+ assert trash_response.status_code == 403
def test_trash_view_normal_user(self, app, user_env):
"""A normal logged in user shouldn't be able to access trash view."""
diff --git a/ckan/tests/controllers/test_group.py b/ckan/tests/controllers/test_group.py
--- a/ckan/tests/controllers/test_group.py
+++ b/ckan/tests/controllers/test_group.py
@@ -18,10 +18,7 @@ def test_bulk_process_throws_403_for_nonexistent_org(self, app):
bulk_process_url = url_for(
"organization.bulk_process", id="does-not-exist"
)
- res = app.get(url=bulk_process_url, status=302, follow_redirects=False)
- # Anonymous users are redirected to login page
- redirect_url = "user/login?next=%2Forganization%2Fbulk_process%2Fdoes-not-exist"
- assert redirect_url in res
+ app.get(url=bulk_process_url, status=403)
def test_page_thru_list_of_orgs_preserves_sort_order(self, app):
orgs = sorted([factories.Organization() for _ in range(35)],
@@ -77,9 +74,7 @@ def user():
@pytest.mark.usefixtures("clean_db", "with_request_context")
class TestGroupControllerNew(object):
def test_not_logged_in(self, app):
- res = app.get(url=url_for("group.new"), status=302, follow_redirects=False)
- # Anonymous users are redirected to login page
- assert "user/login?next=%2Fgroup%2Fnew" in res
+ app.get(url=url_for("group.new"), status=403)
def test_name_required(self, app, user):
env = {"Authorization": user["token"]}
@@ -140,9 +135,7 @@ def test_form_with_initial_data(self, app, user):
@pytest.mark.usefixtures("non_clean_db", "with_request_context")
class TestGroupControllerEdit(object):
def test_not_logged_in(self, app):
- res = app.get(url=url_for("group.new"), status=302, follow_redirects=False)
- # Anonymous users are redirected to login page
- assert "user/login?next=%2Fgroup%2Fnew" in res
+ app.get(url=url_for("group.new"), status=403)
def test_group_doesnt_exist(self, app, user):
env = {"Authorization": user["token"]}
@@ -301,13 +294,10 @@ def test_non_authorized_user_trying_to_delete_fails(
def test_anon_user_trying_to_delete_fails(self, app):
group = factories.Group()
- res = app.get(
+ app.get(
url=url_for("group.delete", id=group["id"]),
- status=302,
- follow_redirects=False
+ status=403,
)
- # Anonymous users are redirected to login page
- assert "user/login?next=%2Fgroup%2Fdelete%2F" in res
group = helpers.call_action(
"group_show", id=group["id"]
@@ -531,11 +521,9 @@ def test_anonymous_users_cannot_add_members(self, app):
with app.flask_app.test_request_context():
url = url_for("group.member_new", id=group["id"])
- res = app.get(url, status=302, follow_redirects=False)
- # Anonymous users are redirected to login page
- assert "user/login?next=%2Fgroup%2Fmember_new%2F" in res
+ app.get(url, status=403)
- res = app.post(
+ app.post(
url,
data={
"id": "test",
@@ -543,11 +531,8 @@ def test_anonymous_users_cannot_add_members(self, app):
"save": "save",
"role": "test",
},
- status=302,
- follow_redirects=False
+ status=403,
)
- # Anonymous users are redirected to login page
- assert "user/login?next=%2Fgroup%2Fmember_new%2F" in res
@pytest.mark.usefixtures("non_clean_db", "with_request_context")
diff --git a/ckan/tests/controllers/test_organization.py b/ckan/tests/controllers/test_organization.py
--- a/ckan/tests/controllers/test_organization.py
+++ b/ckan/tests/controllers/test_organization.py
@@ -25,9 +25,7 @@ def sysadmin():
class TestOrganizationNew(object):
def test_not_logged_in(self, app):
- res = app.get(url=url_for("group.new"), status=302, follow_redirects=False)
- # Anonymous users are redirected to login page
- assert "user/login?next=%2Fgroup%2Fnew" in res
+ app.get(url=url_for("group.new"), status=403)
def test_name_required(self, app, user):
url = url_for("organization.new")
@@ -213,15 +211,12 @@ def test_non_authorized_user_trying_to_delete_fails(
def test_anon_user_trying_to_delete_fails(self, app):
group = factories.Organization()
- res = app.get(
+ app.get(
url=url_for(
"organization.delete", id=group["id"]
),
- status=302,
- follow_redirects=False
+ status=403,
)
- # Anonymous users are redirected to login page
- assert "user/login?next=%2Forganization%2Fdelete%2F" in res
organization = helpers.call_action(
"organization_show", id=group["id"]
@@ -561,15 +556,12 @@ def test_anonymous_users_cannot_add_members(self, app):
organization = factories.Organization()
with app.flask_app.test_request_context():
- res = app.get(
+ app.get(
url_for("organization.member_new", id=organization["id"]),
- status=302,
- follow_redirects=False
+ status=403,
)
- # Anonymous users are redirected to login page
- assert "user/login?next=%2Forganization%2Fmember_new%2F" in res
- res = app.post(
+ app.post(
url_for("organization.member_new", id=organization["id"]),
data={
"id": "test",
@@ -577,8 +569,7 @@ def test_anonymous_users_cannot_add_members(self, app):
"save": "save",
"role": "test",
},
- status=302,
- follow_redirects=False
+ status=403,
)
def test_create_user_for_user_invite(self, mail_server, sysadmin):
diff --git a/ckan/tests/controllers/test_package.py b/ckan/tests/controllers/test_package.py
--- a/ckan/tests/controllers/test_package.py
+++ b/ckan/tests/controllers/test_package.py
@@ -440,14 +440,11 @@ def test_unauthed_user_creating_dataset(self, app):
# provide REMOTE_ADDR to idenfity as remote user, see
# ckan.views.identify_user() for details
- res = app.post(
+ app.post(
url=url_for("dataset.new"),
extra_environ={"REMOTE_ADDR": "127.0.0.1"},
- status=302,
- follow_redirects=False
+ status=403,
)
- # Anonymous users are redirected to login page
- assert "user/login?next=%2Fdataset%2Fnew" in res
def test_form_without_initial_data(self, app, user):
url = url_for("dataset.new")
@@ -551,18 +548,13 @@ def test_anonymous_user_cannot_edit(self, app):
organization = factories.Organization()
dataset = factories.Dataset(owner_org=organization["id"])
url = url_for("dataset.edit", id=dataset["name"])
- res = app.get(url=url, status=302, follow_redirects=False)
- # Anonymous users are redirected to login page
- assert "user/login?next=%2Fdataset%2Fedit%2F" in res
+ app.get(url=url, status=403)
- res = app.post(
+ app.post(
url=url,
data={"notes": "edited description"},
- status=302,
- follow_redirects=False
+ status=403,
)
- # Anonymous users are redirected to login page
- assert "user/login?next=%2Fdataset%2Fedit%2F" in res
def test_validation_errors_for_dataset_name_appear(self, app, user):
"""fill out a bad dataset set name and make sure errors appear"""
@@ -776,10 +768,11 @@ def test_anon_user_cannot_delete_owned_dataset(self, app, user):
users=[{"name": user["name"], "capacity": "admin"}]
)
dataset = factories.Dataset(owner_org=owner_org["id"])
- url = url_for("dataset.delete", id=dataset["name"])
- res = app.post(url, status=302, follow_redirects=False)
- # Anonymous users are redirected to login page
- assert "user/login?next=%2Fdataset%2Fdelete%2F" in res
+
+ response = app.post(
+ url_for("dataset.delete", id=dataset["name"]), status=403
+ )
+ assert helpers.body_contains(response, "Unauthorized to delete package")
deleted = helpers.call_action("package_show", id=dataset["id"])
assert "active" == deleted["state"]
@@ -1004,22 +997,19 @@ def test_anonymous_users_cannot_add_new_resource(self, app):
organization = factories.Organization()
dataset = factories.Dataset(owner_org=organization["id"])
- res = app.get(
+ app.get(
url_for(
"{}_resource.new".format(dataset["type"]), id=dataset["id"]
- ), status=302, follow_redirects=False
+ ), status=403
)
- # Anonymous users are redirected to login page
- assert "user/login?next=%2Fdataset%2F" in res
- res = app.post(
+
+ app.post(
url_for(
"{}_resource.new".format(dataset["type"]), id=dataset["id"]
),
data={"name": "test", "url": "test", "save": "save", "id": ""},
- status=302, follow_redirects=False
+ status=403
)
- # Anonymous users are redirected to login page
- assert "user/login?next=%2Fdataset%2F" in res
def test_anonymous_users_cannot_edit_resource(self, app):
organization = factories.Organization()
@@ -1027,30 +1017,24 @@ def test_anonymous_users_cannot_edit_resource(self, app):
resource = factories.Resource(package_id=dataset["id"])
with app.flask_app.test_request_context():
- res = app.get(
+ app.get(
url_for(
"{}_resource.edit".format(dataset["type"]),
id=dataset["id"],
resource_id=resource["id"],
),
- status=302,
- follow_redirects=False
+ status=403,
)
- # Anonymous users are redirected to login page
- assert "user/login?next=%2Fdataset%2F" in res
- res = app.post(
+ app.post(
url_for(
"{}_resource.edit".format(dataset["type"]),
id=dataset["id"],
resource_id=resource["id"],
),
data={"name": "test", "url": "test", "save": "save", "id": ""},
- status=302,
- follow_redirects=False
+ status=403,
)
- # Anonymous users are redirected to login page
- assert "user/login?next=%2Fdataset%2F" in res
@pytest.mark.usefixtures("non_clean_db", "with_plugins", "with_request_context")
@@ -1340,17 +1324,14 @@ def test_anon_users_cannot_delete_owned_resources(self, app):
dataset = factories.Dataset(owner_org=owner_org["id"])
resource = factories.Resource(package_id=dataset["id"])
- res = app.post(
+ app.post(
url_for(
"{}_resource.delete".format(dataset["type"]),
id=dataset["name"],
resource_id=resource["id"],
),
- status=302,
- follow_redirects=False
+ status=403,
)
- # Anonymous users are redirected to login page
- assert "user/login?next=%2Fdataset%2F" in res
def test_logged_in_users_cannot_delete_resources_they_do_not_own(
self, app, user
@@ -1949,9 +1930,7 @@ def test_resource_listing_premissions_non_auth_user(self, app, user):
def test_resource_listing_premissions_not_logged_in(self, app):
pkg = factories.Dataset()
url = url_for("dataset.resources", id=pkg["name"])
- res = app.get(url, status=302, follow_redirects=False)
- # Anonymous users are redirected to login page
- assert "user/login?next=%2Fdataset%2F" in res
+ app.get(url, status=403)
@pytest.mark.usefixtures('clean_db', 'with_request_context')
diff --git a/ckan/tests/controllers/test_user.py b/ckan/tests/controllers/test_user.py
--- a/ckan/tests/controllers/test_user.py
+++ b/ckan/tests/controllers/test_user.py
@@ -287,9 +287,7 @@ def test_user_edit_unknown_user(self, app):
"""Attempt to read edit user for an unknown user redirects to login
page."""
url = url_for("user.edit", id=factories.User.stub().name)
- res = app.get(url, status=302, follow_redirects=False)
- # Anonymous users are redirected to login page
- assert "user/login?next=%2Fuser%2Fedit%2F" in res
+ app.get(url, status=403)
def test_user_edit_not_logged_in(self, app):
"""Attempt to read edit user for an existing, not-logged in user
@@ -298,9 +296,7 @@ def test_user_edit_not_logged_in(self, app):
user = factories.User()
username = user["name"]
url = url_for("user.edit", id=username)
- res = app.get(url, status=302, follow_redirects=False)
- # Anonymous users are redirected to login page
- assert "user/login?next=%2Fuser%2Fedit%2F" in res
+ app.get(url, status=403)
def test_edit_user(self, app, user):
env = {"Authorization": user["token"]}
| Inconsistent behaviuor in non-authorized errors (2.10)
**CKAN version**
2.10 (master)
**Describe the bug**
Following up from https://github.com/ckan/ckan/pull/6560, here's what happens when a user is not authorized to perform an action on the UI:
| CKAN Version | Logged in user | HTTP status, result |
| --- | --- | --- |
| <= 2.9 (tested 2.9 and 2.8) | No | 403 - Not authorized message
| <= 2.9 (tested 2.9 and 2.8) | Yes | 403 - Not authorized message
| 2.10, default behaviour | No | 302 + 200, Redirect to login page
| 2.10, default behaviour | Yes | 403 - Not authorized message
| 2.10, if `ckan.redirect_to_login_if_not_authorized` is False | No | 403 - Not authorized message
| 2.10, if `ckan.redirect_to_login_if_not_authorized` is False | Yes | 403 - Not authorized message
It seems that at the very least, we should
1. fix the inconsistency between logged in users and non-logged in users in 2.10. Looks like we don't need to check `if current_user.is_anonymous` here:
https://github.com/ckan/ckan/blob/ed155dca25265562e1a9125ee6917b832d514b10/ckan/config/middleware/flask_app.py#L542
2. Decide if we want to change the default behaviour to redirect to the login page or keep the 403 error.
| another option is to keep the 403 but render a login page on the error response. (bonus points for including a hidden parameter in the form to redirect to the original page after login)
@amercader, @wardi it's true that anonymous users get redirected to the login page if 403 happens, but after they log in, ckan redirects them back to where they were and shows 403 if not authorized.
Isn't that what we needed?
@TomeCirun We discussed this in the dev meeting. It's probably best not to change the status code returned between CKAN versions (I had some tests broken because of this). But we can make easier for non-logged in users to login adding a link to the login page to the 403 or 401 error pages (embedding the form would make things more complicated for extensions overriding the authentication logic). So basically rendering `error_document_template.html` with a custom `content` [here](https://github.com/ckan/ckan/blob/ed155dca25265562e1a9125ee6917b832d514b10/ckan/config/middleware/flask_app.py#L551) instead of redirecting.
And then we can remove the `ckan.redirect_to_login_if_not_authorized` setting and simplify things.
Does this make sense?
Everything coming from the dev meetings makes sense :), btw I remember we wanted the same behavior as on 2.9, you can see a comment from @pdelboca [here](https://github.com/ckan/ckan/pull/6560#issuecomment-1111859579 ) asking for that change, maybe we can check this before going any further?
@amercader
@TomeCirun I think extensions should gradually migrate to emit 403s instead of 401s to be consistent with the CKAN core behaviour so let's go ahead with the plan (cc @pdelboca) | 2022-07-28T16:30:25 |
ckan/ckan | 7,021 | ckan__ckan-7021 | [
"7016"
] | 34401f000846aa59559c77e755e56656cf1355f9 | diff --git a/ckan/lib/helpers.py b/ckan/lib/helpers.py
--- a/ckan/lib/helpers.py
+++ b/ckan/lib/helpers.py
@@ -2783,3 +2783,8 @@ def make_login_url(
parsed_base = parsed_base._replace(netloc=netloc, query=urlencode(md))
return urlunparse(parsed_base)
return base
+
+
+@core_helper
+def csrf_input():
+ return snippet('snippets/csrf_input.html')
diff --git a/ckan/plugins/toolkit.py b/ckan/plugins/toolkit.py
--- a/ckan/plugins/toolkit.py
+++ b/ckan/plugins/toolkit.py
@@ -47,7 +47,7 @@
literal,
chained_helper,
redirect_to,
- url_for,
+ url_for
)
from ckan.exceptions import (
CkanVersionException,
@@ -99,7 +99,7 @@
"mail_recipient", "mail_user",
"render_snippet", "add_template_directory", "add_public_directory",
"add_resource", "add_ckan_admin_tab",
- "check_ckan_version", "requires_ckan_version", "get_endpoint",
+ "check_ckan_version", "requires_ckan_version", "get_endpoint"
]
get_converter = get_validator
| Provide a mechanism to support CSRF on extensions that support older CKAN version
@TomeCirun @pdelboca
After #6863, [best practices](https://github.com/ckan/ckan/blob/master/doc/extensions/best-practices.rst) say:
> To add CSRF protection to your extensions use the CSRF macro in all your forms
> {% import 'macros/form.html' as form %}
> ...
> {{ form.csrf_protection() }}
This won't work on CKAN<=2.9 because that macro doesn't exist. Similarly, trying to add the input directly like in [here](https://github.com/ckan/ckan/pull/6863/files#diff-09d2291ff01f465bfadf71b865872b83bd0301fc32f72e3fc96964a74a1619b0R7) will fail because the `csrf_token()` function is not defined.
My suggestion would be:
1. Consolidate all CSRF inputs into a single `{{ h.csrf_input() }}` call (both the ` {{ form.csrf_protection() }}` ones and the direct ` <input type="hidden" ...` ones). Using a helper will allow extensions to override it if necessary. Then we can use the same template markup everywhere.
2. Provide `h.csrf_input()` stubs on CKAN<2.9 that don't actually return anything. This could be done either:
2.1. Patching CKAN core so 2.9.6 and 2.8.11 register `csrf_input()` template helpers, but they return an empty string
2.2 Something similar but using ckantoolkit. I think this would be messier and even impossible.
At the end of this, an extension wanting to support CKAN<=2.9 and CKAN 2.10 with CSRF protection can just add the same code as core, and it will work across CKAN versions without messy checks on each extension:
```
<form class="dataset-form add-member-form" method='post'>
{{ h.csrf_input() }}
```
Does this make sense?
**edit**: updated to use a template helper instead of a Jinja tag
| Forgot to say that this should be validated on everyone's favourite forms extension, ckanext-scheming!
@TomeCirun Does the above make sense? would you have time to work on it?
Yes @amercader, I can work on this | 2022-08-21T21:15:44 |
|
ckan/ckan | 7,029 | ckan__ckan-7029 | [
"7016"
] | 81e391f7a0dfa6a5b65a7b481e59091e1b618d8c | diff --git a/ckan/lib/helpers.py b/ckan/lib/helpers.py
--- a/ckan/lib/helpers.py
+++ b/ckan/lib/helpers.py
@@ -2703,3 +2703,8 @@ def sanitize_id(id_):
ValueError.
'''
return str(uuid.UUID(id_))
+
+
+@core_helper
+def csrf_input():
+ return ''
| Provide a mechanism to support CSRF on extensions that support older CKAN version
@TomeCirun @pdelboca
After #6863, [best practices](https://github.com/ckan/ckan/blob/master/doc/extensions/best-practices.rst) say:
> To add CSRF protection to your extensions use the CSRF macro in all your forms
> {% import 'macros/form.html' as form %}
> ...
> {{ form.csrf_protection() }}
This won't work on CKAN<=2.9 because that macro doesn't exist. Similarly, trying to add the input directly like in [here](https://github.com/ckan/ckan/pull/6863/files#diff-09d2291ff01f465bfadf71b865872b83bd0301fc32f72e3fc96964a74a1619b0R7) will fail because the `csrf_token()` function is not defined.
My suggestion would be:
1. Consolidate all CSRF inputs into a single `{{ h.csrf_input() }}` call (both the ` {{ form.csrf_protection() }}` ones and the direct ` <input type="hidden" ...` ones). Using a helper will allow extensions to override it if necessary. Then we can use the same template markup everywhere.
2. Provide `h.csrf_input()` stubs on CKAN<2.9 that don't actually return anything. This could be done either:
2.1. Patching CKAN core so 2.9.6 and 2.8.11 register `csrf_input()` template helpers, but they return an empty string
2.2 Something similar but using ckantoolkit. I think this would be messier and even impossible.
At the end of this, an extension wanting to support CKAN<=2.9 and CKAN 2.10 with CSRF protection can just add the same code as core, and it will work across CKAN versions without messy checks on each extension:
```
<form class="dataset-form add-member-form" method='post'>
{{ h.csrf_input() }}
```
Does this make sense?
**edit**: updated to use a template helper instead of a Jinja tag
| Forgot to say that this should be validated on everyone's favourite forms extension, ckanext-scheming!
@TomeCirun Does the above make sense? would you have time to work on it?
Yes @amercader, I can work on this | 2022-08-23T15:15:21 |
|
ckan/ckan | 7,030 | ckan__ckan-7030 | [
"7016"
] | 4d0e47c635bcb05f09d23253477028a66249cc7f | diff --git a/ckan/lib/helpers.py b/ckan/lib/helpers.py
--- a/ckan/lib/helpers.py
+++ b/ckan/lib/helpers.py
@@ -2987,3 +2987,8 @@ def can_update_owner_org(package_dict, user_orgs=None):
return True
return False
+
+
+@core_helper
+def csrf_input():
+ return ''
| Provide a mechanism to support CSRF on extensions that support older CKAN version
@TomeCirun @pdelboca
After #6863, [best practices](https://github.com/ckan/ckan/blob/master/doc/extensions/best-practices.rst) say:
> To add CSRF protection to your extensions use the CSRF macro in all your forms
> {% import 'macros/form.html' as form %}
> ...
> {{ form.csrf_protection() }}
This won't work on CKAN<=2.9 because that macro doesn't exist. Similarly, trying to add the input directly like in [here](https://github.com/ckan/ckan/pull/6863/files#diff-09d2291ff01f465bfadf71b865872b83bd0301fc32f72e3fc96964a74a1619b0R7) will fail because the `csrf_token()` function is not defined.
My suggestion would be:
1. Consolidate all CSRF inputs into a single `{{ h.csrf_input() }}` call (both the ` {{ form.csrf_protection() }}` ones and the direct ` <input type="hidden" ...` ones). Using a helper will allow extensions to override it if necessary. Then we can use the same template markup everywhere.
2. Provide `h.csrf_input()` stubs on CKAN<2.9 that don't actually return anything. This could be done either:
2.1. Patching CKAN core so 2.9.6 and 2.8.11 register `csrf_input()` template helpers, but they return an empty string
2.2 Something similar but using ckantoolkit. I think this would be messier and even impossible.
At the end of this, an extension wanting to support CKAN<=2.9 and CKAN 2.10 with CSRF protection can just add the same code as core, and it will work across CKAN versions without messy checks on each extension:
```
<form class="dataset-form add-member-form" method='post'>
{{ h.csrf_input() }}
```
Does this make sense?
**edit**: updated to use a template helper instead of a Jinja tag
| Forgot to say that this should be validated on everyone's favourite forms extension, ckanext-scheming!
@TomeCirun Does the above make sense? would you have time to work on it?
Yes @amercader, I can work on this | 2022-08-23T15:19:21 |
|
ckan/ckan | 7,033 | ckan__ckan-7033 | [
"7009"
] | 34401f000846aa59559c77e755e56656cf1355f9 | diff --git a/ckan/config/environment.py b/ckan/config/environment.py
--- a/ckan/config/environment.py
+++ b/ckan/config/environment.py
@@ -115,7 +115,7 @@ def update_config() -> None:
webassets_init()
- for plugin in p.PluginImplementations(p.IConfigurer):
+ for plugin in reversed(list(p.PluginImplementations(p.IConfigurer))):
# must do update in place as this does not work:
# config = plugin.update_config(config)
plugin.update_config(config)
| IConfigurer plugin load order
**CKAN version**
(all)
**Describe the bug**
`update_config` runs through all IConfigurer plugins from first to last calling `plugin.update_config`. The pattern for other interfaces is that the "first plugin wins", but this is difficult to implement when later plugins override values from earlier ones in the list.
**Steps to reproduce**
Enable two plugins that set the same config value using IConfigurer
**Expected behavior**
First plugin value should win, like with other interfaces.
**Additional details**
ckanext-envvars recommends adding `envvars` last in the list of plugins, which makes sense but if other plugins depend on/override values configured in envvars (e.g. ckanext-scheming) they won't be available at `update_config` time.
| We decided to [reverse the order](https://github.com/ckan/ckan/blob/f2eb20ebf9de21016fd3d15ed028be1cce8d447c/ckan/config/environment.py#L118) in which `IConfigurer` plugins are read to be consistent with other hooks. Add a changelog entry.
> We decided to [reverse the order](https://github.com/ckan/ckan/blob/f2eb20ebf9de21016fd3d15ed028be1cce8d447c/ckan/config/environment.py#L118) in which `IConfigurer` plugins are read to be consistent with other hooks. Add a changelog entry.
Great, I can work on this one :) | 2022-08-23T20:39:33 |
|
ckan/ckan | 7,058 | ckan__ckan-7058 | [
"7028"
] | 5cacf59a092f9cc94ab83f2bcceabb1a103a4612 | diff --git a/ckan/views/api.py b/ckan/views/api.py
--- a/ckan/views/api.py
+++ b/ckan/views/api.py
@@ -15,7 +15,6 @@
import ckan.model as model
from ckan.common import json, _, g, request, current_user
-from ckan.config.middleware.flask_app import csrf
from ckan.lib.helpers import url_for
from ckan.lib.base import render
from ckan.lib.i18n import get_locales_from_config
@@ -208,8 +207,6 @@ def mixed(multi_dict: "MultiDict[str, Any]") -> dict[str, Any]:
# View functions
-# exempt the CKAN API actions from csrf-validation.
[email protected]
def action(logic_function: str, ver: int = API_DEFAULT_VERSION) -> Response:
u'''Main endpoint for the action API (v3)
| Lock down cookie based authentication on API endpoints
Discussed on 2022-08-23 dev meeting:
1. Default behaviour: discard cookie based authentication in the API if it doesn't include the CSRF token
- Is this equivalent to remove the `@csrf.exempt` decorator [here](https://github.com/ckan/ckan/blob/34401f000846aa59559c77e755e56656cf1355f9/ckan/views/api.py#L212)?
2. Add new configuration option: turn off entirely cookie based authentication on the API endpoint
- Not sure how to implement this, but probably we need to fiddle at the Flask-login level. Maybe [this](https://flask-login.readthedocs.io/en/latest/#disabling-session-cookie-for-apis) is helpful?
3. (Optional): Allow cookie based authentication without valid CSRF tokens on development mode
@wardi @EricSoroos did I capture that correctly?
| @TomeCirun you were kindly volunteered to work on this by @tino097 :)
Let's start with the first point. I think what we need to do is:
1. Remove the `@csrf.exempt` check from the API `action` endpoint. This will cause all client side JS API calls to fail, so
2. We need to update the JS calls to include the CSRF header, like you did for the `follow` module on #6863 . Remember to move the `addCsrfTokenHeader()` function to the [base module class](https://github.com/ckan/ckan/blob/master/ckan/public/base/javascript/module.js). Or maybe we even don't have to change any modules and just modify the [client class](https://github.com/ckan/ckan/blob/master/ckan/public/base/javascript/client.js) they use to add the header
3. Document the behaviour change (No cookie based authentication in the API without CSRF token) and the changes needed in JS if they are not using the ckan client
Does this make sense? | 2022-09-05T04:49:09 |
|
ckan/ckan | 7,077 | ckan__ckan-7077 | [
"7076"
] | 9f1b5cfaff8c135b589e2ea0275f1286c2e02711 | diff --git a/ckan/model/modification.py b/ckan/model/modification.py
--- a/ckan/model/modification.py
+++ b/ckan/model/modification.py
@@ -47,8 +47,12 @@ def notify_observers(self, session: Any, method: Any):
for item in plugins.PluginImplementations(plugins.IResourceUrlChange):
item.notify(obj)
- changed_pkgs = set(obj for obj in changed
- if isinstance(obj, model.Package))
+
+ changed_pkgs = set()
+ new_pkg_ids = [obj.id for obj in new if isinstance(obj, model.Package)]
+ for obj in changed:
+ if isinstance(obj, model.Package) and obj.id not in new_pkg_ids:
+ changed_pkgs.add(obj)
for obj in new | changed | deleted:
if not isinstance(obj, model.Package):
| diff --git a/ckan/tests/lib/search/test_index.py b/ckan/tests/lib/search/test_index.py
--- a/ckan/tests/lib/search/test_index.py
+++ b/ckan/tests/lib/search/test_index.py
@@ -3,10 +3,12 @@
import datetime
import hashlib
import json
+from unittest import mock
import pytest
import six
from ckan.common import config
import ckan.lib.search as search
+from ckan.tests import factories, helpers
@pytest.mark.skipif(not search.is_available(), reason="Solr not reachable")
@@ -299,3 +301,22 @@ def test_indexed_package_stores_resource_type(self):
# Resource types are indexed
assert indexed_pkg["res_type"] == ["doc", "file"]
+
+
[email protected]("clean_index")
+def test_index_only_called_once():
+
+ with mock.patch("ckan.lib.search.index.PackageSearchIndex.index_package") as m:
+
+ dataset = factories.Dataset()
+
+ assert m.call_count == 1
+
+ m.reset_mock()
+
+ dataset["notes"] = "hi"
+ helpers.call_action("package_update", **dataset)
+
+ assert m.call_count == 1
+
+ assert helpers.call_action("package_show", id=dataset["id"])["notes"] == "hi"
| Search indexing logic called twice after update or create dataset
**CKAN version**
2.10
**Describe the bug**
When updating or creating a dataset, we are indexing the dataset twice in a row, ie the [`index_package()`](https://github.com/ckan/ckan/blob/9f1b5cfaff8c135b589e2ea0275f1286c2e02711/ckan/lib/search/index.py#L108) function gets called twice during the same operation (and of course any `IPackageController.before_index()` hook gets called twice as well.
The root cause is the the obscure code run in the [`DomainObjectModificationExtension`](https://github.com/ckan/ckan/blob/9f1b5cfaff8c135b589e2ea0275f1286c2e02711/ckan/model/modification.py#L27), which considers the same Package object both new and changed at the same time, and fires two separate notification events.
| 2022-09-13T10:33:58 |
|
ckan/ckan | 7,086 | ckan__ckan-7086 | [
"7085"
] | 81715e826981440e3cc1bd5e21ad7ca168975102 | diff --git a/ckan/config/environment.py b/ckan/config/environment.py
--- a/ckan/config/environment.py
+++ b/ckan/config/environment.py
@@ -191,6 +191,8 @@ def update_config() -> None:
template_paths = [jinja2_templates_path]
extra_template_paths = config.get_value('extra_template_paths')
+ if 'plugin_template_paths' in config:
+ template_paths = config['plugin_template_paths'] + template_paths
if extra_template_paths:
# must be first for them to override defaults
template_paths = extra_template_paths.split(',') + template_paths
diff --git a/ckan/config/middleware/flask_app.py b/ckan/config/middleware/flask_app.py
--- a/ckan/config/middleware/flask_app.py
+++ b/ckan/config/middleware/flask_app.py
@@ -145,7 +145,9 @@ def make_flask_stack(conf: Union[Config, CKANConfig]) -> CKANApp:
public_folder = config.get_value(u'ckan.base_public_folder')
app.static_folder = config.get_value(
'extra_public_paths'
- ).split(',') + [os.path.join(root, public_folder)] + storage_folder
+ ).split(',') + config.get('plugin_public_paths', []) + [
+ os.path.join(root, public_folder)
+ ] + storage_folder
app.jinja_options = jinja_extensions.get_jinja_env_options()
app.jinja_env.policies['ext.i18n.trimmed'] = True
diff --git a/ckan/plugins/toolkit.py b/ckan/plugins/toolkit.py
--- a/ckan/plugins/toolkit.py
+++ b/ckan/plugins/toolkit.py
@@ -123,7 +123,7 @@ def add_template_directory(config_: CKANConfig, relative_path: str):
The path is relative to the file calling this function.
"""
- _add_served_directory(config_, relative_path, "extra_template_paths")
+ _add_served_directory(config_, relative_path, "plugin_template_paths")
def add_public_directory(config_: CKANConfig, relative_path: str):
@@ -139,7 +139,7 @@ def add_public_directory(config_: CKANConfig, relative_path: str):
from ckan.lib.helpers import _local_url
from ckan.lib.webassets_tools import add_public_path
- path = _add_served_directory(config_, relative_path, "extra_public_paths")
+ path = _add_served_directory(config_, relative_path, "plugin_public_paths")
url = _local_url("/", locale="default")
add_public_path(path, url)
@@ -150,18 +150,18 @@ def _add_served_directory(
import inspect
import os
- assert config_var in ("extra_template_paths", "extra_public_paths")
+ assert config_var in ("plugin_template_paths", "plugin_public_paths")
# we want the filename that of the function caller but they will
# have used one of the available helper functions
filename = inspect.stack()[2].filename
this_dir = os.path.dirname(filename)
absolute_path = os.path.join(this_dir, relative_path)
- if absolute_path not in config_.get_value(config_var).split(","):
- if config_.get_value(config_var):
- config_[config_var] += "," + absolute_path
+ if absolute_path not in config_.get(config_var, []):
+ if config_var in config_:
+ config_[config_var] = [absolute_path] + config_[config_var]
else:
- config_[config_var] = absolute_path
+ config_[config_var] = [absolute_path]
return absolute_path
| diff --git a/ckan/tests/helpers.py b/ckan/tests/helpers.py
--- a/ckan/tests/helpers.py
+++ b/ckan/tests/helpers.py
@@ -598,6 +598,7 @@ class FakeSMTP(smtplib.SMTP):
def __init__(self):
self._msgs = []
+ self.esmtp_features = ['starttls']
def __call__(self, *args):
return self
| plugin template order reversed (since #7033)
**CKAN version**
master
**Describe the bug**
After we swapped the order of calling plugins' update_config hooks the resulting order of templates and public directories is now reversed
**Steps to reproduce**
have more than one plugin that adds template directories
**Expected behavior**
first plugin templates override later plugin templates (historic behaviour)
**Additional details**
| 2022-09-14T17:38:24 |
|
ckan/ckan | 7,093 | ckan__ckan-7093 | [
"5888"
] | 59eea9ebd29067e303cf4325c76a119e46566d9c | diff --git a/ckan/logic/action/update.py b/ckan/logic/action/update.py
--- a/ckan/logic/action/update.py
+++ b/ckan/logic/action/update.py
@@ -491,10 +491,10 @@ def package_revise(context: Context, data_dict: DataDict) -> ActionResult.Packag
if unmatched:
model.Session.rollback()
- raise ValidationError({'message': [{'match': [
+ raise ValidationError({'match': [
'__'.join(str(p) for p in unm)
for unm in unmatched
- ]}]})
+ ]})
if 'filter' in data:
orig_id = orig['id']
@@ -506,7 +506,7 @@ def package_revise(context: Context, data_dict: DataDict) -> ActionResult.Packag
dfunc.update_merge_dict(orig, data['update'])
except dfunc.DataError as de:
model.Session.rollback()
- raise ValidationError({'message': [{'update': [de.error]}]})
+ raise ValidationError({'update': [de.error]})
# update __extend keys before __#__* so that files may be
# attached to newly added resources in the same call
@@ -517,7 +517,7 @@ def package_revise(context: Context, data_dict: DataDict) -> ActionResult.Packag
dfunc.update_merge_string_key(orig, k, v)
except dfunc.DataError as de:
model.Session.rollback()
- raise ValidationError({'message': [{k: [de.error]}]})
+ raise ValidationError({k: [de.error]})
_check_access('package_revise', context, {"update": orig})
| Bug: package_revise returns a list not str in the message value on error
**CKAN version**
2.9
**Describe the bug**
package_revise returns a list in the message value eg.
```
{'message': [{'resources__1__upload': ['Unmatched key resources__1']}], '__type': 'Validation Error'}
```
**Steps to reproduce**
Specify a resource that doesn't exist when uploading eg. `update__resources__1__upload`
**Expected behavior**
Error is returned with a string message (judging by how ckanapi Python library handles the returned error message by attempting to "split" it)
**Additional details**
I had raised an error against the ckanapi Python library (https://github.com/ckan/ckanapi/issues/186), but it seems the error is in package _revise. @wardi said "interesting, this might be a bug in package_revise, none of the other actions return a list in the message value AFAIK"
Traceback:
```
Traceback (most recent call last):
File "/home/mcarans/Programming/hdx-python-api/src/hdx/data/hdxobject.py", line 331, in _write_to_hdx
return self.configuration.call_remoteckan(self.actions()[action], data, files=files_to_upload)
File "/home/mcarans/Programming/hdx-python-api/src/hdx/hdx_configuration.py", line 307, in call_remoteckan
return self.remoteckan().call_action(*args, **kwargs)
File "/home/mcarans/Programming/VirtualEnvs/hdx-python-api/lib/python3.8/site-packages/ckanapi/remoteckan.py", line 88, in call_action
return reverse_apicontroller_action(url, status, response)
File "/home/mcarans/Programming/VirtualEnvs/hdx-python-api/lib/python3.8/site-packages/ckanapi/common.py", line 114, in reverse_apicontroller_action
emessage = err.get('message', '').split(': ', 1)[-1]
AttributeError: 'list' object has no attribute 'split'
```
| @mcarans I would like to work in this issue but I am unable to reproduce this issue. Can you provide me more information on how to reproduce it.
@Sunny-NEC The issue is that the package_revise call in CKAN returns a list rather than a string. When using the CKANAPI Python library to call package_revise in a way that causes an error eg. uploading a file into a resource that doesn't exist, the list type returned by CKAN causes a failure in the CKANAPI Python library 4.5 and lower.
The problem is that CKAN is not returning the expected type ie. package_revise is not following the convention of the other CKAN functions when returning errors. That is my understanding of the issue from what @wardi has said and he has made a fix in the CKANAPI library 4.6 hence why you are not seeing the error I guess, but the inconsistency in the CKAN package_revise call remains. Does this explanation help?
Hi @mcarans , I'm trying to reproduce the issue but am unable to do so. Could you please confirm where you're getting the error, is it coming from the `ckanapi` or `package_revise`?
Can you please provide the API endpoint that you're using to get this error response?
Thanks.
@robin-NEC I was using `ckanapi` and a fix was released in that library for the problem. See [this issue](https://github.com/ckan/ckanapi/issues/186). @wardi said "interesting, this might be a bug in package_revise, none of the other actions return a list in the message value AFAIK"
Looking at the source code, it may be that it was later fixed in CKAN in a large update a while ago. If you load the diff for [ckan/logic/action/update.py](https://github.com/ckan/ckan/commit/b2a03aa66b50fde7a68e0b2921104475117e7093#diff-dd88e6f8dd6bc2534492239093b9b1480233b670287fe4bc275a8ba32ed99c67) and search for `[{'match':` you can see that on line 488, it has changed from `raise ValidationError([{'match': [` to `raise ValidationError({'message': [{'match': [` and similarly for other ValidationError lines.
@robin-NEC I have tried a call like this in Postman:
url: SERVER_URL/api/3/action/package_revise
body:
match__id=ANY DATASET ID TO MATCH
update__resources__20__upload
(20 is any number higher than the number of resources in the dataset)
I got:
`{"help": "https://stage.data-humdata-org.ahconu.org/api/3/action/help_show?name=package_revise", "error": {"message": [{"resources__20__upload": ["Unmatched key resources__20"]}], "__type": "Validation Error"}, "success": false}`
I wrote before that the "error" part I saw looked like this so it appears the problem is still there:
`{'message': [{'resources__1__upload': ['Unmatched key resources__1']}], '__type': 'Validation Error'}`
If I look at the error from a different call like `package_show`, it looks like this:
`{"help": "https://stage.data-humdata-org.ahconu.org/api/3/action/help_show?name=package_show", "error": {"name_or_id": ["Missing value"], "__type": "Validation Error"}, "success": false}`
error for `package_revise` is of form "error": {string key: string or list of dictionaries value}
error for `package_show` is of form "error": {string key: string or list of strings value}
It really depends what has been defined as what is allowed for the values in the "error" dictionary as to whether the different forms of error are a bug or a feature.
note that latest ckanapi no longer fails this way when a list is returned in the message key | 2022-09-21T20:51:31 |
|
ckan/ckan | 7,096 | ckan__ckan-7096 | [
"7095"
] | 367fed2fa572e896c5eb703db9c663e097133e41 | diff --git a/ckan/config/middleware/flask_app.py b/ckan/config/middleware/flask_app.py
--- a/ckan/config/middleware/flask_app.py
+++ b/ckan/config/middleware/flask_app.py
@@ -12,7 +12,7 @@
from logging.handlers import SMTPHandler
from typing import Any, Iterable, Optional, Union, cast
-from flask import Blueprint, send_from_directory
+from flask import Blueprint, send_from_directory, current_app
from flask.ctx import _AppCtxGlobals
from flask.sessions import SessionInterface
from flask_multistatic import MultiStaticFlask
@@ -327,7 +327,10 @@ def load_user_from_request(request): # type: ignore
This callback function is called whenever a user could not be
authenticated via the session cookie, so we fall back to the API token.
"""
+ g.login_via_auth_header = True
+
user = _get_user_for_apitoken()
+
return user
# Update the main CKAN config object with the Flask specific keys
@@ -410,6 +413,16 @@ def ckan_before_request() -> Optional[Response]:
# Sets g.user and g.userobj for extensions
response = identify_user()
+ # Disable CSRF protection if user was logged in via the Authorization
+ # header
+ if g.get("login_via_auth_header"):
+ # Get the actual view function, as it might not match the endpoint,
+ # eg "organization.edit" -> "group.edit", or custom dataset types
+ endpoint = request.endpoint or ""
+ view = current_app.view_functions.get(endpoint)
+ dest = f"{view.__module__}.{view.__name__}" # type: ignore
+ csrf.exempt(dest)
+
# Set the csrf_field_name so we can use it in our templates
g.csrf_field_name = config.get_value("WTF_CSRF_FIELD_NAME")
| diff --git a/ckan/tests/controllers/test_api.py b/ckan/tests/controllers/test_api.py
--- a/ckan/tests/controllers/test_api.py
+++ b/ckan/tests/controllers/test_api.py
@@ -380,3 +380,39 @@ def test_cookie_based_auth_disabled(app):
res = app.get(url, environ_overrides=env)
assert res.status_code == 200
+
+
[email protected]("clean_db")
+def test_header_based_auth_default(app):
+
+ sysadmin = factories.SysadminWithToken()
+ org = factories.Organization()
+ dataset = factories.Dataset(private=True, owner_org=org["id"])
+
+ url = url_for("api.action", ver=3, logic_function="package_show", id=dataset["id"])
+
+ env = {"Authorization": sysadmin["token"]}
+
+ res = app.get(url, environ_overrides=env)
+
+ assert res.status_code == 200
+
+
[email protected]("clean_db")
+def test_header_based_auth_default_post(app):
+
+ sysadmin = factories.SysadminWithToken()
+ org = factories.Organization()
+ dataset = factories.Dataset(private=True, owner_org=org["id"])
+
+ url = url_for("api.action", ver=3, logic_function="package_patch")
+
+ env = {"Authorization": sysadmin["token"]}
+
+ data = {
+ "id": dataset["id"],
+ "notes": "updated",
+ }
+ res = app.post(url, environ_overrides=env, data=data)
+
+ assert res.status_code == 200
diff --git a/ckan/tests/controllers/test_group.py b/ckan/tests/controllers/test_group.py
--- a/ckan/tests/controllers/test_group.py
+++ b/ckan/tests/controllers/test_group.py
@@ -350,19 +350,16 @@ def test_membership_list(self, app):
assert user_roles["User One"] == "Admin"
assert user_roles["User Two"] == "Member"
- @mock.patch("flask_login.utils._get_user")
- def test_membership_add(self, current_user, app):
+ def test_membership_add(self, app):
"""Member can be added via add member page"""
user = factories.User(fullname="My Owner")
- user_obj = model.User.get(user["name"])
- # mock current_user
- current_user.return_value = user_obj
factories.User(fullname="My Fullname", name="my-new-user")
group = self._create_group(user["name"])
url = url_for("group.member_new", id=group["name"])
add_response = app.post(
url,
+ environ_overrides={"REMOTE_USER": user["name"]},
data={"save": "", "username": "my-new-user", "role": "member"},
)
@@ -383,18 +380,15 @@ def test_membership_add(self, current_user, app):
assert user_roles["My Owner"] == "Admin"
assert user_roles["My Fullname"] == "Member"
- @mock.patch("flask_login.utils._get_user")
- def test_membership_add_by_email(self, current_user, app, mail_server):
+ def test_membership_add_by_email(self, app, mail_server):
user = factories.User(fullname="My Owner")
- user_obj = model.User.get(user["name"])
- # mock current_user
- current_user.return_value = user_obj
group = self._create_group(user["name"])
url = url_for("group.member_new", id=group["name"])
email = "[email protected]"
app.post(
url,
+ environ_overrides={"REMOTE_USER": user["name"]},
data={"save": "", "email": email, "role": "member"},
status=200
)
@@ -403,20 +397,19 @@ def test_membership_add_by_email(self, current_user, app, mail_server):
assert user.email == email
assert group["id"] in user.get_group_ids(capacity="member")
- @mock.patch("flask_login.utils._get_user")
- def test_membership_edit_page(self, current_user, app):
+ def test_membership_edit_page(self, app):
"""If `user` parameter provided, render edit page."""
owner = factories.User(fullname="My Owner")
- user_obj = model.User.get(owner["name"])
- # mock current_user
- current_user.return_value = user_obj
member = factories.User(fullname="My Fullname", name="my-user")
group = self._create_group(owner["name"], users=[
{'name': member['name'], 'capacity': 'admin'}
])
url = url_for("group.member_new", id=group["name"], user=member['name'])
- response = app.get(url)
+ response = app.get(
+ url,
+ environ_overrides={"REMOTE_USER": owner["name"]},
+ )
page = BeautifulSoup(response.body)
assert page.select_one('.page-heading').text.strip() == 'Edit Member'
@@ -425,19 +418,16 @@ def test_membership_edit_page(self, current_user, app):
assert page.select_one('#username').get('value') == member['name']
@pytest.mark.usefixtures("clean_db")
- @mock.patch("flask_login.utils._get_user")
- def test_admin_add(self, current_user, app):
+ def test_admin_add(self, app):
"""Admin can be added via add member page"""
owner = factories.User(fullname="My Owner")
- user_obj = model.User.get(owner["name"])
- # mock current_user
- current_user.return_value = user_obj
factories.User(fullname="My Fullname", name="my-admin-user")
group = self._create_group(owner["name"])
url = url_for("group.member_new", id=group["name"])
add_response = app.post(
url,
+ environ_overrides={"REMOTE_USER": owner["name"]},
data={"save": "", "username": "my-admin-user", "role": "admin"},
)
@@ -458,13 +448,9 @@ def test_admin_add(self, current_user, app):
assert user_roles["My Owner"] == "Admin"
assert user_roles["My Fullname"] == "Admin"
- @mock.patch("flask_login.utils._get_user")
- def test_remove_member(self, current_user, app):
+ def test_remove_member(self, app):
"""Member can be removed from group"""
user = factories.User(fullname="My Owner")
- user_obj = model.User.get(user["name"])
- # mock current_user
- current_user.return_value = user_obj
user_two = factories.User(fullname="User Two")
other_users = [{"name": user_two["id"], "capacity": "member"}]
@@ -475,7 +461,10 @@ def test_remove_member(self, current_user, app):
"group.member_delete", user=user_two["id"], id=group["id"]
)
- remove_response = app.post(remove_url)
+ remove_response = app.post(
+ remove_url,
+ environ_overrides={"REMOTE_USER": user["name"]},
+ )
assert helpers.body_contains(remove_response, "1 members")
remove_response_html = BeautifulSoup(remove_response.body)
@@ -493,20 +482,21 @@ def test_remove_member(self, current_user, app):
assert len(user_roles.keys()) == 1
assert user_roles["My Owner"] == "Admin"
- @mock.patch("flask_login.utils._get_user")
- def test_member_users_cannot_add_members(self, current_user, app):
+ def test_member_users_cannot_add_members(self, app):
user = factories.User(fullname="My Owner")
- user_obj = model.User.get(user["name"])
- # mock current_user
- current_user.return_value = user_obj
group = factories.Group(
users=[{"name": user["name"], "capacity": "member"}]
)
- app.get(url_for("group.member_new", id=group["id"]), status=403)
+ app.get(
+ url_for("group.member_new", id=group["id"]),
+ environ_overrides={"REMOTE_USER": user["name"]},
+ status=403
+ )
app.post(
url_for("group.member_new", id=group["id"]),
+ environ_overrides={"REMOTE_USER": user["name"]},
data={
"id": "test",
"username": "test",
diff --git a/ckan/tests/controllers/test_package.py b/ckan/tests/controllers/test_package.py
--- a/ckan/tests/controllers/test_package.py
+++ b/ckan/tests/controllers/test_package.py
@@ -33,13 +33,6 @@ def _get_location(res):
return urlparse(location)._replace(scheme='', netloc='').geturl()
-def mock_current_user(current_user):
- user = factories.User()
- user_obj = model.User.get(user["name"])
- # mock current_user
- current_user.return_value = user_obj
-
-
@pytest.mark.usefixtures("clean_db", "with_request_context")
class TestPackageNew(object):
@@ -185,28 +178,38 @@ def test_complete_package_with_one_resource(self, app, user):
assert pkg.resources[0].url == u"http://example.com/resource"
assert pkg.state == "active"
- @mock.patch("flask_login.utils._get_user")
- def test_complete_package_with_two_resources(self, current_user, app):
- mock_current_user(current_user)
+ def test_complete_package_with_two_resources(self, app):
+
+ user = factories.User()
url = url_for("dataset.new")
name = factories.Dataset.stub().name
- response = app.post(url, data={
- "name": name,
- "save": "",
- "_ckan_phase": 1
- }, follow_redirects=False)
+ response = app.post(
+ url,
+ data={
+ "name": name,
+ "save": "",
+ "_ckan_phase": 1
+ },
+ environ_overrides={"REMOTE_USER": user["name"]},
+ follow_redirects=False
+ )
location = _get_location(response)
app.post(location, data={
- "id": "",
- "url": "http://example.com/resource0",
- "save": "again"
- })
+ "id": "",
+ "url": "http://example.com/resource0",
+ "save": "again"
+ },
+
+ environ_overrides={"REMOTE_USER": user["name"]},
+ )
app.post(location, data={
- "id": "",
- "url": "http://example.com/resource1",
- "save": "go-metadata"
- })
+ "id": "",
+ "url": "http://example.com/resource1",
+ "save": "go-metadata"
+ },
+ environ_overrides={"REMOTE_USER": user["name"]},
+ )
pkg = model.Package.by_name(name)
resources = sorted(pkg.resources, key=lambda r: r.url)
assert resources[0].url == u"http://example.com/resource0"
@@ -232,23 +235,30 @@ def test_previous_button_works(self, app, user):
assert '/dataset/edit/' in response.headers['location']
- @mock.patch("flask_login.utils._get_user")
- def test_previous_button_populates_form(self, current_user, app):
- mock_current_user(current_user)
+ def test_previous_button_populates_form(self, app):
+
+ user = factories.User()
url = url_for("dataset.new")
name = factories.Dataset.stub().name
- response = app.post(url, data={
- "name": name,
- "save": "",
- "_ckan_phase": 1
- }, follow_redirects=False)
+ response = app.post(
+ url,
+ environ_overrides={"REMOTE_USER": user["name"]},
+ data={
+ "name": name,
+ "save": "",
+ "_ckan_phase": 1
+ },
+ follow_redirects=False
+ )
location = _get_location(response)
response = app.post(location, data={
"id": "",
"save": "go-dataset"
- })
+ },
+ environ_overrides={"REMOTE_USER": user["name"]},
+ )
assert 'name="title"' in response
assert f'value="{name}"'
@@ -814,27 +824,27 @@ def test_logged_in_user_cannot_delete_owned_dataset(self, app, user):
assert 403 == response.status_code
assert helpers.body_contains(response, "Unauthorized to delete package")
- @mock.patch("flask_login.utils._get_user")
- def test_confirm_cancel_delete(self, current_user, app):
+ def test_confirm_cancel_delete(self, app):
"""Test confirmation of deleting datasets
When package_delete is made as a get request, it should return a
'do you want to delete this dataset? confirmation page"""
user = factories.User()
- user_obj = model.User.get(user["name"])
- # mock current_user
- current_user.return_value = user_obj
owner_org = factories.Organization(
users=[{"name": user["name"], "capacity": "admin"}]
)
dataset = factories.Dataset(owner_org=owner_org["id"])
- response = app.get(url_for("dataset.delete", id=dataset["name"]))
+ response = app.get(
+ url_for("dataset.delete", id=dataset["name"]),
+ environ_overrides={"REMOTE_USER": user["name"]},
+ )
assert 200 == response.status_code
message = "Are you sure you want to delete dataset - {name}?"
assert helpers.body_contains(response, message.format(name=dataset["title"]))
response = app.post(
url_for("dataset.delete", id=dataset["name"]),
+ environ_overrides={"REMOTE_USER": user["name"]},
data={"cancel": ""}
)
assert 200 == response.status_code
@@ -1085,12 +1095,8 @@ def test_resource_download_content_type(self, create_with_upload, app):
@pytest.mark.ckan_config("ckan.plugins", "image_view")
@pytest.mark.usefixtures("non_clean_db", "with_plugins", "with_request_context")
class TestResourceView(object):
- @mock.patch("flask_login.utils._get_user")
- def test_resource_view_create(self, current_user, app):
+ def test_resource_view_create(self, app):
user = factories.User()
- user_obj = model.User.get(user["name"])
- # mock current_user
- current_user.return_value = user_obj
owner_org = factories.Organization(
users=[{"name": user["name"], "capacity": "admin"}]
)
@@ -1104,15 +1110,15 @@ def test_resource_view_create(self, current_user, app):
view_type="image_view",
)
- response = app.post(url, data={"title": "Test Image View"})
+ response = app.post(
+ url,
+ environ_overrides={"REMOTE_USER": user["name"]},
+ data={"title": "Test Image View"}
+ )
assert helpers.body_contains(response, "Test Image View")
- @mock.patch("flask_login.utils._get_user")
- def test_resource_view_edit(self, current_user, app):
+ def test_resource_view_edit(self, app):
user = factories.User()
- user_obj = model.User.get(user["name"])
- # mock current_user
- current_user.return_value = user_obj
owner_org = factories.Organization(
users=[{"name": user["name"], "capacity": "admin"}]
)
@@ -1127,16 +1133,16 @@ def test_resource_view_edit(self, current_user, app):
view_id=resource_view["id"],
)
- response = app.post(url, data={"title": "Updated RV Title"})
+ response = app.post(
+ url,
+ environ_overrides={"REMOTE_USER": user["name"]},
+ data={"title": "Updated RV Title"}
+ )
assert helpers.body_contains(response, "Updated RV Title")
- @mock.patch("flask_login.utils._get_user")
@pytest.mark.ckan_config("ckan.views.default_views", "")
- def test_resource_view_delete(self, current_user, app):
+ def test_resource_view_delete(self, app):
user = factories.User()
- user_obj = model.User.get(user["name"])
- # mock current_user
- current_user.return_value = user_obj
owner_org = factories.Organization(
users=[{"name": user["name"], "capacity": "admin"}]
)
@@ -1151,7 +1157,11 @@ def test_resource_view_delete(self, current_user, app):
view_id=resource_view["id"],
)
- response = app.post(url, data={"delete": "Delete"})
+ response = app.post(
+ url,
+ environ_overrides={"REMOTE_USER": user["name"]},
+ data={"delete": "Delete"}
+ )
assert helpers.body_contains(response, "This resource has no views")
def test_existent_resource_view_page_returns_ok_code(self, app):
@@ -1429,16 +1439,12 @@ def test_sysadmins_can_delete_any_resource(self, app, sysadmin):
with pytest.raises(logic.NotFound):
helpers.call_action("resource_show", id=resource["id"])
- @mock.patch("flask_login.utils._get_user")
- def test_confirm_and_cancel_deleting_a_resource(self, current_user, app):
+ def test_confirm_and_cancel_deleting_a_resource(self, app):
"""Test confirmation of deleting resources
When resource_delete is made as a get request, it should return a
'do you want to delete this reource? confirmation page"""
user = factories.User()
- user_obj = model.User.get(user["name"])
- # mock current_user
- current_user.return_value = user_obj
owner_org = factories.Organization(
users=[{"name": user["name"], "capacity": "admin"}]
)
@@ -1449,7 +1455,8 @@ def test_confirm_and_cancel_deleting_a_resource(self, current_user, app):
"{}_resource.delete".format(dataset["type"]),
id=dataset["name"],
resource_id=resource["id"],
- )
+ ),
+ environ_overrides={"REMOTE_USER": user["name"]},
)
assert 200 == response.status_code
message = "Are you sure you want to delete resource - {name}?"
@@ -1461,6 +1468,7 @@ def test_confirm_and_cancel_deleting_a_resource(self, current_user, app):
id=dataset["name"],
resource_id=resource["id"],
),
+ environ_overrides={"REMOTE_USER": user["name"]},
data={"cancel": ""},
)
assert 200 == response.status_code
diff --git a/ckan/tests/controllers/test_user.py b/ckan/tests/controllers/test_user.py
--- a/ckan/tests/controllers/test_user.py
+++ b/ckan/tests/controllers/test_user.py
@@ -625,15 +625,12 @@ def test_request_reset_but_mailer_not_configured(
assert "Error sending the email" in response
- @mock.patch("flask_login.utils._get_user")
- def test_sysadmin_not_authorized(self, current_user, app):
+ def test_sysadmin_not_authorized(self, app):
user = factories.User()
- user_obj = model.User.get(user["name"])
- # mock current_user
- current_user.return_value = user_obj
app.post(
url_for("user.sysadmin"),
data={"username": user["name"], "status": "1"},
+ environ_overrides={"REMOTE_USER": user["name"]},
status=403
)
@@ -646,13 +643,9 @@ def test_sysadmin_invalid_user(self, app, sysadmin):
status=404,
)
- @mock.patch("flask_login.utils._get_user")
- def test_sysadmin_promote_success(self, current_user, app):
+ def test_sysadmin_promote_success(self, app):
sysadmin = factories.Sysadmin()
- sysadmin_obj = model.User.get(sysadmin["name"])
- # mock current_user
- current_user.return_value = sysadmin_obj
# create a normal user
user = factories.User(fullname="Alice")
@@ -660,6 +653,7 @@ def test_sysadmin_promote_success(self, current_user, app):
resp = app.post(
url_for("user.sysadmin"),
data={"username": user["name"], "status": "1"},
+ environ_overrides={"REMOTE_USER": sysadmin["name"]},
status=200,
)
assert "Promoted Alice to sysadmin" in resp.body
@@ -668,12 +662,8 @@ def test_sysadmin_promote_success(self, current_user, app):
userobj = model.User.get(user["id"])
assert userobj.sysadmin
- @mock.patch('flask_login.utils._get_user')
- def test_sysadmin_revoke_success(self, current_user, app):
+ def test_sysadmin_revoke_success(self, app):
sysadmin = factories.Sysadmin()
- sysadmin_obj = model.User.get(sysadmin["name"])
- # mock current_user
- current_user.return_value = sysadmin_obj
# create another sysadmin
user = factories.Sysadmin(fullname="Bob")
@@ -681,6 +671,7 @@ def test_sysadmin_revoke_success(self, current_user, app):
resp = app.post(
url_for("user.sysadmin"),
data={"username": user["name"], "status": "0"},
+ environ_overrides={"REMOTE_USER": sysadmin["name"]},
status=200,
)
assert "Revoked sysadmin permission from Bob" in resp.body
diff --git a/ckan/tests/helpers.py b/ckan/tests/helpers.py
--- a/ckan/tests/helpers.py
+++ b/ckan/tests/helpers.py
@@ -268,8 +268,6 @@ def test_dataset_search(self, app):
"""
config["testing"] = True
- # exempt the CKAN TESTS from csrf-validation.
- config["WTF_CSRF_METHODS"] = []
app = ckan.config.middleware.make_app(config)
app = CKANTestApp(app)
diff --git a/ckanext/example_idatasetform/tests/test_example_idatasetform.py b/ckanext/example_idatasetform/tests/test_example_idatasetform.py
--- a/ckanext/example_idatasetform/tests/test_example_idatasetform.py
+++ b/ckanext/example_idatasetform/tests/test_example_idatasetform.py
@@ -175,19 +175,17 @@ def test_dataset_create_redirects(self, app, user):
"fancy_type.read", id=name, _external=True
)
- @mock.patch("flask_login.utils._get_user")
- def test_links_on_edit_pages(self, current_user, app):
- user = factories.User()
- user_obj = model.User.get(user["name"])
- # mock current_user
- current_user.return_value = user_obj
+ def test_links_on_edit_pages(self, app):
+ user = factories.Sysadmin()
pkg = factories.Dataset(type="fancy_type", user=user)
res = factories.Resource(package_id=pkg["id"], user=user)
- page = bs4.BeautifulSoup(
- app.get(
- url_for("fancy_type.edit", id=pkg["name"])).body
+ response = app.get(
+ url_for("fancy_type.edit", id=pkg["name"]),
+ environ_overrides={"REMOTE_USER": user["name"]},
+ status=200,
)
+ page = bs4.BeautifulSoup(response.body)
page_header = page.find(class_="page-header")
for action in ["edit", "resources", "read"]:
assert page_header.find(
@@ -199,6 +197,7 @@ def test_links_on_edit_pages(self, current_user, app):
)
resp = app.post(
url_for("fancy_type.edit", id=pkg["name"]),
+ environ_overrides={"REMOTE_USER": user["name"]},
data={
"name": pkg["name"],
"save": "",
@@ -226,7 +225,8 @@ def test_links_on_edit_pages(self, current_user, app):
"fancy_type_resource.edit",
id=pkg["id"],
resource_id=res["id"],
- )
+ ),
+ environ_overrides={"REMOTE_USER": user["name"]},
).body
)
page_header = page.find(class_="page-header")
@@ -257,6 +257,7 @@ def test_links_on_edit_pages(self, current_user, app):
id=pkg["name"],
resource_id=res["id"],
),
+ environ_overrides={"REMOTE_USER": user["name"]},
data={"id": res["id"], "url": res["url"], "save": "go-metadata"},
follow_redirects=False,
)
| POST requests to API don't work with CSRF, tests bypass CSRF protection
**CKAN version**
2.10
**Describe the bug**
The API is completely unusable since https://github.com/ckan/ckan/pull/7058 was merged.
Any POST API call (and presumably PUT, DELETE etc) returns a `400 Bad Request: The CSRF token is missing` error, which in hindsight makes sense because we removed the `@csrf.exempt` decorator from the `api.action` endpoint. We'll need to see how we can implement:
* API call + Cookie authentication = CSRF enabled (to support current frontend API usage)
* API call + Header authentication = CSRF disabled (to support external API calls)
But more worryingly,I found out that the tests are happily ignoring all these issues, by bypassing CSRF protection entirely.
https://github.com/ckan/ckan/blob/367fed2fa572e896c5eb703db9c663e097133e41/ckan/tests/helpers.py#L271-L272
This might made sense while we were implementing the feature, but I think we need to discuss what we want going forward.
| 2022-09-22T11:16:26 |
|
ckan/ckan | 7,103 | ckan__ckan-7103 | [
"7075"
] | 367fed2fa572e896c5eb703db9c663e097133e41 | diff --git a/ckan/logic/action/update.py b/ckan/logic/action/update.py
--- a/ckan/logic/action/update.py
+++ b/ckan/logic/action/update.py
@@ -302,7 +302,7 @@ def package_update(
if hasattr(upload, 'mimetype'):
resource['mimetype'] = upload.mimetype
- if 'size' not in resource and 'url_type' in resource:
+ if 'url_type' in resource:
if hasattr(upload, 'filesize'):
resource['size'] = upload.filesize
| resource_patch does not update file size
**CKAN version**
2.9.5, probably others
**Describe the bug**
Updating an uploaded resource file through API does not update the resource's `size` field
**Steps to reproduce**
Steps to reproduce the behavior:
1. Create a dataset and a file upload resource
1. Observe the resource's `size` field value
1. Change the file through the UI
1. Observe the resource's `size` field value changes as it should
1. Use the action API to upload a new file with `resource_patch` (or `resource_update`, I assume)
1. Observe the resource's `size` field value stays the same
**Expected behavior**
The file size should reflect the uploaded file regardless of the method used to upload it
**Additional details**
I assume this is because the resource already has a `size` field when `resource_update` calls `package_update`, which assumes it is already set to the correct value. In `resource_create` the size is set, but `resource_update` just keeps the same value as before. Thus the new file size is not set.
| Looks like we need to remove the `if 'size' not in resource` here?
https://github.com/ckan/ckan/blob/97d48e1d5ad0c52ba7352baa155bb320c74f0ae6/ckan/logic/action/update.py#L305
Do you want to give it a go and submit a PR if it works @bzar ?
Hi @amercader @bzar , I would like to work on this issue.
@amercader seems to fix the issue with a quick test. Since @robin-NEC has not PR'd yet I'll do it. | 2022-09-23T10:05:30 |
|
ckan/ckan | 7,107 | ckan__ckan-7107 | [
"6684"
] | 8efb5af4ea0c040d11731e866d41ef179d9b60aa | diff --git a/ckan/lib/helpers.py b/ckan/lib/helpers.py
--- a/ckan/lib/helpers.py
+++ b/ckan/lib/helpers.py
@@ -655,7 +655,7 @@ def full_current_url() -> str:
@core_helper
def current_url() -> str:
''' Returns current url unquoted'''
- return unquote(request.environ['CKAN_CURRENT_URL'])
+ return request.environ['CKAN_CURRENT_URL']
@core_helper
diff --git a/ckan/views/__init__.py b/ckan/views/__init__.py
--- a/ckan/views/__init__.py
+++ b/ckan/views/__init__.py
@@ -190,8 +190,6 @@ def set_ckan_current_url(environ: Any) -> None:
qs = environ.get(u'QUERY_STRING')
if qs:
- # sort out weird encodings
- qs = quote(qs, u'')
environ[u'CKAN_CURRENT_URL'] = u'%s?%s' % (path_info, qs)
else:
environ[u'CKAN_CURRENT_URL'] = path_info
diff --git a/ckanext/datastore/backend/postgres.py b/ckanext/datastore/backend/postgres.py
--- a/ckanext/datastore/backend/postgres.py
+++ b/ckanext/datastore/backend/postgres.py
@@ -21,7 +21,7 @@
import six
from urllib.parse import (
- urlencode, unquote, urlunparse, parse_qsl, urlparse
+ urlencode, urlunparse, parse_qsl, urlparse
)
from io import StringIO
@@ -764,7 +764,7 @@ def _insert_links(data_dict: dict[str, Any], limit: int, offset: int):
# change the offset in the url
parsed = list(urlparse(urlstring))
- query = unquote(parsed[4])
+ query = parsed[4]
arguments = dict(parse_qsl(query))
arguments_start = dict(arguments)
| Helpers.current_url returns inconsistently quoted url, causing 500 errors.
**CKAN version**
Definitely 2.8, Probably 2.9, Not sure about master. Bug appears to have been added 5 years ago. Definitely on python2, maybe on python3.
**Describe the bug**
https://site/%EF%AC%81?foo=bar&bz=%AC%81
`ckan.config.middleware.__init__.py:handle_i18n` urlencodes the querystring, but this function is explictly not for querystrings, as it encodes the special characters. (it encodes & and =, so It's for things that go into urls and querystrings, not the whole querystring).
This urlencoded querystring gets added back into the current url, at which point we have a current "url" which is potentially not a valid url for anything in our system. As evidence for this, datastore/backend/postgres.py has added a patch to parse the returned url, unquote, and then reassemble.
Because of this, helpers.current_url returns a urldecoded version of the url, which is also not really something that we want to do, because that decodes the path component as well.
Now, once we're url decoding, we're taking it out of ascii and putting essentially arbitrary bytes through a unicode encode/decode process and potentially getting invalid UTF-8, or trying to put UTF-8 bytes into an ascii string, causing an error.
**Steps to reproduce**
Steps to reproduce the behavior:
Visit https://site/%EF%AC%81 and it returns a 500 error, not a 404. The path is the fi ligature.
**Expected behavior**
Return a 404, not a server error.
| 2022-09-27T14:43:31 |
||
ckan/ckan | 7,113 | ckan__ckan-7113 | [
"7102"
] | dc49cece33e447858d0008bc71b9a4ab724602ee | diff --git a/ckan/model/license.py b/ckan/model/license.py
--- a/ckan/model/license.py
+++ b/ckan/model/license.py
@@ -303,7 +303,7 @@ class LicenseOpenGovernment(DefaultLicense):
id = "uk-ogl"
od_conformance = 'approved'
# CS: bad_spelling ignore
- url = "http://reference.data.gov.uk/id/open-government-licence"
+ url = "https://www.nationalarchives.gov.uk/doc/open-government-licence/version/3/"
@property
def title(self):
| Hyperlink with the UK Open Government License does not work
**CKAN version**
2.9.5
**Describe the bug**
The link in the `license.py` under class `LicenseOpenGovernment`, stating (http://reference.data.gov.uk/id/open-government-licence) is now a non-existing page.
It is rendered on the dataset using the license, which is going to an invalid link.
Found the recent one should be provided by [The National Archives](https://www.nationalarchives.gov.uk/doc/open-government-licence)
**Steps to reproduce**
1. Have a dataset with uk-ogl license
2. Go to the package view page and the link for the license is there
**Expected behavior**
Expected reaching to a valid link, for example the [The National Archives](https://www.nationalarchives.gov.uk/doc/open-government-licence) one
**Additional details**
It is controlled under class `LicenseOpenGovernment` in `ckan > ckan > model > license.py`
| 2022-10-01T16:03:59 |
||
ckan/ckan | 7,118 | ckan__ckan-7118 | [
"7117"
] | 97e9916e4e3efac551f3ef6ac5db82a5d45d6161 | diff --git a/ckan/lib/app_globals.py b/ckan/lib/app_globals.py
--- a/ckan/lib/app_globals.py
+++ b/ckan/lib/app_globals.py
@@ -91,6 +91,14 @@ def set_theme(asset):
app_globals.theme = asset
+def set_main_css(css_file):
+ ''' Sets the main_css. The css_file must be of the form file.css '''
+ assert css_file.endswith('.css')
+ new_css = css_file
+ # FIXME we should check the css file exists
+ app_globals.main_css = str(new_css)
+
+
def set_app_global(key, value):
'''
Set a new key on the app_globals (g) object
@@ -181,6 +189,9 @@ def get_config_value(key, default=''):
# custom styling
theme = get_config_value('ckan.theme') or 'css/main'
set_theme(theme)
+ # legacy -- preserve for extensinos
+ main_css = get_config_value('ckan.main_css', '/base/css/main.css')
+ set_main_css(main_css)
if app_globals.site_logo:
app_globals.header_class = 'header-image'
diff --git a/ckan/lib/helpers.py b/ckan/lib/helpers.py
--- a/ckan/lib/helpers.py
+++ b/ckan/lib/helpers.py
@@ -691,6 +691,11 @@ def get_rtl_theme():
return config.get('ckan.i18n.rtl_theme', 'css/main-rtl')
+@core_helper
+def get_rtl_css():
+ return config.get('ckan.i18n.rtl_css', '/base/css/main-rtl.css')
+
+
class Message(object):
'''A message returned by ``Flash.pop_messages()``.
| Theme regression in 2.9.6
**CKAN version**
2.9.6
**Describe the bug**
On updating to ckan 2.9.6 from 2.9.5, an extension that used the app global main_css failed with a jinja template error:
```
ckan29 | {% asset main_css[6:-4] %}
ckan29 | jinja2.exceptions.UndefinedError: 'ckan.config.middleware.flask_app.CKAN_AppCtxGlobals object' has no attribute 'main_css'
```
Ref: https://github.com/ckan/ckan/commit/f9084f909538a963b1121d5cfb1e3a1485324add
**Steps to reproduce**
Steps to reproduce the behavior:
Have an extension that refers to the old `main_css` asset or `h.get_rtl_css`
**Expected behavior**
Not an error -- point releases should not remove portions of the publicly visible API.
| 2022-10-03T11:43:13 |
||
ckan/ckan | 7,122 | ckan__ckan-7122 | [
"7119"
] | d199d39d5e225ecbc4ee9c75418009226c7c8571 | diff --git a/ckan/lib/dictization/model_save.py b/ckan/lib/dictization/model_save.py
--- a/ckan/lib/dictization/model_save.py
+++ b/ckan/lib/dictization/model_save.py
@@ -66,8 +66,20 @@ def package_resource_list_save(
if res_dicts is None and allow_partial_update:
return
+ session = context['session']
+ model = context['model']
resource_list = package.resources_all
- old_list = package.resources_all[:]
+ # existing resources not marked as deleted - when removed these
+ # need to be kept in the db marked as deleted so that extensions like
+ # datastore have a chance to remove tables created for those resources
+ old_list = session.query(model.Resource) \
+ .filter(model.Resource.package_id == package.id) \
+ .filter(model.Resource.state != 'deleted')[:]
+ # resources previously deleted can be removed permanently as part
+ # of this update
+ deleted_list = session.query(model.Resource) \
+ .filter(model.Resource.package_id == package.id) \
+ .filter(model.Resource.state == 'deleted')[:]
obj_list = []
for res_dict in res_dicts or []:
@@ -87,6 +99,9 @@ def package_resource_list_save(
# according to their ordering in the obj_list.
resource_list[:] = obj_list
+ # Permanently remove old deleted resources
+ for resource in set(deleted_list) - set(obj_list):
+ resource.purge()
# Mark any left-over resources as deleted
for resource in set(old_list) - set(obj_list):
resource.state = 'deleted'
| package_update performance of repeated calls
**CKAN version**
all
**Describe the bug**
Repeated calls to `package_update` with a set of resources w/o consistent resource ids get slower over time
**Steps to reproduce**
For this test I used a dataset with 10 resources repeatedly submitted to `package_update`:
```json
{
"name": "10res",
"resources": [
{"url": "1"}, {"url": "2"}, {"url": "3"}, {"url": "4"}, {"url": "5"},
{"url": "6"}, {"url": "7"}, {"url": "8"}, {"url": "9"}, {"url": "10"}
]
}
```

- orig: time to complete on original ckan source
- filter: time to complete with filter applied (see below)
- purge: time to complete with resources purged (see below)
**Expected behavior**
ckan shouldn't get slower over time as resources are updated.
**Additional details**
filter patch:
This targets only the source of the slowness (iterating over all the deleted resources in python and resubmitting them with `state='deleted'` to postgres) and maintains the ever-growing list of deleted resources in the db
```patch
diff --git a/ckan/lib/dictization/model_save.py b/ckan/lib/dictization/model_save.py
index f4eff4427..c9cba0cc2 100644
--- a/ckan/lib/dictization/model_save.py
+++ b/ckan/lib/dictization/model_save.py
@@ -66,8 +66,12 @@ def package_resource_list_save(
if res_dicts is None and allow_partial_update:
return
+ session = context['session']
+ model = context['model']
resource_list = package.resources_all
- old_list = package.resources_all[:]
+ old_list = session.query(model.Resource) \
+ .filter(model.Resource.package_id == package.id) \
+ .filter(model.Resource.state != 'deleted')[:]
obj_list = []
for res_dict in res_dicts or []:
```
purge patch:
This solves the issue by purging resources that are removed in a package_update. This seems like a better solution because I can't think of any value in keeping these deleted resources in the db
```patch
diff --git a/ckan/lib/dictization/model_save.py b/ckan/lib/dictization/model_save.py
index f4eff4427..080e13ecc 100644
--- a/ckan/lib/dictization/model_save.py
+++ b/ckan/lib/dictization/model_save.py
@@ -89,8 +89,7 @@ def package_resource_list_save(
# Mark any left-over resources as deleted
for resource in set(old_list) - set(obj_list):
- resource.state = 'deleted'
- resource_list.append(resource)
+ resource.purge()
def package_extras_save(
```
| 2022-10-04T18:37:11 |
||
ckan/ckan | 7,125 | ckan__ckan-7125 | [
"7111"
] | 07669305decebaec827142cb26ecbd739473d2ab | diff --git a/ckan/views/group.py b/ckan/views/group.py
--- a/ckan/views/group.py
+++ b/ckan/views/group.py
@@ -425,6 +425,8 @@ def read(group_type: str,
extra_vars["q"] = q
+ limit = config.get(u'ckan.datasets_per_page', limit)
+
try:
# Do not query for the group datasets when dictizing, as they will
# be ignored and get requested on the controller anyway
| Is ckan.datasets_per_page not being used?
**CKAN version**
CKAN 2.9.5
**Describe the bug**
I set the _ckan.datasets_per_page_ configuration options to 10 and this is working fine on routes:
- /dataset/id
- /group
- /organization
But is not working in the routes*
- /group/id
- /organization/id
where it always shows 20 results per page. Reading through the source code I noticed that the _read_ function called in *those routes receives a _limit_ parameter with a default value of 20, but it is not updated in the function body with something like
```python
the_limit = config.get('ckan.datasets_per_page', limit)
```
I added this change in my local installation and it worked. Is this by design or is it a bug? I just want to be sure that this is a bug before opening a PR.
https://github.com/ckan/ckan/blob/dc49cece33e447858d0008bc71b9a4ab724602ee/ckan/views/group.py#L408-L411
Thanks.
| @ddazal That makes sense, want to submit a PR? | 2022-10-06T17:23:06 |
|
ckan/ckan | 7,132 | ckan__ckan-7132 | [
"7131"
] | 2448cd9784450ae87133f92e3e8fc5be36226ee1 | diff --git a/ckan/views/resource.py b/ckan/views/resource.py
--- a/ckan/views/resource.py
+++ b/ckan/views/resource.py
@@ -443,7 +443,7 @@ def get(self,
class DeleteView(MethodView):
- def _prepare(self, id: str):
+ def _prepare(self, resource_id: str):
context = cast(Context, {
u'model': model,
u'session': model.Session,
@@ -451,12 +451,14 @@ def _prepare(self, id: str):
u'auth_user_obj': current_user
})
try:
- check_access(u'package_delete', context, {u'id': id})
+ check_access(u'resource_delete', context, {u'id': resource_id})
except NotAuthorized:
return base.abort(
403,
- _(u'Unauthorized to delete package %s') % u''
+ _(u'Unauthorized to delete resource %s') % u''
)
+ except NotFound:
+ return base.abort(404, _(u'Resource not found'))
return context
def post(self, package_type: str, id: str, resource_id: str) -> Response:
@@ -465,7 +467,7 @@ def post(self, package_type: str, id: str, resource_id: str) -> Response:
u'{}_resource.edit'.format(package_type),
resource_id=resource_id, id=id
)
- context = self._prepare(id)
+ context = self._prepare(resource_id)
try:
get_action(u'resource_delete')(context, {u'id': resource_id})
@@ -487,7 +489,7 @@ def post(self, package_type: str, id: str, resource_id: str) -> Response:
return base.abort(404, _(u'Resource not found'))
def get(self, package_type: str, id: str, resource_id: str) -> str:
- context = self._prepare(id)
+ context = self._prepare(resource_id)
try:
resource_dict = get_action(u'resource_show')(
context, {
| diff --git a/ckan/tests/controllers/test_package.py b/ckan/tests/controllers/test_package.py
--- a/ckan/tests/controllers/test_package.py
+++ b/ckan/tests/controllers/test_package.py
@@ -1408,7 +1408,7 @@ def test_logged_in_users_cannot_delete_resources_they_do_not_own(
extra_environ=env
)
assert 403 == response.status_code
- assert helpers.body_contains(response, "Unauthorized to delete package")
+ assert helpers.body_contains(response, "Unauthorized to delete resource")
def test_sysadmins_can_delete_any_resource(self, app, sysadmin):
owner_org = factories.Organization()
| Resource DeleteView uses package_delete auth function
**CKAN version**
2.9.6
**Describe the bug**
Allowing deleting resources but not packages is not possible, because https://github.com/ckan/ckan/blob/9f1b5cfaff8c135b589e2ea0275f1286c2e02711/ckan/views/resource.py#L454 checks `package_delete`.
**Steps to reproduce**
Steps to reproduce the behavior:
- Override `package_delete` and `resource_delete` auth functions with a plugin to create a situation where you can delete a resource in a package but not the package itsef
- Navigate to the resource's edit view
- Observe the delete button existing
- Try to delete the resource
- Observe `403 Forbidden: Unauthorized to delete package`
**Expected behavior**
`resource_delete` auth function defining if a resource can be deleted
**Additional details**
Should be fixable by just changing the auth function. I'll make a PR.
| 2022-10-11T11:58:53 |
|
ckan/ckan | 7,135 | ckan__ckan-7135 | [
"7134"
] | 2448cd9784450ae87133f92e3e8fc5be36226ee1 | diff --git a/ckan/migration/versions/104_9f33a0280c51_resource_view_resource_id_index.py b/ckan/migration/versions/104_9f33a0280c51_resource_view_resource_id_index.py
new file mode 100644
--- /dev/null
+++ b/ckan/migration/versions/104_9f33a0280c51_resource_view_resource_id_index.py
@@ -0,0 +1,27 @@
+# encoding: utf-8
+
+"""resource_view resource_id index
+
+Revision ID: 9f33a0280c51
+Revises: 353aaf2701f0
+Create Date: 2022-10-11 02:31:35.941858
+
+"""
+from alembic import op
+
+
+# revision identifiers, used by Alembic.
+revision = '9f33a0280c51'
+down_revision = '353aaf2701f0'
+branch_labels = None
+depends_on = None
+
+
+def upgrade():
+ op.create_index(
+ u'idx_view_resource_id', u'resource_view', [u'resource_id']
+ )
+
+
+def downgrade():
+ op.drop_index(u'idx_view_resource_id')
| Add an index in table resource_view to improve DB performance
**CKAN version**
2.9.6, master
**Describe the bug**
Table `resource_view` needs a index on column `resource_id`.
**Steps to reproduce**
In a big CKAN database (500k packages) run the query
```
begin;
explain (analyze,buffers,timing)
delete from resource where package_id = [###];
rollback;
...
Trigger for constraint resource_view_resource_id_fkey: time=68.124 calls=6
```
**Expected behavior**
```
CREATE INDEX idx_view_resource_id
ON resource_view(resource_id);
```
After the index added, the time dropped from **68.124** to **0.420**, that is 170 times faster.
**Additional details**
This will greatly reduce time spent when clearing a big harvest source.
| 2022-10-11T15:54:33 |
||
ckan/ckan | 7,167 | ckan__ckan-7167 | [
"7166"
] | 6b1821791d4d2287f0d16945b6d2df23955a42e8 | diff --git a/ckan/plugins/core.py b/ckan/plugins/core.py
--- a/ckan/plugins/core.py
+++ b/ckan/plugins/core.py
@@ -157,7 +157,7 @@ def __init__(self, *args: Any, **kwargs: Any):
["after_search", "after_dataset_search"],
["before_index", "before_dataset_index"],
["before_view", "before_dataset_view"]]:
- if hasattr(self, old_name):
+ if hasattr(self, old_name) and not hasattr(self, new_name):
msg = (
f"The method 'IPackageController.{old_name}' is "
+ f"deprecated. Please use '{new_name}' instead!"
@@ -175,7 +175,7 @@ def __init__(self, *args: Any, **kwargs: Any):
["before_delete", "before_resource_delete"],
["after_delete", "after_resource_delete"],
["before_show", "before_resource_show"]]:
- if hasattr(self, old_name):
+ if hasattr(self, old_name) and not hasattr(self, new_name):
msg = (
f"The method 'IResourceController.{old_name}' is "
+ f"deprecated. Please use '{new_name}' instead!"
| allow plugins to implent old and new method names
**CKAN version**
master, 2.10
**Describe the bug**
In the past it has been possible for plugins to implement both the old and new names of methods, but since #7148 the new method gets overwritten by the old method.
**Steps to reproduce**
Use e.g. scheming_nerf_index plugin which implements both `before_index` and `before_dataset_index` for compatibility
**Expected behavior**
Not an infinite loop :upside_down_face:
**Additional details**
| 2022-10-31T15:25:07 |
||
ckan/ckan | 7,219 | ckan__ckan-7219 | [
"7119"
] | 7126c4c6b0397f3338abd8e24b79a28b7aac3b17 | diff --git a/ckan/lib/dictization/model_save.py b/ckan/lib/dictization/model_save.py
--- a/ckan/lib/dictization/model_save.py
+++ b/ckan/lib/dictization/model_save.py
@@ -59,8 +59,15 @@ def package_resource_list_save(res_dicts, package, context):
if res_dicts is None and allow_partial_update:
return
+ session = context['session']
+ model = context['model']
resource_list = package.resources_all
- old_list = package.resources_all[:]
+ old_list = session.query(model.Resource) \
+ .filter(model.Resource.package_id == package.id) \
+ .filter(model.Resource.state != 'deleted')[:]
+ deleted_list = session.query(model.Resource) \
+ .filter(model.Resource.package_id == package.id) \
+ .filter(model.Resource.state == 'deleted')[:]
obj_list = []
for res_dict in res_dicts or []:
@@ -80,6 +87,9 @@ def package_resource_list_save(res_dicts, package, context):
# according to their ordering in the obj_list.
resource_list[:] = obj_list
+ # Permanently remove old deleted resources
+ for resource in set(deleted_list) - set(obj_list):
+ resource.purge()
# Mark any left-over resources as deleted
for resource in set(old_list) - set(obj_list):
resource.state = 'deleted'
| package_update performance of repeated calls
**CKAN version**
all
**Describe the bug**
Repeated calls to `package_update` with a set of resources w/o consistent resource ids get slower over time
**Steps to reproduce**
For this test I used a dataset with 10 resources repeatedly submitted to `package_update`:
```json
{
"name": "10res",
"resources": [
{"url": "1"}, {"url": "2"}, {"url": "3"}, {"url": "4"}, {"url": "5"},
{"url": "6"}, {"url": "7"}, {"url": "8"}, {"url": "9"}, {"url": "10"}
]
}
```

- orig: time to complete on original ckan source
- filter: time to complete with filter applied (see below)
- purge: time to complete with resources purged (see below)
**Expected behavior**
ckan shouldn't get slower over time as resources are updated.
**Additional details**
filter patch:
This targets only the source of the slowness (iterating over all the deleted resources in python and resubmitting them with `state='deleted'` to postgres) and maintains the ever-growing list of deleted resources in the db
```patch
diff --git a/ckan/lib/dictization/model_save.py b/ckan/lib/dictization/model_save.py
index f4eff4427..c9cba0cc2 100644
--- a/ckan/lib/dictization/model_save.py
+++ b/ckan/lib/dictization/model_save.py
@@ -66,8 +66,12 @@ def package_resource_list_save(
if res_dicts is None and allow_partial_update:
return
+ session = context['session']
+ model = context['model']
resource_list = package.resources_all
- old_list = package.resources_all[:]
+ old_list = session.query(model.Resource) \
+ .filter(model.Resource.package_id == package.id) \
+ .filter(model.Resource.state != 'deleted')[:]
obj_list = []
for res_dict in res_dicts or []:
```
purge patch:
This solves the issue by purging resources that are removed in a package_update. This seems like a better solution because I can't think of any value in keeping these deleted resources in the db
```patch
diff --git a/ckan/lib/dictization/model_save.py b/ckan/lib/dictization/model_save.py
index f4eff4427..080e13ecc 100644
--- a/ckan/lib/dictization/model_save.py
+++ b/ckan/lib/dictization/model_save.py
@@ -89,8 +89,7 @@ def package_resource_list_save(
# Mark any left-over resources as deleted
for resource in set(old_list) - set(obj_list):
- resource.state = 'deleted'
- resource_list.append(resource)
+ resource.purge()
def package_extras_save(
```
| 2022-11-17T20:18:45 |
||
ckan/ckan | 7,223 | ckan__ckan-7223 | [
"7222"
] | 192d176cfd88aa7b5b9ff93cdb1fa35d8b783135 | diff --git a/ckan/common.py b/ckan/common.py
--- a/ckan/common.py
+++ b/ckan/common.py
@@ -128,6 +128,9 @@ def __delitem__(self, key: str):
except RuntimeError:
pass
+ def is_declared(self, key: str) -> bool:
+ return key in config_declaration
+
def get_value(self, key: str) -> Any:
if self.get("config.mode") == "strict":
return self[key]
diff --git a/ckan/config/declaration/__init__.py b/ckan/config/declaration/__init__.py
--- a/ckan/config/declaration/__init__.py
+++ b/ckan/config/declaration/__init__.py
@@ -64,7 +64,7 @@ def __init__(self):
def __bool__(self):
return bool(self._members)
- def __contains__(self, key: Key):
+ def __contains__(self, key: Union[Key, str]):
return key in self._options
def __getitem__(self, key: Key) -> Option[Any]:
diff --git a/ckan/config/middleware/flask_app.py b/ckan/config/middleware/flask_app.py
--- a/ckan/config/middleware/flask_app.py
+++ b/ckan/config/middleware/flask_app.py
@@ -163,7 +163,16 @@ def make_flask_stack(conf: Union[Config, CKANConfig]) -> CKANApp:
# Update Flask config with the CKAN values. We use the common config
# object as values might have been modified on `load_environment`
if config:
- app.config.update(config)
+ if config.get_value("config.mode") == "strict":
+ # Config values have been already parsed and validated
+ app.config.update(config)
+ else:
+ # Parse all values to ensure Flask gets the validated values
+ for key in config.keys():
+ if config.is_declared(key):
+ app.config[key] = config.get_value(key)
+ else:
+ app.config[key] = config.get(key)
else:
app.config.update(conf)
| diff --git a/ckan/tests/config/test_middleware.py b/ckan/tests/config/test_middleware.py
--- a/ckan/tests/config/test_middleware.py
+++ b/ckan/tests/config/test_middleware.py
@@ -93,3 +93,18 @@ def test_all_plugin_blueprints_are_registered(app):
assert url == "/another_simple_url"
res = app.get(url, status=200)
assert "Hello World, this is another view served from an extension" in res.body
+
+
[email protected]_config("REMEMBER_COOKIE_DURATION", "12345")
+def test_flask_config_values_are_parsed(app):
+ assert (
+ app.flask_app.config["REMEMBER_COOKIE_DURATION"] == 12345
+ )
+
+
[email protected]_config("config.mode", "strict")
[email protected]_config("REMEMBER_COOKIE_DURATION", "12345")
+def test_flask_config_values_are_parsed_in_strict_mode(app):
+ assert (
+ app.flask_app.config["REMEMBER_COOKIE_DURATION"] == 12345
+ )
| Exception on a fresh install / no session when trying to login
**CKAN version**
master/2.10
**Describe the bug**
On a fresh install, if `REMEMBER_COOKIE_DURATION` is set in the ini file I get an exception trying to login
```
Traceback (most recent call last):
File "/home/adria/dev/pyenvs/ckan-py3/lib/python3.8/site-packages/flask_login/login_manager.py", line 476, in _set_cookie
expires = datetime.utcnow() + duration
TypeError: unsupported operand type(s) for +: 'datetime.datetime' and 'str'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/adria/dev/pyenvs/ckan-py3/lib/python3.8/site-packages/flask/app.py", line 1540, in finalize_request
response = self.process_response(response)
File "/home/adria/dev/pyenvs/ckan-py3/lib/python3.8/site-packages/flask/app.py", line 1885, in process_response
response = self.ensure_sync(func)(response)
File "/home/adria/dev/pyenvs/ckan-py3/lib/python3.8/site-packages/flask_login/login_manager.py", line 447, in _update_remember_cookie
self._set_cookie(response)
File "/home/adria/dev/pyenvs/ckan-py3/lib/python3.8/site-packages/flask_login/login_manager.py", line 478, in _set_cookie
raise Exception(
Exception: REMEMBER_COOKIE_DURATION must be a datetime.timedelta, instead got: 31536000
```
**Steps to reproduce**
* Add `REMEMBER_COOKIE_DURATION = 31536000` to your ini file
* Delete the sessions folder in `/tmp/<ckan.site_id>`
* Try to login
**Additional details**
Based on the stack trace complaining about `duration` being a str, I guess that the problem is that we are passing raw config values to Flask's `app.config` object instead of parsed ones or something along those lines
| 2022-11-18T15:00:26 |
|
ckan/ckan | 7,241 | ckan__ckan-7241 | [
"7225"
] | 4810f792edf2fe901da461572aa925395eab04ca | diff --git a/ckan/cli/clean.py b/ckan/cli/clean.py
new file mode 100644
--- /dev/null
+++ b/ckan/cli/clean.py
@@ -0,0 +1,94 @@
+# encoding: utf-8
+
+import click
+import magic
+import os
+
+from typing import List
+
+from ckan import model
+from ckan import logic
+from ckan.common import config
+from ckan.lib.uploader import get_uploader
+from ckan.types import Context
+
+
[email protected](short_help="Provide commands to clean entities from the database")
[email protected]_option("-h", "--help")
+def clean():
+ pass
+
+
+def _get_users_with_invalid_image(mimetypes: List[str]) -> List[model.User]:
+ """Returns a list of users containing images with mimetypes not supported.
+ """
+ users = model.User.all()
+ users_with_img = [u for u in users if u.image_url]
+ invalid = []
+ for user in users_with_img:
+ upload = get_uploader("user", old_filename=user.image_url)
+ filepath = upload.old_filepath # type: ignore
+ if os.path.exists(filepath):
+ mimetype = magic.from_file(filepath, mime=True)
+ if mimetype not in mimetypes:
+ invalid.append(user)
+ return invalid
+
+
[email protected]("users", short_help="Clean users containing invalid images.")
[email protected](
+ "-f", "--force", is_flag=True, help="Do not ask for comfirmation."
+)
+def users(force: bool):
+ """Removes users with invalid images from the database.
+
+ Invalid images are the ones with mimetypes not defined in
+ `ckan.upload.user.mimetypes` configuration option.
+
+ This command will work only for CKAN's default Upload, other
+ extensions defining upload interfaces will need to implement its
+ own logic to retrieve and determine if an uploaded image contains
+ an invalid mimetype.
+
+ Example:
+
+ ckan clean users
+ ckan clean users --force
+
+ """
+ mimetypes = config.get_value("ckan.upload.user.mimetypes")
+ if not mimetypes:
+ click.echo("No mimetypes have been configured for user uploads.")
+ return
+
+ invalid = _get_users_with_invalid_image(mimetypes)
+
+ if not invalid:
+ click.echo("No users were found with invalid images.")
+ return
+
+ for user in invalid:
+ msg = "User {} has an invalid image: {}".format(
+ user.name, user.image_url
+ )
+ click.echo(msg)
+
+ if not force:
+ click.confirm("Permanently delete users and their images?", abort=True)
+
+ site_user = logic.get_action("get_site_user")({"ignore_auth": True}, {})
+ context: Context = {"user": site_user["name"]}
+
+ for user in invalid:
+ upload = get_uploader("user", old_filename=user.image_url)
+ file_path = upload.old_filepath # type: ignore
+ try:
+ os.remove(file_path)
+ except Exception:
+ msg = "Cannot remove {}. User will not be deleted.".format(
+ file_path
+ )
+ click.echo(msg)
+ else:
+ logic.get_action("user_delete")(context, {"id": user.name})
+ click.secho("Deleted user: %s" % user.name, fg="green", bold=True)
diff --git a/ckan/cli/cli.py b/ckan/cli/cli.py
--- a/ckan/cli/cli.py
+++ b/ckan/cli/cli.py
@@ -16,6 +16,7 @@
from . import (
asset,
config,
+ clean,
dataset,
db, search_index, server,
generate,
@@ -229,3 +230,4 @@ def ckan():
ckan.add_command(user.user)
ckan.add_command(views.views)
ckan.add_command(shell.shell)
+ckan.add_command(clean.clean)
diff --git a/ckan/cli/user.py b/ckan/cli/user.py
--- a/ckan/cli/user.py
+++ b/ckan/cli/user.py
@@ -7,7 +7,6 @@
import six
import click
-
import ckan.logic as logic
import ckan.model as model
from ckan.cli import error_shout
| diff --git a/ckan/tests/cli/test_clean.py b/ckan/tests/cli/test_clean.py
new file mode 100644
--- /dev/null
+++ b/ckan/tests/cli/test_clean.py
@@ -0,0 +1,89 @@
+# -*- coding: utf-8 -*-
+import pytest
+
+from ckan.cli.cli import ckan
+from ckan.tests.helpers import call_action
+
+
[email protected]("clean_db")
+class TestUserClean:
+ def test_output_if_there_are_not_invalid_users(self, cli):
+ result = cli.invoke(ckan, ["clean", "users"])
+ assert "No users were found with invalid images." in result.output
+
+ @pytest.mark.ckan_config("ckan.upload.user.mimetypes", "")
+ @pytest.mark.ckan_config("ckan.upload.user.types", "")
+ def test_confirm_dialog_if_no_force(
+ self, cli, monkeypatch, create_with_upload, faker, ckan_config
+ ):
+ fake_user = {
+ "name": "fake-user",
+ "email": "[email protected]",
+ "password": "12345678",
+ "action": "user_create",
+ "upload_field_name": "image_upload",
+ }
+ fake_user = create_with_upload(
+ "<html><body>hello world</body></html>", "index.html", **fake_user
+ )
+
+ user = {
+ "name": "valid-user",
+ "email": "valid-user@example",
+ "password": "12345678",
+ "action": "user_create",
+ "upload_field_name": "image_upload",
+ }
+ user = create_with_upload(faker.image(), "image.png", **user)
+
+ monkeypatch.setitem(
+ ckan_config, "ckan.upload.user.mimetypes", "image/png"
+ )
+ result = cli.invoke(ckan, ["clean", "users"])
+
+ assert (
+ f"User {fake_user['name']} has an invalid image:"
+ f" {fake_user['image_url']}"
+ in result.output
+ )
+ assert (
+ f"User {user['name']} has an invalid image: {user['image_url']}"
+ not in result.output
+ )
+ assert "Permanently delete users and their images?" in result.output
+ users = call_action("user_list")
+ assert len(users) == 2
+
+ @pytest.mark.ckan_config("ckan.upload.user.mimetypes", "")
+ @pytest.mark.ckan_config("ckan.upload.user.types", "")
+ def test_correct_users_are_deleted(
+ self, cli, monkeypatch, create_with_upload, faker, ckan_config
+ ):
+ fake_user = {
+ "name": "fake-user",
+ "email": "[email protected]",
+ "password": "12345678",
+ "action": "user_create",
+ "upload_field_name": "image_upload",
+ }
+ fake_user = create_with_upload(
+ "<html><body>hello world</body></html>", "index.html", **fake_user
+ )
+
+ user = {
+ "name": "valid-user",
+ "email": "valid-user@example",
+ "password": "12345678",
+ "action": "user_create",
+ "upload_field_name": "image_upload",
+ }
+ user = create_with_upload(faker.image(), "image.png", **user)
+
+ monkeypatch.setitem(
+ ckan_config, "ckan.upload.user.mimetypes", "image/png"
+ )
+ result = cli.invoke(ckan, ["clean", "users", "--force"])
+ users = call_action("user_list")
+ assert f"Deleted user: {fake_user['name']}" in result.output
+ assert len(users) == 1
+ assert users[0]["name"] == "valid-user"
| User clean up command
Some auth configurations can lead to the creation of spam user account. Default changes in #7208 will hopefully make more difficult for maintainers to end up in this situation but we can also provide a small command to cleanup spam user accounts.
The logic should be:
* Filter any user accounts that
1. Has a value for `image_url`
2. The file referenced in `image_url` does not match one of the ones allowed by `ckan.uploads.user.mimetypes`
* Ask user to confirm (unless the `-f / --force` flag is passed) showing a list of the accounts that will be deleted (if admins want to keep one they can update the image_url value)
* Delete the user object and the linked uploaded file
Where should this command be available?
1. Keep it on `ckan user clean` or something similar
2. Add a new `ckan clean ....` or `ckan cleanup ...` command that we can later expand to eg purge datasets / orgs, delete old activities etc
Any thoughts?
| 2022-11-26T10:22:36 |
|
ckan/ckan | 7,279 | ckan__ckan-7279 | [
"7247"
] | f6b552878d6f1912462aedd83a0fb9cc2bae1513 | diff --git a/ckanext/datapusher/plugin.py b/ckanext/datapusher/plugin.py
--- a/ckanext/datapusher/plugin.py
+++ b/ckanext/datapusher/plugin.py
@@ -37,6 +37,8 @@ class DatapusherPlugin(p.SingletonPlugin):
def update_config(self, config: CKANConfig):
templates_base = config.get_value(u'ckan.base_templates_folder')
p.toolkit.add_template_directory(config, templates_base)
+ p.toolkit.add_public_directory(config, 'public')
+ p.toolkit.add_resource('assets', 'ckanext-datapusher')
def configure(self, config: CKANConfig):
self.config = config
| UI broken in Resource DataStore tab
**CKAN version**
2.10/master
**Describe the bug**
Missing icons and misaligned

| Probably a similar fix as https://github.com/ckan/ckan/pull/7169
A little bit more of context: The problem here is that the timeline depends on a css class `activity` that is no longer available in CKAN core since it has been moved to the `activity` extension.
The solution is to rebuild the html/css of the timeline to look similar to the activity stream. #7169 contains the `css` class removed and how to fix the icon display using Font Awesome stack (https://fontawesome.com/docs/web/style/stack).
This change should be done in datapusher extension (and if time, also xloader one.)
To summarise:
- `datapusher` extension should contain all the CSS files required to display that log timeline properly (either by mimicking activity's CSS or building a new one)
- `xloader` will have the same issue, but that should be fixed in its repository.
### Notes on the extensions
* Both `xloader` and `datapusher` define a new view called `resource_data` that is going to render `resource_data.html`. This template {% extends "package/resource_edit_base.html" %}. (in both extensions) Neither extension overrides any other template. They just have the same behaviour (A view rendering a template with the same name). So `xloader` **is not** overriding `datapusher` template it just render a similar template in the same position.
* `xloader` is a replacement for `datapusher` so only one should be available at the time. If the two are active, then two Datastore tabs are gonna be displayed. This is a side effect of both extension having a similar behaviour (defining a view and rendering a template in the same location). | 2022-12-15T04:03:20 |
|
ckan/ckan | 7,309 | ckan__ckan-7309 | [
"7199"
] | f93998cb08ac46e2f63318040c8a4a2ad4837559 | diff --git a/ckan/cli/sass.py b/ckan/cli/sass.py
--- a/ckan/cli/sass.py
+++ b/ckan/cli/sass.py
@@ -11,21 +11,32 @@
@click.command(
- name=u'sass',
- short_help=u'Compile all root sass documents into their CSS counterparts')
-def sass():
- command = (u'npm', u'run', u'build')
-
- public = config.get_value(u'ckan.base_public_folder')
-
- root = os.path.join(os.path.dirname(__file__), u'..', public, u'base')
+ name='sass',
+ short_help='Compile all root sass documents into their CSS counterparts')
[email protected](
+ '-d',
+ '--debug',
+ is_flag=True,
+ help="Compile css with sourcemaps.")
+def sass(debug: bool):
+ command = ('npm', 'run', 'build')
+
+ public = config.get_value('ckan.base_public_folder')
+
+ root = os.path.join(os.path.dirname(__file__), '..', public, 'base')
root = os.path.abspath(root)
- _compile_sass(root, command, u'main')
-
-
-def _compile_sass(root: str, command: tuple[str, ...], color: str):
- click.echo(u'compile {}.css'.format(color))
- command = command + (u'--', u'--' + color)
+ _compile_sass(root, command, 'main', debug)
+
+
+def _compile_sass(
+ root: str,
+ command: tuple[str, ...],
+ color: str,
+ debug: bool):
+ click.echo('compile {}.css'.format(color))
+ command = command + ('--', '--' + color)
+ if debug:
+ command = command + ('--debug',)
process = subprocess.Popen(
command,
| White on Yellow?? Color Contrast
**CKAN version**
https://demo.ckan.org/en/user/edit/mgifford
**Describe the bug**
Title: WCAG 1.4.3: Ensures the contrast between foreground and background colors meets WCAG 2 AA contrast ratio thresholds (.btn-warning)
Tags: Accessibility, WCAG 1.4.3, color-contrast
Issue: Ensures the contrast between foreground and background colors meets WCAG 2 AA contrast ratio thresholds (color-contrast - https://accessibilityinsights.io/info-examples/web/color-contrast)
Target application: Manage - mgifford - Users - CKAN Demo - https://demo.ckan.org/en/user/edit/mgifford
Element path: .btn-warning
Snippet: <a class="btn btn-warning" href="/en/user/generate_key/b8037a86-a216-4c9b-8211-e197fa09143a" data-module="confirm-action" data-module-content="Are you sure you want to regenerate the API key?">Regenerate API Key</a>
How to fix:
Fix any of the following:
Element has insufficient color contrast of 1.94 (foreground color: #ffffff, background color: #f0ad4e, font size: 10.5pt (14px), font weight: bold). Expected contrast ratio of 4.5:1
Environment: Microsoft Edge version 107.0.1418.35
====
This accessibility issue was found using Accessibility Insights for Web 2.35.0 (axe-core 4.4.1), a tool that helps find and fix accessibility issues. Get more information & download this tool at http://aka.ms/AccessibilityInsights.
| 2023-01-05T03:32:50 |
||
ckan/ckan | 7,353 | ckan__ckan-7353 | [
"7352"
] | 0fd774dd5e2e81d9baec4ab9dd2d4aff7cc5e01d | diff --git a/ckan/config/middleware/flask_app.py b/ckan/config/middleware/flask_app.py
--- a/ckan/config/middleware/flask_app.py
+++ b/ckan/config/middleware/flask_app.py
@@ -262,7 +262,10 @@ def make_flask_stack(conf: Union[Config, CKANConfig]) -> CKANApp:
_register_error_handler(app)
# CSRF
- app.config['WTF_CSRF_FIELD_NAME'] = "_csrf_token"
+ wtf_key = "WTF_CSRF_SECRET_KEY"
+ if not app.config.get(wtf_key):
+ config[wtf_key] = app.config[wtf_key] = app.config["SECRET_KEY"]
+ app.config["WTF_CSRF_FIELD_NAME"] = "_csrf_token"
csrf.init_app(app)
# Set up each IBlueprint extension as a Flask Blueprint
| diff --git a/ckan/tests/config/test_middleware.py b/ckan/tests/config/test_middleware.py
--- a/ckan/tests/config/test_middleware.py
+++ b/ckan/tests/config/test_middleware.py
@@ -100,3 +100,13 @@ def test_flask_config_values_are_parsed(app):
assert (
app.flask_app.config["REMEMBER_COOKIE_DURATION"] == 12345
)
+
+
[email protected]_config("WTF_CSRF_SECRET_KEY", None)
+def test_no_wtf_secret_falls_back_to_secret_key(app):
+ assert (
+ app.flask_app.config["WTF_CSRF_SECRET_KEY"] == config.get("beaker.session.secret")
+ )
+ assert (
+ config["WTF_CSRF_SECRET_KEY"] == config.get("beaker.session.secret")
+ )
| No default for WTF_CSRF_SECRET_KEY config option
## CKAN version
2.10
## Describe the bug
The `WTF_CSRF_SECRET_KEY` config option, used to generate the CSRF tokens is defined as such in the declaration:
https://github.com/ckan/ckan/blob/9e60350f27c9266b5afbd741484265c5e06a2d38/ckan/config/config_declaration.yaml#L645-L647
This means that when a new ini file is generated, a secret value is added to the ini file by default, but when that config option is not defined in an ini file (ie you are using an ini file generated with a previous version of CKAN when upgrading your instance) the default value is `None`.
This causes the app to fail on all requests with:
```
File "/home/adria/dev/pyenvs/ckan-py3/src/ckan/ckan/templates/base.html", line 27, in block 'meta'
<meta name="{{ g.csrf_field_name }}" content="{{ csrf_token() }}" />
File "/home/adria/dev/pyenvs/ckan-py3/lib/python3.8/site-packages/flask_wtf/csrf.py", line 36, in generate_csrf
secret_key = _get_config(
File "/home/adria/dev/pyenvs/ckan-py3/lib/python3.8/site-packages/flask_wtf/csrf.py", line 136, in _get_config
raise RuntimeError(message)
RuntimeError: A secret key is required to use CSRF.
```
That's because wtforms falls back to Flask's `SECRET_KEY` only if `WTF_CSRF_SECRET_KEY` is not present in the config, but we add it to the config, just empty.
This setting should have either be checked at startup to see if it's set or fallback to a default like we do with the rest of the secret keys (I prefer the latter)
| We need to come up with a consistent approach to handle secrets and their defaults, I'll raise that in a separate issue | 2023-01-24T10:44:03 |
ckan/ckan | 7,357 | ckan__ckan-7357 | [
"7356"
] | 978875e41643b53fc2c714b2264f32e502db3f8d | diff --git a/ckanext/datastore/backend/__init__.py b/ckanext/datastore/backend/__init__.py
--- a/ckanext/datastore/backend/__init__.py
+++ b/ckanext/datastore/backend/__init__.py
@@ -29,7 +29,9 @@ def get_all_resources_ids_in_datastore() -> list[str]:
def _parse_sort_clause( # type: ignore
clause: str, fields_types: Container[str]):
- clause_match = re.match(u'^(.+?)( +(asc|desc) *)?$', clause, re.I)
+ clause_match = re.match(
+ u'^(.+?)( +(asc|desc))?( nulls +(first|last) *)?$', clause, re.I
+ )
if not clause_match:
return False
@@ -38,6 +40,8 @@ def _parse_sort_clause( # type: ignore
if field[0] == field[-1] == u'"':
field = field[1:-1]
sort = (clause_match.group(3) or u'asc').lower()
+ if clause_match.group(4):
+ sort += (clause_match.group(4)).lower()
if field not in fields_types:
return False
diff --git a/ckanext/datastore/logic/action.py b/ckanext/datastore/logic/action.py
--- a/ckanext/datastore/logic/action.py
+++ b/ckanext/datastore/logic/action.py
@@ -473,7 +473,7 @@ def datastore_search(context: Context, data_dict: dict[str, Any]):
(optional, default: all fields in original order)
:type fields: list or comma separated string
:param sort: comma separated field names with ordering
- e.g.: "fieldname1, fieldname2 desc"
+ e.g.: "fieldname1, fieldname2 desc nulls last"
:type sort: string
:param include_total: True to return total matching record count
(optional, default: true)
| diff --git a/ckanext/datastore/tests/test_search.py b/ckanext/datastore/tests/test_search.py
--- a/ckanext/datastore/tests/test_search.py
+++ b/ckanext/datastore/tests/test_search.py
@@ -453,6 +453,31 @@ def test_search_filter_with_percent_in_column_name(self):
result = helpers.call_action("datastore_search", **search_data)
assert result["total"] == 1
+ @pytest.mark.ckan_config("ckan.plugins", "datastore")
+ @pytest.mark.usefixtures("clean_datastore", "with_plugins")
+ def test_search_sort_nulls_first_last(self):
+ resource = factories.Resource()
+ data = {
+ "resource_id": resource["id"],
+ "force": True,
+ "records": [{"a": 1, "b": "Y"}, {"b": "Z"}],
+ }
+ helpers.call_action("datastore_create", **data)
+
+ search_data = {
+ "resource_id": data["resource_id"],
+ "sort": [u"a desc nulls last"],
+ }
+ result = helpers.call_action("datastore_search", **search_data)
+ assert result["records"][0]['b'] == 'Y'
+
+ search_data = {
+ "resource_id": data["resource_id"],
+ "sort": [u"a desc nulls first"],
+ }
+ result = helpers.call_action("datastore_search", **search_data)
+ assert result["records"][0]['b'] == 'Z'
+
@pytest.mark.usefixtures("with_request_context")
class TestDatastoreSearchLegacyTests(object):
| datastore sort: nulls first/last
## CKAN version
master
## Describe the bug
we should be able to sort null values in datastore last
### Steps to reproduce
add "nulls last" to a datastore_search sort parameter
### Expected behavior
nulls last
### Additional details
| 2023-01-25T20:53:59 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.