Handle absence of anonymous user
authorDenis Laxalde <denis@laxalde.org>
Wed, 29 Apr 2015 22:46:17 +0200
changeset 11575 97110b4af42f
parent 11574 af1021553648
child 11576 6df91cb85ecc
Handle absence of anonymous user Set cw_session and then cw_cnx request attributes to None in case anonymous connection is not allowed (i.e. no "anon" user in config). Then catch AuthenticationError in CubicWebPyramidHandler and return the 'login' view. Closes #4751862.
pyramid_cubicweb/bwcompat.py
pyramid_cubicweb/core.py
--- a/pyramid_cubicweb/bwcompat.py	Tue May 19 08:38:08 2015 +0200
+++ b/pyramid_cubicweb/bwcompat.py	Wed Apr 29 22:46:17 2015 +0200
@@ -110,8 +110,12 @@
             # that is accessible by the pyramid views
             headers = security.forget(request)
             raise HTTPSeeOther(ex.url, headers=headers)
-        # except AuthenticationError:
-        # XXX I don't think it makes sens to catch this ex here (cdevienne)
+        except cubicweb.AuthenticationError:
+            # Will occur upon access to req.cnx which is a
+            # cubicweb.dbapi._NeedAuthAccessMock.
+            if not content:
+                content = vreg['views'].main_template(req, 'login')
+                request.response.body = content
 
         return request.response
 
--- a/pyramid_cubicweb/core.py	Tue May 19 08:38:08 2015 +0200
+++ b/pyramid_cubicweb/core.py	Wed Apr 29 22:46:17 2015 +0200
@@ -240,7 +240,10 @@
     :param request: A pyramid request
     :returns type: :class:`cubicweb.server.session.Connection`
     """
-    cnx = repoapi.ClientConnection(request.cw_session)
+    session = request.cw_session
+    if session is None:
+        return None
+    cnx = repoapi.ClientConnection(session)
 
     def cleanup(request):
         if (request.exception is not None and not isinstance(
@@ -286,8 +289,10 @@
     repo = request.registry['cubicweb.repository']
 
     if not request.authenticated_userid:
-        session = repo_connect(
-            request, repo, eid=request.registry['cubicweb.anonymous_eid'])
+        eid = request.registry.get('cubicweb.anonymous_eid')
+        if eid is None:
+            return None
+        session = repo_connect(request, repo, eid=eid)
     else:
         session = request._cw_cached_session
 
@@ -305,7 +310,9 @@
 
     """
     req = CubicWebPyramidRequest(request)
-    req.set_cnx(request.cw_cnx)
+    cnx = request.cw_cnx
+    if cnx is not None:
+        req.set_cnx(request.cw_cnx)
     return req
 
 
@@ -358,8 +365,9 @@
 
     with repo.internal_cnx() as cnx:
         login = config.registry['cubicweb.config'].anonymous_user()[0]
-        config.registry['cubicweb.anonymous_eid'] = cnx.find(
-            'CWUser', login=login).one().eid
+        if login is not None:
+            config.registry['cubicweb.anonymous_eid'] = cnx.find(
+                'CWUser', login=login).one().eid
 
     config.add_request_method(
         _cw_session, name='cw_session', property=True, reify=True)