backport oldstable stable
authorSylvain Thénault <sylvain.thenault@logilab.fr>
Sat, 18 Dec 2010 23:11:58 +0100
branchstable
changeset 6750 ef513c03a224
parent 6746 f29a5f015fc3 (current diff)
parent 6749 48f468f33704 (diff)
child 6751 02091c91520f
child 6752 7351806cd485
backport oldstable
__pkginfo__.py
cwconfig.py
debian/control
devtools/__init__.py
devtools/devctl.py
hooks/syncschema.py
req.py
server/sources/ldapuser.py
test/unittest_req.py
--- a/__pkginfo__.py	Tue Dec 14 15:08:23 2010 +0100
+++ b/__pkginfo__.py	Sat Dec 18 23:11:58 2010 +0100
@@ -52,7 +52,7 @@
     'Twisted': '',
     # XXX graphviz
     # server dependencies
-    'logilab-database': '>= 1.3.1',
+    'logilab-database': '>= 1.3.2',
     'pysqlite': '>= 2.5.5', # XXX install pysqlite2
     }
 
--- a/cwconfig.py	Tue Dec 14 15:08:23 2010 +0100
+++ b/cwconfig.py	Sat Dec 18 23:11:58 2010 +0100
@@ -142,7 +142,7 @@
 from smtplib import SMTP
 from threading import Lock
 from os.path import (exists, join, expanduser, abspath, normpath,
-                     basename, isdir, dirname)
+                     basename, isdir, dirname, splitext)
 from warnings import warn
 from logilab.common.decorators import cached, classproperty
 from logilab.common.deprecation import deprecated
@@ -400,6 +400,13 @@
         return join(cls.shared_dir(), 'i18n')
 
     @classmethod
+    def cw_languages(cls):
+        for fname in os.listdir(join(cls.i18n_lib_dir())):
+            if fname.endswith('.po'):
+                yield splitext(fname)[0]
+
+
+    @classmethod
     def available_cubes(cls):
         import re
         cubes = set()
@@ -682,8 +689,8 @@
 
     def __init__(self, debugmode=False):
         register_stored_procedures()
-        ConfigurationMixIn.__init__(self)
         self._cubes = None
+        super(CubicWebNoAppConfiguration, self).__init__()
         self.debugmode = debugmode
         self.adjust_sys_path()
         self.load_defaults()
@@ -973,11 +980,15 @@
 
     def __init__(self, appid, debugmode=False):
         self.appid = appid
-        CubicWebNoAppConfiguration.__init__(self, debugmode)
+        super(CubicWebConfiguration, self).__init__(debugmode)
+        fake_gettext = (unicode, lambda ctx, msgid: unicode(msgid))
+        for lang in self.available_languages():
+            self.translations[lang] = fake_gettext
+        self._cubes = None
         self.load_file_configuration(self.main_config_file())
 
     def adjust_sys_path(self):
-        CubicWebNoAppConfiguration.adjust_sys_path(self)
+        super(CubicWebConfiguration, self).adjust_sys_path()
         # adding apphome to python path is not usually necessary in production
         # environments, but necessary for tests
         if self.apphome and not self.apphome in sys.path:
@@ -1075,8 +1086,8 @@
         if not force and hasattr(self, '_logging_initialized'):
             return
         self._logging_initialized = True
-        CubicWebNoAppConfiguration.init_log(self, logthreshold,
-                                            logfile=self.get('log-file'))
+        super_self = super(CubicWebConfiguration, self)
+        super_self.init_log(logthreshold, logfile=self.get('log-file'))
         # read a config file if it exists
         logconfig = join(self.apphome, 'logging.conf')
         if exists(logconfig):
--- a/debian/control	Tue Dec 14 15:08:23 2010 +0100
+++ b/debian/control	Sat Dec 18 23:11:58 2010 +0100
@@ -33,7 +33,7 @@
 Conflicts: cubicweb-multisources
 Replaces: cubicweb-multisources
 Provides: cubicweb-multisources
-Depends: ${python:Depends}, cubicweb-common (= ${source:Version}), cubicweb-ctl (= ${source:Version}), python-logilab-database (>= 1.3.1), cubicweb-postgresql-support | cubicweb-mysql-support | python-pysqlite2
+Depends: ${python:Depends}, cubicweb-common (= ${source:Version}), cubicweb-ctl (= ${source:Version}), python-logilab-database (>= 1.3.2), cubicweb-postgresql-support | cubicweb-mysql-support | python-pysqlite2
 Recommends: pyro (< 4.0.0), cubicweb-documentation (= ${source:Version})
 Description: server part of the CubicWeb framework
  CubicWeb is a semantic web application framework.
--- a/devtools/__init__.py	Tue Dec 14 15:08:23 2010 +0100
+++ b/devtools/__init__.py	Sat Dec 18 23:11:58 2010 +0100
@@ -24,7 +24,7 @@
 import logging
 from datetime import timedelta
 from os.path import (abspath, join, exists, basename, dirname, normpath, split,
-                     isfile, isabs)
+                     isfile, isabs, splitext)
 
 from logilab.common.date import strptime
 from cubicweb import CW_SOFTWARE_ROOT, ConfigurationError, schema, cwconfig
@@ -181,7 +181,7 @@
     cube_appobject_path = TestServerConfiguration.cube_appobject_path | TwistedConfiguration.cube_appobject_path
 
     def available_languages(self, *args):
-        return ('en', 'fr', 'de')
+        return self.cw_languages()
 
     def pyro_enabled(self):
         # but export PYRO_MULTITHREAD=0 or you get problems with sqlite and
--- a/devtools/devctl.py	Tue Dec 14 15:08:23 2010 +0100
+++ b/devtools/devctl.py	Sat Dec 18 23:11:58 2010 +0100
@@ -26,7 +26,7 @@
 # completion). So import locally in command helpers.
 import sys
 from datetime import datetime
-from os import mkdir, chdir, listdir, path as osp
+from os import mkdir, chdir, path as osp
 from warnings import warn
 
 from logilab.common import STD_BLACKLIST
@@ -34,6 +34,7 @@
 from cubicweb.__pkginfo__ import version as cubicwebversion
 from cubicweb import CW_SOFTWARE_ROOT as BASEDIR, BadCommandUsage
 from cubicweb.cwctl import CWCTL
+from cubicweb.cwconfig import CubicWebNoAppConfiguration
 from cubicweb.toolsutils import (SKEL_EXCLUDE, Command, copy_skeleton,
                                  underline_title)
 from cubicweb.web.webconfig import WebConfiguration
@@ -64,6 +65,10 @@
     @property
     def apphome(self):
         return None
+
+    def available_languages(self):
+        return self.cw_languages()
+
     def main_config_file(self):
         return None
     def init_log(self):
@@ -264,11 +269,6 @@
 
 ''' % cubicwebversion
 
-def cw_languages():
-    for fname in listdir(osp.join(WebConfiguration.i18n_lib_dir())):
-        if fname.endswith('.po'):
-            yield osp.splitext(fname)[0]
-
 
 class UpdateCubicWebCatalogCommand(Command):
     """Update i18n catalogs for cubicweb library.
@@ -330,7 +330,7 @@
         print '-> merging main pot file with existing translations.'
         chdir(cwi18ndir)
         toedit = []
-        for lang in cw_languages():
+        for lang in CubicWebNoAppConfiguration.cw_languages():
             target = '%s.po' % lang
             execute('msgmerge -N --sort-output -o "%snew" "%s" "%s"'
                     % (target, target, cubicwebpot))
@@ -445,7 +445,7 @@
     print '-> merging main pot file with existing translations:'
     chdir('i18n')
     toedit = []
-    for lang in cw_languages():
+    for lang in CubicWebNoAppConfiguration.cw_languages():
         print '-> language', lang
         cubepo = '%s.po' % lang
         if not osp.exists(cubepo):
--- a/hooks/syncschema.py	Tue Dec 14 15:08:23 2010 +0100
+++ b/hooks/syncschema.py	Sat Dec 18 23:11:58 2010 +0100
@@ -285,13 +285,15 @@
         self.session.vreg.schema.rename_entity_type(oldname, newname)
         # we need sql to operate physical changes on the system database
         sqlexec = self.session.system_sql
-        sqlexec('ALTER TABLE %s%s RENAME TO %s%s' % (SQL_PREFIX, oldname,
-                                                     SQL_PREFIX, newname))
+        dbhelper= self.session.pool.source('system').dbhelper
+        sql = dbhelper.sql_rename_table(SQL_PREFIX+oldname,
+                                        SQL_PREFIX+newname)
+        sqlexec(sql)
         self.info('renamed table %s to %s', oldname, newname)
-        sqlexec('UPDATE entities SET type=%s WHERE type=%s',
-                (newname, oldname))
-        sqlexec('UPDATE deleted_entities SET type=%s WHERE type=%s',
-                (newname, oldname))
+        sqlexec('UPDATE entities SET type=%(newname)s WHERE type=%(oldname)s',
+                {'newname': newname, 'oldname': oldname})
+        sqlexec('UPDATE deleted_entities SET type=%(newname)s WHERE type=%(oldname)s',
+                {'newname': newname, 'oldname': oldname})
         # XXX transaction records
 
     def precommit_event(self):
--- a/req.py	Tue Dec 14 15:08:23 2010 +0100
+++ b/req.py	Sat Dec 18 23:11:58 2010 +0100
@@ -142,7 +142,7 @@
 
     def ensure_ro_rql(self, rql):
         """raise an exception if the given rql is not a select query"""
-        first = rql.split(' ', 1)[0].lower()
+        first = rql.split(None, 1)[0].lower()
         if first in ('insert', 'set', 'delete'):
             raise Unauthorized(self._('only select queries are authorized'))
 
--- a/server/schemaserial.py	Tue Dec 14 15:08:23 2010 +0100
+++ b/server/schemaserial.py	Sat Dec 18 23:11:58 2010 +0100
@@ -126,8 +126,9 @@
                 sqlexec('UPDATE %(p)sCWEType SET %(p)sname=%%(n)s WHERE %(p)seid=%%(x)s'
                         % {'p': sqlutils.SQL_PREFIX}, {'x': eid, 'n': netype})
                 if etype.lower() != netype.lower():
-                    sqlexec('ALTER TABLE %s%s RENAME TO %s%s' % (
-                        sqlutils.SQL_PREFIX, etype, sqlutils.SQL_PREFIX, netype))
+                    alter_table_sql = dbhelper.sql_rename_table(sqlutils.SQL_PREFIX+etype,
+                                                                sqlutils.SQL_PREFIX+netype)
+                    sqlexec(alter_table_sql)
             sqlexec('UPDATE entities SET type=%(n)s WHERE type=%(x)s',
                     {'x': etype, 'n': netype})
             session.commit(False)
--- a/server/sources/ldapuser.py	Tue Dec 14 15:08:23 2010 +0100
+++ b/server/sources/ldapuser.py	Sat Dec 18 23:11:58 2010 +0100
@@ -126,6 +126,12 @@
           'help': 'classes of user',
           'group': 'ldap-source', 'level': 1,
           }),
+        ('user-filter',
+         {'type': 'string',
+          'default': '',
+          'help': 'additional filters to be set in the ldap query to find valid users',
+          'group': 'ldap-source', 'level': 2,
+          }),
         ('user-login-attr',
          {'type' : 'string',
           'default': 'uid',
@@ -177,11 +183,11 @@
         self.user_login_attr = source_config['user-login-attr']
         self.user_default_groups = splitstrip(source_config['user-default-group'])
         self.user_attrs = dict(v.split(':', 1) for v in splitstrip(source_config['user-attrs-map']))
+        self.user_filter = source_config.get('user-filter')
         self.user_rev_attrs = {'eid': 'dn'}
         for ldapattr, cwattr in self.user_attrs.items():
             self.user_rev_attrs[cwattr] = ldapattr
-        self.base_filters = [filter_format('(%s=%s)', ('objectClass', o))
-                              for o in self.user_classes]
+        self.base_filters = self._make_base_filters()
         self._conn = None
         self._cache = {}
         # ttlm is in minutes!
@@ -194,6 +200,13 @@
                                     source_config.get('synchronization-interval',
                                                       24*60*60))
 
+    def _make_base_filters(self):
+        filters =  [filter_format('(%s=%s)', ('objectClass', o))
+                              for o in self.user_classes] 
+        if self.user_filter:
+            filters += [self.user_filter]
+        return filters
+
     def reset_caches(self):
         """method called during test to reset potential source caches"""
         self._cache = {}
@@ -286,8 +299,7 @@
             # we really really don't want that
             raise AuthenticationError()
         searchfilter = [filter_format('(%s=%s)', (self.user_login_attr, login))]
-        searchfilter.extend([filter_format('(%s=%s)', ('objectClass', o))
-                             for o in self.user_classes])
+        searchfilter.extend(self._make_base_filters())
         searchstr = '(&%s)' % ''.join(searchfilter)
         # first search the user
         try:
--- a/test/unittest_req.py	Tue Dec 14 15:08:23 2010 +0100
+++ b/test/unittest_req.py	Sat Dec 18 23:11:58 2010 +0100
@@ -18,7 +18,7 @@
 from logilab.common.testlib import TestCase, unittest_main
 from cubicweb.req import RequestSessionBase
 from cubicweb.devtools.testlib import CubicWebTC
-
+from cubicweb import Unauthorized
 
 class RebuildURLTC(TestCase):
     def test_rebuild_url(self):
@@ -42,6 +42,12 @@
         self.assertRaises(AssertionError, req.build_url, 'one', 'two not allowed')
         self.assertRaises(AssertionError, req.build_url, 'view', test=None)
 
+    def test_ensure_no_rql(self):
+        req = RequestSessionBase(None)
+        self.assertEqual(req.ensure_ro_rql('Any X WHERE X is CWUser'), None)
+        self.assertEqual(req.ensure_ro_rql('  Any X WHERE X is CWUser  '), None)
+        self.assertRaises(Unauthorized, req.ensure_ro_rql, 'SET X login "toto" WHERE X is CWUser')
+        self.assertRaises(Unauthorized, req.ensure_ro_rql, '   SET X login "toto" WHERE X is CWUser   ')
 
 if __name__ == '__main__':
     unittest_main()