[repoapi] add an anonymous_cnx function
authorPierre-Yves David <pierre-yves.david@logilab.fr>
Mon, 24 Jun 2013 18:18:51 +0200
changeset 9062 fa5bc8aef7ed
parent 9061 e86fdab3d296
child 9063 383d45cf61fa
[repoapi] add an anonymous_cnx function This function return an anonymous ClientConnection. It aims to replace ``dbapi.anonymous_session``.
repoapi.py
test/unittest_repoapi.py
--- a/repoapi.py	Fri Jun 21 16:40:12 2013 +0200
+++ b/repoapi.py	Mon Jun 24 18:18:51 2013 +0200
@@ -18,7 +18,7 @@
 """Official API to access the content of a repository
 """
 from cubicweb.utils import parse_repo_uri
-from cubicweb import ConnectionError, ProgrammingError
+from cubicweb import ConnectionError, ProgrammingError, AuthenticationError
 from uuid import uuid4
 from contextlib import contextmanager
 from cubicweb.req import RequestSessionBase
@@ -87,6 +87,21 @@
     # this is something to consider once we have proper server side Connection.
     return ClientConnection(session, autoclose_session=True)
 
+def anonymous_cnx(repo):
+    """return a ClientConnection for Anonymous user.
+
+    The ClientConnection is associated to a new Session object that will be
+    closed when the ClientConnection is closed.
+
+    raises an AuthenticationError if anonymous usage is not allowed
+    """
+    anoninfo = getattr(repo.config, 'anonymous_user', lambda: None)()
+    if anoninfo is None: # no anonymous user
+        raise AuthenticationError('anonymous access is not authorized')
+    anon_login, anon_password = anoninfo
+    # use vreg's repository cache
+    return connect(repo, anon_login, password=anon_password)
+
 def _srv_cnx_func(name):
     """Decorate ClientConnection method blindly forward to Connection
     THIS TRANSITIONAL PURPOSE
--- a/test/unittest_repoapi.py	Fri Jun 21 16:40:12 2013 +0200
+++ b/test/unittest_repoapi.py	Mon Jun 24 18:18:51 2013 +0200
@@ -21,7 +21,7 @@
 from cubicweb.devtools.testlib import CubicWebTC
 
 from cubicweb import ProgrammingError
-from cubicweb.repoapi import ClientConnection, connect
+from cubicweb.repoapi import ClientConnection, connect, anonymous_cnx
 
 
 class REPOAPITC(CubicWebTC):
@@ -74,6 +74,15 @@
             rset = clt_cnx.execute('Any X WHERE X is CWUser')
             self.assertTrue(rset)
 
+    def test_anonymous_connect(self):
+        """check that you can get anonymous connection when the data exist"""
+
+        clt_cnx = anonymous_cnx(self.repo)
+        self.assertEqual('anon', clt_cnx.user.login)
+        with clt_cnx:
+            rset = clt_cnx.execute('Any X WHERE X is CWUser')
+            self.assertTrue(rset)
 
 
 
+