[server] Refactor Repository.register_user into a CubicWeb service (closes #3020639)
authorVladimir Popescu <vladimir.popescu@logilab.fr>
Fri, 19 Jul 2013 17:38:15 +0200
changeset 9687 00c2356faba7
parent 9686 9a04e48e780b
child 9688 1f6ecd90df4f
[server] Refactor Repository.register_user into a CubicWeb service (closes #3020639) [jcr: move commit to the caller; add item in release notes; fix NameErrors]
doc/3.19.rst
server/repository.py
sobjects/services.py
sobjects/test/unittest_register_user.py
--- a/doc/3.19.rst	Fri Apr 18 14:25:36 2014 +0200
+++ b/doc/3.19.rst	Fri Jul 19 17:38:15 2013 +0200
@@ -136,6 +136,9 @@
 * ``repo.gc_stats()`` is now deprecated. The same information is available through
   a service (``_cw.call_service('repo_gc_stats')``).
 
+* ``repo.register_user()`` is now deprecated.  The functionality is now
+  available through a service (``_cw.call_service('register_user')``).
+
 * ``request.set_session`` no longer takes an optional ``user`` argument.
 
 * CubicwebTC does not have repo and cnx as class attributes anymore. They are
--- a/server/repository.py	Fri Apr 18 14:25:36 2014 +0200
+++ b/server/repository.py	Fri Jul 19 17:38:15 2013 +0200
@@ -41,7 +41,6 @@
 from logilab.common.deprecation import deprecated
 
 from yams import BadSchemaDefinition
-from yams.schema import role_name
 from rql import RQLSyntaxError
 from rql.utils import rqlvar_maker
 
@@ -611,43 +610,16 @@
                                         'P pkey K, P value V, NOT P for_user U',
                                         build_descr=False)
 
-    # XXX protect this method: anonymous should be allowed and registration
-    # plugged
+    @deprecated("[3.19] Use session.call_service('register_user') instead'")
     def register_user(self, login, password, email=None, **kwargs):
         """check a user with the given login exists, if not create it with the
         given password. This method is designed to be used for anonymous
         registration on public web site.
         """
         with self.internal_cnx() as cnx:
-            # for consistency, keep same error as unique check hook (although not required)
-            errmsg = cnx._('the value "%s" is already used, use another one')
-            if (cnx.execute('CWUser X WHERE X login %(login)s', {'login': login},
-                            build_descr=False)
-                or cnx.execute('CWUser X WHERE X use_email C, C address %(login)s',
-                               {'login': login}, build_descr=False)):
-                qname = role_name('login', 'subject')
-                raise ValidationError(None, {qname: errmsg % login})
-            # we have to create the user
-            user = self.vreg['etypes'].etype_class('CWUser')(cnx)
-            if isinstance(password, unicode):
-                # password should *always* be utf8 encoded
-                password = password.encode('UTF8')
-            kwargs['login'] = login
-            kwargs['upassword'] = password
-            self.glob_add_entity(cnx, EditedEntity(user, **kwargs))
-            cnx.execute('SET X in_group G WHERE X eid %(x)s, G name "users"',
-                        {'x': user.eid})
-            if email or '@' in login:
-                d = {'login': login, 'email': email or login}
-                if cnx.execute('EmailAddress X WHERE X address %(email)s', d,
-                               build_descr=False):
-                    qname = role_name('address', 'subject')
-                    raise ValidationError(None, {qname: errmsg % d['email']})
-                cnx.execute('INSERT EmailAddress X: X address %(email)s, '
-                            'U primary_email X, U use_email X '
-                            'WHERE U login %(login)s', d, build_descr=False)
+            cnx.call_service('register_user', login=login, password=password,
+                             email=email, **kwargs)
             cnx.commit()
-        return True
 
     def find_users(self, fetch_attrs, **query_attrs):
         """yield user attributes for cwusers matching the given query_attrs
--- a/sobjects/services.py	Fri Apr 18 14:25:36 2014 +0200
+++ b/sobjects/services.py	Fri Jul 19 17:38:15 2013 +0200
@@ -1,4 +1,4 @@
-# copyright 2003-2012 LOGILAB S.A. (Paris, FRANCE), all rights reserved.
+# copyright 2003-2014 LOGILAB S.A. (Paris, FRANCE), all rights reserved.
 # contact http://www.logilab.fr/ -- mailto:contact@logilab.fr
 #
 # This file is part of CubicWeb.
@@ -19,8 +19,10 @@
 
 import threading
 
+from yams.schema import role_name
+from cubicweb import ValidationError
 from cubicweb.server import Service
-from cubicweb.predicates import match_user_groups
+from cubicweb.predicates import match_user_groups, match_kwargs
 
 class StatsService(Service):
     """Return a dictionary containing some statistics about the repository
@@ -100,3 +102,50 @@
         results['referenced'] = values
         results['unreachable'] = len(garbage)
         return results
+
+
+class RegisterUserService(Service):
+    """check if a user with the given login exists, if not create it with the
+    given password. This service is designed to be used for anonymous
+    registration on public web sites.
+
+    To use it, do:
+     with self.appli.repo.internal_cnx() as cnx:
+        cnx.call_service('register_user',
+                         login=login,
+                         password=password,
+                         **kwargs)
+    """
+    __regid__ = 'register_user'
+    __select__ = Service.__select__ & match_kwargs('login', 'password')
+
+    def call(self, login, password, email=None, **kwargs):
+        cnx = self._cw
+        errmsg = cnx._('the value "%s" is already used, use another one')
+
+        if (cnx.execute('CWUser X WHERE X login %(login)s', {'login': login},
+                        build_descr=False)
+            or cnx.execute('CWUser X WHERE X use_email C, C address %(login)s',
+                           {'login': login}, build_descr=False)):
+            qname = role_name('login', 'subject')
+            raise ValidationError(None, {qname: errmsg % login})
+
+        if isinstance(password, unicode):
+            # password should *always* be utf8 encoded
+            password = password.encode('UTF8')
+        kwargs['login'] = login
+        kwargs['upassword'] = password
+        # we have to create the user
+        user = cnx.create_entity('CWUser', **kwargs)
+        cnx.execute('SET X in_group G WHERE X eid %(x)s, G name "users"',
+                    {'x': user.eid})
+
+        if email or '@' in login:
+            d = {'login': login, 'email': email or login}
+            if cnx.execute('EmailAddress X WHERE X address %(email)s', d,
+                           build_descr=False):
+                qname = role_name('address', 'subject')
+                raise ValidationError(None, {qname: errmsg % d['email']})
+            cnx.execute('INSERT EmailAddress X: X address %(email)s, '
+                        'U primary_email X, U use_email X '
+                        'WHERE U login %(login)s', d, build_descr=False)
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/sobjects/test/unittest_register_user.py	Fri Jul 19 17:38:15 2013 +0200
@@ -0,0 +1,52 @@
+# copyright 2003-2014 LOGILAB S.A. (Paris, FRANCE), all rights reserved.
+# contact http://www.logilab.fr/ -- mailto:contact@logilab.fr
+#
+# This file is part of CubicWeb.
+#
+# CubicWeb is free software: you can redistribute it and/or modify it under the
+# terms of the GNU Lesser General Public License as published by the Free
+# Software Foundation, either version 2.1 of the License, or (at your option)
+# any later version.
+#
+# CubicWeb is distributed in the hope that it will be useful, but WITHOUT
+# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+# FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more
+# details.
+#
+# You should have received a copy of the GNU Lesser General Public License along
+# with CubicWeb.  If not, see <http://www.gnu.org/licenses/>.
+"""unittest for cubicweb.dbapi"""
+
+from cubicweb import ValidationError
+from cubicweb.web import Unauthorized
+from cubicweb.devtools.testlib import CubicWebTC
+
+
+class RegisterUserTC(CubicWebTC):
+
+    def test_register_user_service(self):
+        acc = self.new_access('admin')
+        with acc.client_cnx() as cnx:
+            cnx.call_service('register_user', login=u'foo1', password=u'bar1',
+                             email=u'foo1@bar1.com', firstname=u'Foo1',
+                             surname=u'Bar1')
+
+        acc = self.new_access('anon')
+        with acc.client_cnx() as cnx:
+            self.assertRaises(Unauthorized, cnx.call_service, 'register_user',
+                              login=u'foo2', password=u'bar2',
+                              email=u'foo2@bar2.com', firstname=u'Foo2', surname=u'Bar2')
+
+        with self.repo.internal_cnx() as cnx:
+            cnx.call_service('register_user', login=u'foo3',
+                             password=u'bar3', email=u'foo3@bar3.com',
+                             firstname=u'Foo3', surname=u'Bar3')
+            # same login
+            with self.assertRaises(ValidationError):
+                cnx.call_service('register_user', login=u'foo3',
+                                 password=u'bar3')
+
+
+if __name__ == '__main__':
+    from logilab.common.testlib import unittest_main
+    unittest_main()