[auth] Make last_login_time updated.
authorChristophe de Vienne <christophe@unlish.com>
Sun, 02 Nov 2014 22:54:24 +0100
changeset 11519 92423d03ef25
parent 11518 962b37beab27
child 11520 9f3b9e610c3d
[auth] Make last_login_time updated. The update is done when the user logs in, then every time the authentication is reissued. Closes #4549891
pyramid_cubicweb/defaults.py
--- a/pyramid_cubicweb/defaults.py	Thu Oct 23 16:29:44 2014 +0200
+++ b/pyramid_cubicweb/defaults.py	Sun Nov 02 22:54:24 2014 +0100
@@ -1,3 +1,5 @@
+import datetime
+import logging
 import warnings
 
 from pyramid.authentication import AuthTktAuthenticationPolicy
@@ -5,6 +7,34 @@
 
 from pyramid_cubicweb.core import get_principals
 
+log = logging.getLogger(__name__)
+
+
+class CubicWebAuthTktAuthenticationPolicy(AuthTktAuthenticationPolicy):
+    """An authentication policy that update the user last_login_time.
+
+    The update is done in the 'remember' method, which is called on login,
+    and each time the authentication ticket is reissued.
+
+    Meaning, the last_login_time is updated reissue_time seconds (maximum)
+    before the last request by the user.
+    """
+
+    def remember(self, request, principal, **kw):
+        headers = super(CubicWebAuthTktAuthenticationPolicy, self).remember(
+            request, principal, **kw)
+        try:
+            repo = request.registry['cubicweb.repository']
+            with repo.internal_session() as cnx:
+                cnx.execute(
+                    "SET U last_login_time %(now)s WHERE U eid %(user)s", {
+                        'now': datetime.datetime.now(),
+                        'user': principal})
+                cnx.commit()
+        except:
+            log.exception("Failed to update last_login_time")
+        return headers
+
 
 def includeme(config):
     config.include('pyramid_cubicweb.session')
@@ -27,7 +57,7 @@
         ''')
 
     config.set_authentication_policy(
-        AuthTktAuthenticationPolicy(
+        CubicWebAuthTktAuthenticationPolicy(
             secret, callback=get_principals, hashalg='sha512',
             reissue_time=3600))
     config.set_authorization_policy(ACLAuthorizationPolicy())