How to detect (daily) User Login when using cookies?

90 views
Skip to first unread message

Tobias Dacoir

unread,
Jan 23, 2015, 4:43:41 AM1/23/15
to django...@googlegroups.com
I'm using django-allauth and I receive a signal when a user logs in. Now I want to store each day the user logs in. However, when the user does not logout he can still log in the next day thanks to the cookies. I know that I can set SESSION_EXPIRE_AT_BROWSER_CLOSE to True in settings.py. But this may annoy some Users.

So is there a way to use cookies but still tell if a User has accessed the site for the first time today?

Collin Anderson

unread,
Jan 27, 2015, 3:00:15 PM1/27/15
to django...@googlegroups.com
Hi,

Would it make sense to simply keep a record of when the last time you've seen the user is?

Collin

Tobias Dacoir

unread,
Jan 28, 2015, 4:58:30 AM1/28/15
to django...@googlegroups.com
Yes that would be enough. I know in the User Model there is last_login but that is only updated when the User actually logs in. And the signal from django-allauth is also only send when the user uses the login form. The only other alternative I found was to check in every view I have for request.user and store / update datetime.now. But this is quite ugly.

Collin Anderson

unread,
Jan 30, 2015, 8:50:03 AM1/30/15
to django...@googlegroups.com
Hi,

If you use a custom authentication backend, you could update it every time get_user(request) is called.

Collin

Tom Evans

unread,
Jan 30, 2015, 9:56:10 AM1/30/15
to django...@googlegroups.com
On Fri, Jan 30, 2015 at 1:50 PM, Collin Anderson <cmawe...@gmail.com> wrote:
> Hi,
>
> If you use a custom authentication backend, you could update it every time
> get_user(request) is called.
>

HTTP is stateless, authentication happens every request, so that gets
called on every request, causing session modification on each request.

How about:

from django.utils import timezone

class DailyLoginMiddleware(object):
def process_request(self, request):
if request.user.is_authenticated():
today = timezone.now().strftime('%Y%m%d')
if request.session.get('last_seen') != today:
request.session['last_seen'] = today
setattr(request, 'new_today', True)

Store todays date in the session, check to see if it is changed, only
modify the session if the date has changed, set an attribute on the
request so that later views can include that information.

Cheers

Tom

Tobias Dacoir

unread,
Jan 30, 2015, 10:34:42 AM1/30/15
to django...@googlegroups.com
Thanks. Though I do not use a Custom Authentication Backend, it should be possible to inherit from the Default one and just overwrite the get_user Method.
I will test it out.
Reply all
Reply to author
Forward
0 new messages