-
Notifications
You must be signed in to change notification settings - Fork 2k
/
base.py
630 lines (545 loc) · 24.6 KB
/
base.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
"""The base Controller API
Provides the BaseController class for subclassing.
"""
from datetime import datetime
from hashlib import md5
import logging
import os
import urllib
import time
from paste.deploy.converters import asbool
from pylons import c, cache, config, g, request, response, session
from pylons.controllers import WSGIController
from pylons.controllers.util import abort as _abort
from pylons.controllers.util import redirect_to, redirect
from pylons.decorators import jsonify, validate
from pylons.i18n import _, ungettext, N_, gettext, ngettext
from pylons.templating import cached_template, pylons_globals
from genshi.template import MarkupTemplate
from genshi.template.base import TemplateSyntaxError
from genshi.template.text import NewTextTemplate
from webhelpers.html import literal
import ckan.exceptions
import ckan
import ckan.authz as authz
from ckan.lib import i18n
import lib.render
import ckan.lib.helpers as h
import ckan.lib.app_globals as app_globals
from ckan.plugins import PluginImplementations, IGenshiStreamFilter
from ckan.lib.helpers import json
import ckan.model as model
log = logging.getLogger(__name__)
PAGINATE_ITEMS_PER_PAGE = 50
APIKEY_HEADER_NAME_KEY = 'apikey_header_name'
APIKEY_HEADER_NAME_DEFAULT = 'X-CKAN-API-Key'
ALLOWED_FIELDSET_PARAMS = ['package_form', 'restrict']
def abort(status_code=None, detail='', headers=None, comment=None):
if detail and status_code != 503:
h.flash_error(detail)
# #1267 Convert detail to plain text, since WebOb 0.9.7.1 (which comes
# with Lucid) causes an exception when unicode is received.
detail = detail.encode('utf8')
return _abort(status_code=status_code,
detail=detail,
headers=headers,
comment=comment)
def render_snippet(template_name, **kw):
''' Helper function for rendering snippets. Rendered html has
comment tags added to show the template used. NOTE: unlike other
render functions this takes a list of keywords instead of a dict for
the extra template variables. '''
# allow cache_force to be set in render function
cache_force = kw.pop('cache_force', None)
output = render(template_name, extra_vars=kw, cache_force=cache_force,
renderer='snippet')
output = '\n<!-- Snippet %s start -->\n%s\n<!-- Snippet %s end -->\n' % (
template_name, output, template_name)
return literal(output)
def render_text(template_name, extra_vars=None, cache_force=None):
''' Helper function to render a genshi NewTextTemplate without
having to pass the loader_class or method. '''
return render(template_name,
extra_vars=extra_vars,
cache_force=cache_force,
method='text',
loader_class=NewTextTemplate)
def render_jinja2(template_name, extra_vars):
env = config['pylons.app_globals'].jinja_env
template = env.get_template(template_name)
return template.render(**extra_vars)
def render(template_name, extra_vars=None, cache_key=None, cache_type=None,
cache_expire=None, method='xhtml', loader_class=MarkupTemplate,
cache_force = None, renderer=None):
''' Main template rendering function. '''
def render_template():
globs = extra_vars or {}
globs.update(pylons_globals())
globs['actions'] = model.Action
# Using pylons.url() directly destroys the localisation stuff so
# we remove it so any bad templates crash and burn
del globs['url']
try:
template_path, template_type = lib.render.template_info(template_name)
except lib.render.TemplateNotFound:
template_type = 'genshi'
template_path = ''
# snippets should not pass the context
# but allow for legacy genshi templates
if renderer == 'snippet' and template_type != 'genshi':
del globs['c']
del globs['tmpl_context']
log.debug('rendering %s [%s]' % (template_path, template_type))
if config.get('debug'):
context_vars = globs.get('c')
if context_vars:
context_vars = dir(context_vars)
debug_info = {'template_name' : template_name,
'template_path' : template_path,
'template_type' : template_type,
'vars' : globs,
'c_vars': context_vars,
'renderer' : renderer,}
if 'CKAN_DEBUG_INFO' not in request.environ:
request.environ['CKAN_DEBUG_INFO'] = []
request.environ['CKAN_DEBUG_INFO'].append(debug_info)
# Jinja2 templates
if template_type == 'jinja2':
# We don't want to have the config in templates it should be
# accessed via g (app_globals) as this gives us flexability such
# as changing via database settings.
del globs['config']
# TODO should we raise error if genshi filters??
return render_jinja2(template_name, globs)
# Genshi templates
template = globs['app_globals'].genshi_loader.load(template_name,
cls=loader_class)
stream = template.generate(**globs)
for item in PluginImplementations(IGenshiStreamFilter):
stream = item.filter(stream)
if loader_class == NewTextTemplate:
return literal(stream.render(method="text", encoding=None))
return literal(stream.render(method=method, encoding=None,
strip_whitespace=True))
if 'Pragma' in response.headers:
del response.headers["Pragma"]
## Caching Logic
allow_cache = True
# Force cache or not if explicit.
if cache_force is not None:
allow_cache = cache_force
# Do not allow caching of pages for logged in users/flash messages etc.
elif session.last_accessed:
allow_cache = False
# Tests etc.
elif 'REMOTE_USER' in request.environ:
allow_cache = False
# Don't cache if based on a non-cachable template used in this.
elif request.environ.get('__no_cache__'):
allow_cache = False
# Don't cache if we have set the __no_cache__ param in the query string.
elif request.params.get('__no_cache__'):
allow_cache = False
# Don't cache if we have extra vars containing data.
elif extra_vars:
for k, v in extra_vars.iteritems():
allow_cache = False
break
# Record cachability for the page cache if enabled
request.environ['CKAN_PAGE_CACHABLE'] = allow_cache
if allow_cache:
response.headers["Cache-Control"] = "public"
try:
cache_expire = int(config.get('ckan.cache_expires', 0))
response.headers["Cache-Control"] += \
", max-age=%s, must-revalidate" % cache_expire
except ValueError:
pass
else:
# We do not want caching.
response.headers["Cache-Control"] = "private"
# Prevent any further rendering from being cached.
request.environ['__no_cache__'] = True
log.debug('Template cache-control: %s' % response.headers["Cache-Control"])
# Render Time :)
try:
return cached_template(template_name, render_template,
loader_class=loader_class)
except ckan.exceptions.CkanUrlException, e:
raise ckan.exceptions.CkanUrlException(
'\nAn Exception has been raised for template %s\n%s' %
(template_name, e.message))
class ValidationException(Exception):
pass
class BaseController(WSGIController):
repo = model.repo
authorizer = authz.Authorizer()
log = logging.getLogger(__name__)
def __before__(self, action, **params):
c.__timer = time.time()
c.__version__ = ckan.__version__
app_globals.app_globals._check_uptodate()
self._identify_user()
i18n.handle_request(request, c)
# If the user is logged in add their number of new activities to the
# template context.
if c.userobj:
from ckan.logic import get_action
new_activities_count = get_action(
'dashboard_new_activities_count')
context = {'model': model, 'session': model.Session,
'user': c.user or c.author}
c.new_activities = new_activities_count(context, {})
def _identify_user(self):
'''
Identifies the user using two methods:
a) If he has logged into the web interface then repoze.who will
set REMOTE_USER.
b) For API calls he may set a header with his API key.
If the user is identified then:
c.user = user name (unicode)
c.userobj = user object
c.author = user name
otherwise:
c.user = None
c.userobj = None
c.author = user\'s IP address (unicode)
'''
# see if it was proxied first
c.remote_addr = request.environ.get('HTTP_X_FORWARDED_FOR', '')
if not c.remote_addr:
c.remote_addr = request.environ.get('REMOTE_ADDR',
'Unknown IP Address')
# environ['REMOTE_USER'] is set by repoze.who if it authenticates
# a user's cookie or OpenID. But repoze.who doesn't check the user
# (still) exists in our database - we need to do that here. (Another
# way would be with an userid_checker, but that would mean another db
# access.
# See: http://docs.repoze.org/who/1.0/narr.html#module-repoze.who\
# .plugins.sql )
c.user = request.environ.get('REMOTE_USER', '')
if c.user:
c.user = c.user.decode('utf8')
c.userobj = model.User.by_name(c.user)
if c.userobj is None:
# This occurs when you are logged in, clean db
# and then restart (or when you change your username)
# There is no user object, so even though repoze thinks you
# are logged in and your cookie has ckan_display_name, we
# need to force user to logout and login again to get the
# User object.
session['lang'] = request.environ.get('CKAN_LANG')
session.save()
ev = request.environ
if 'repoze.who.plugins' in ev:
pth = getattr(ev['repoze.who.plugins']['friendlyform'],
'logout_handler_path')
h.redirect_to(pth)
else:
c.userobj = self._get_user_for_apikey()
if c.userobj is not None:
c.user = c.userobj.name
if c.user:
c.author = c.user
else:
c.author = c.remote_addr
c.author = unicode(c.author)
def __call__(self, environ, start_response):
"""Invoke the Controller"""
# WSGIController.__call__ dispatches to the Controller method
# the request is routed to. This routing information is
# available in environ['pylons.routes_dict']
try:
res = WSGIController.__call__(self, environ, start_response)
finally:
model.Session.remove()
# Clean out any old cookies as they may contain api keys etc
# This also improves the cachability of our pages as cookies
# prevent proxy servers from caching content unless they have
# been configured to ignore them.
for cookie in request.cookies:
if cookie.startswith('ckan') and cookie not in ['ckan']:
response.delete_cookie(cookie)
# Remove the ckan session cookie if not used e.g. logged out
elif cookie == 'ckan' and not c.user:
# Check session for valid data (including flash messages)
# (DGU also uses session for a shopping basket-type behaviour)
is_valid_cookie_data = False
for key, value in session.items():
if not key.startswith('_') and value:
is_valid_cookie_data = True
break
if not is_valid_cookie_data:
if session.id:
if not session.get('lang'):
self.log.debug('No session data any more - '
'deleting session')
self.log.debug('Session: %r', session.items())
session.delete()
else:
response.delete_cookie(cookie)
self.log.debug('No session data any more - '
'deleting session cookie')
# Remove auth_tkt repoze.who cookie if user not logged in.
elif cookie == 'auth_tkt' and not session.id:
response.delete_cookie(cookie)
return res
def __after__(self, action, **params):
self._set_cors()
r_time = time.time() - c.__timer
url = request.environ['CKAN_CURRENT_URL'].split('?')[0]
log.info(' %s render time %.3f seconds' % (url, r_time))
def _set_cors(self):
response.headers['Access-Control-Allow-Origin'] = "*"
response.headers['Access-Control-Allow-Methods'] = \
"POST, PUT, GET, DELETE, OPTIONS"
response.headers['Access-Control-Allow-Headers'] = \
"X-CKAN-API-KEY, Authorization, Content-Type"
def _get_user(self, reference):
return model.User.by_name(reference)
def _get_pkg(self, reference):
return model.Package.get(reference)
def _get_group(self, reference):
return model.Group.get(reference)
def _get_tag(self, reference):
return model.Tag.get(reference)
@classmethod
def _get_request_data(cls, try_url_params=False):
'''Returns a dictionary, extracted from a request.
If there is no data, None or "" is returned.
ValueError will be raised if the data is not a JSON-formatted dict.
The data is retrieved as a JSON-encoded dictionary from the request
body. Or, if the `try_url_params` argument is True and the request is
a GET request, then an attempt is made to read the data from the url
parameters of the request.
try_url_params
If try_url_params is False, then the data_dict is read from the
request body.
If try_url_params is True and the request is a GET request then the
data is read from the url parameters. The resulting dict will only
be 1 level deep, with the url-param fields being the keys. If a
single key has more than one value specified, then the value will
be a list of strings, otherwise just a string.
This function is only used by the API, so no strings need to be
translated.
TODO: If this is only used by the API, then perhaps it should be
moved to the api controller class?
'''
cls.log.debug('Retrieving request params: %r' % request.params)
cls.log.debug('Retrieving request POST: %r' % request.POST)
cls.log.debug('Retrieving request GET: %r' % request.GET)
request_data = None
if request.POST:
try:
keys = request.POST.keys()
# Parsing breaks if there is a = in the value, so for now
# we will check if the data is actually all in a single key
if keys and request.POST[keys[0]] in [u'1', u'']:
request_data = keys[0]
else:
request_data = urllib.unquote_plus(request.body)
except Exception, inst:
msg = "Could not find the POST data: %r : %s" % \
(request.POST, inst)
raise ValueError(msg)
elif try_url_params and request.GET:
return request.GET.mixed()
else:
try:
if request.method in ['POST', 'PUT']:
request_data = request.body
else:
request_data = None
except Exception, inst:
msg = "Could not extract request body data: %s" % \
(inst)
raise ValueError(msg)
cls.log.debug('Retrieved request body: %r' % request.body)
if not request_data:
msg = "No request body data"
raise ValueError(msg)
if request_data:
try:
request_data = json.loads(request_data, encoding='utf8')
except ValueError, e:
raise ValueError('Error decoding JSON data. '
'Error: %r '
'JSON data extracted from the request: %r' %
(e, request_data))
if not isinstance(request_data, dict):
raise ValueError('Request data JSON decoded to %r but '
'it needs to be a dictionary.' % request_data)
# ensure unicode values
for key, val in request_data.items():
# if val is str then assume it is ascii, since json converts
# utf8 encoded JSON to unicode
request_data[key] = cls._make_unicode(val)
cls.log.debug('Request data extracted: %r' % request_data)
return request_data
@classmethod
def _make_unicode(cls, entity):
"""Cast bare strings and strings in lists or dicts to Unicode
"""
if isinstance(entity, str):
return unicode(entity)
elif isinstance(entity, list):
new_items = []
for item in entity:
new_items.append(cls._make_unicode(item))
return new_items
elif isinstance(entity, dict):
new_dict = {}
for key, val in entity.items():
new_dict[key] = cls._make_unicode(val)
return new_dict
else:
return entity
def _get_user_for_apikey(self):
apikey_header_name = config.get(APIKEY_HEADER_NAME_KEY,
APIKEY_HEADER_NAME_DEFAULT)
apikey = request.headers.get(apikey_header_name, '')
if not apikey:
apikey = request.environ.get(apikey_header_name, '')
if not apikey:
# For misunderstanding old documentation (now fixed).
apikey = request.environ.get('HTTP_AUTHORIZATION', '')
if not apikey:
apikey = request.environ.get('Authorization', '')
# Forget HTTP Auth credentials (they have spaces).
if ' ' in apikey:
apikey = ''
if not apikey:
return None
self.log.debug("Received API Key: %s" % apikey)
apikey = unicode(apikey)
query = model.Session.query(model.User)
user = query.filter_by(apikey=apikey).first()
return user
def _get_timing_cache_path(self):
return path
@classmethod
def _get_user_editable_groups(cls):
if not hasattr(c, 'user'):
c.user = model.PSEUDO_USER__VISITOR
import ckan.authz # Todo: Move import to top of this file?
groups = ckan.authz.Authorizer.authorized_query(
c.user, model.Group, action=model.Action.EDIT).all()
return [g for g in groups if g.state == model.State.ACTIVE]
def _get_package_dict(self, *args, **kwds):
import ckan.forms
user_editable_groups = self._get_user_editable_groups()
package_dict = ckan.forms.get_package_dict(
user_editable_groups=user_editable_groups,
*args, **kwds
)
return package_dict
def _edit_package_dict(self, *args, **kwds):
import ckan.forms
return ckan.forms.edit_package_dict(*args, **kwds)
@classmethod
def _get_package_fieldset(cls, is_admin=False, **kwds):
kwds.update(request.params)
kwds['user_editable_groups'] = cls._get_user_editable_groups()
kwds['is_admin'] = is_admin
from ckan.forms import GetPackageFieldset
return GetPackageFieldset(**kwds).fieldset
def _get_standard_package_fieldset(self):
import ckan.forms
user_editable_groups = self._get_user_editable_groups()
fieldset = ckan.forms.get_standard_fieldset(
user_editable_groups=user_editable_groups
)
return fieldset
def _handle_update_of_authz(self, domain_object):
'''In the event of a post request to a domain object\'s authz form,
work out which of the four possible actions is to be done,
and do it before displaying the page.
Returns the updated roles for the domain_object.
'''
from ckan.logic import NotFound, get_action
context = {'model': model, 'session': model.Session,
'user': c.user or c.author}
data_dict = {'domain_object': domain_object.id}
# Work out actions needed, depending on which button was pressed
update_type = 'user'
if 'save' in request.POST:
update_or_add = 'update'
elif 'add' in request.POST:
update_or_add = 'add'
else:
update_type = None
update_or_add = None
# Work out what role checkboxes are checked or unchecked
checked_roles = [box_id for (box_id, value) in request.params.items()
if (value == u'on')]
unchecked_roles = [box_id for (box_id, value) in request.params.items()
if (value == u'submitted')]
action = None
if update_or_add is 'update':
# Get user_roles by decoding the checkbox grid - user$role strings
user_roles = {}
for checked_role in checked_roles:
obj_id, role = checked_role.split('$')
if obj_id not in user_roles:
user_roles[obj_id] = []
user_roles[obj_id].append(role)
# Users without roles need adding to the user_roles too to make
# their roles be deleted
for unchecked_role in unchecked_roles:
obj_id, role = unchecked_role.split('$')
if obj_id not in user_roles:
user_roles[obj_id] = []
# Convert user_roles to role dictionaries
role_dicts = []
for user, roles in user_roles.items():
role_dicts.append({update_type: user, 'roles': roles})
data_dict['user_roles'] = role_dicts
action = 'user_role_bulk_update'
success_message = _('Updated')
elif update_or_add is 'add':
# Roles for this new user is a simple list from the checkbox row
data_dict['roles'] = checked_roles
# User comes from the input box.
new_user = request.params.get('new_user_name')
if new_user:
data_dict[update_type] = new_user
action = 'user_role_update'
success_message = _('User role(s) added')
else:
h.flash_error(_('Please supply a user name'))
if action:
try:
roles = get_action(action)(context, data_dict)
except NotFound, e:
h.flash_error(_('Not found') + (': %s' % e if str(e) else ''))
else:
h.flash_success(success_message)
# Return roles for all users on this domain object
if update_or_add is 'add':
if update_type in data_dict:
del data_dict[update_type]
return get_action('roles_show')(context, data_dict)
def _prepare_authz_info_for_render(self, user_object_roles):
# =================
# Display the page
# Find out all the possible roles. At the moment, any role can be
# associated with any object, so that's easy:
possible_roles = model.Role.get_all()
# uniquify and sort
users = sorted(list(set([uor['user_id']
for uor in user_object_roles['roles']
if uor['user_id']])))
# make a dictionary from (user, role) to True, False
users_roles = [(uor['user_id'], uor['role'])
for uor in user_object_roles['roles']
if uor['user_id']]
user_role_dict = {}
for u in users:
for r in possible_roles:
user_role_dict[(u, r)] = (u, r) in users_roles
c.roles = possible_roles
c.users = users
c.user_role_dict = user_role_dict
# Include the '_' function in the public names
__all__ = [__name for __name in locals().keys() if not __name.startswith('_')
or __name == '_']