0

I want to restrict multiple logins for which i want to access request.user.is_authenticated attribute , i tried to access this attribute in the middlewares in the response cycle when login view call has been made but still in both the cycles like from request to response and back this attricute is false , so needs help

my models.py

class LoggedInUser(models.Model):
    user = models.ForeignKey(User, related_name='logged_in_user', on_delete =models.CASCADE, null=True, blank=True)
    session_key = models.OneToOneField(Session, on_delete=models.CASCADE, null=True, blank=True)

    def __str__(self):
        return self.user.username

my signals.py

@receiver(user_logged_in)
def delete_other_active_sessions(sender, user, request, **kwargs):
    Session.objects.filter(loggedinuser__user=user).delete()
    print('here inside signals')
    #save current session
    request.session.save()

    LoggedInUser.objects.get_or_create(user=user, session = request.session.session_key)

user_logged_in.connect(delete_other_active_sessions)

my apps.py

class AccountsConfig(AppConfig):
    default_auto_field = "django.db.models.BigAutoField"
    name = "accounts"


    def ready(self):
        import accounts.signals

This is how i am trying to restrict multiple logins but signals are not fired needs help

  • The `user.is_authenticated` attribute won't be useful to you for that purpose. It is _always_ going to return `True` in case it is not an `AnonymousUser` instance. That attribute does not track if a user is logged in or not. – Abdul Aziz Barkat Nov 12 '21 at 03:41
  • Does this answer your question? [Why is user.is\_authenticated asserting true after logout](https://stackoverflow.com/questions/64414009/why-is-user-is-authenticated-asserting-true-after-logout) – Abdul Aziz Barkat Nov 12 '21 at 03:49
  • Then how can i check if a user is logged in or not – Dhruv Singhal Nov 12 '21 at 04:07
  • Please answer how can i check if user is authenticated or not – Dhruv Singhal Nov 12 '21 at 06:17
  • See https://stackoverflow.com/questions/2723052/how-to-get-the-list-of-the-authenticated-users and various other similar questions. You need to check the session (If you use database backed sessions) map it to the user some way (People do this by attaching to the user logged in signal, etc.). – Abdul Aziz Barkat Nov 12 '21 at 06:28
  • I have updated my approach but signals are not firing i dont know why – Dhruv Singhal Nov 12 '21 at 07:45

0 Answers0