How to lookup django session for a particular user?

后端 未结 6 1502
太阳男子
太阳男子 2020-12-07 11:13

I am writing an application where I will be accessing the database from django and from a stand alone application. Both need to do session verification and the session shoul

6条回答
  •  北海茫月
    2020-12-07 12:03

    Peter Rowell, thanks for your response. It was a tremendous help. This is what I did to get it working. Only had to change one file in djang.contrib.sessions.

    In django/contrib/sessions/models.py, add the user_id to the table (add to DB table manually or drop table and run manage.py syncdb).

    class Session(models.Model):
    
        ...
    
        user_id = models.IntegerField(_('user_id'), null=True)
    
        ...
    
        def save(self, *args, **kwargs):
            user_id = self.get_decoded().get('_auth_user_id')
            if ( user_id != None ):
                self.user_id = user_id
    
            # Call the "real" save() method.
            super(Session, self).save(*args, **kwargs)
    

    Now in your view where you do login (if you use django's base login, you will have to override it)

    # On login, destroy all prev sessions
            # This disallows multiple logins from different browsers
            dbSessions = Session.objects.filter( user_id = request.user.id )
            for index, dbSession in enumerate( dbSessions ):
                if ( dbSession.session_key != request.session.session_key ):
                    dbSession.delete()
    

    This worked for me.

提交回复
热议问题