1

I am using djangorestframework-simplejwt==4.4.0 in my application for User Authentication. But by default it provides multiple logins for a single user i.e. I can generate n number of tokens.

What I want is to prevent multiple logins from the same account. How do I do that?

Models.py

class Company(models.Model):
    region_coices = (('East', 'East'), ('West', 'West'), ('North', 'North'), ('South', 'South'))
    category = (('Automotive', 'Automotive'), ('F.M.C.G.', 'F.M.C.G.'), ('Pharmaceuticals', 'Pharmaceuticals'),
                ('Ecommerce', 'Ecommerce'), ('Others', 'Others'))
    type = models.ManyToManyField(CompanyTypes)
    name = models.CharField(max_length=500, default=0)
    email = models.EmailField(max_length=50, default=0)


class User(AbstractUser):
    is_admin = models.BooleanField(default=False)
    company = models.ForeignKey(Company, on_delete=models.CASCADE, blank=True, null=True)

    @property
    def full_name(self):
        return self.first_name + " " + self.last_name



class EmployeeTypes(models.Model):
    emp_choices = (('Pool Operator', 'Pool Operator'), ('Consignor', 'Consignor'), ('Consignee', 'Consignee'))
    emp_type = models.CharField(max_length=500, default='Pool Operator', choices=emp_choices)


class Employee(models.Model):
    role_choices = (('CRUD', 'CRUD'), ('View', 'View'))
    user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
    company = models.ForeignKey(Company, on_delete=models.CASCADE, related_name="company")
    name = models.CharField(max_length=500, default=0)

Urls.py

path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
Rahul Sharma
  • 2,187
  • 6
  • 31
  • 76

1 Answers1

0

You need to implement a login mechanism yourself.

You can store user refresh token with his user agent and IP address in the database or some cache systems like Redis, when the user wants to refresh the access token, check provided refresh token alongside his IP address and user agent against the database and if any token exists, give him a new access token.

On login, drop unexpired refresh tokens if exist in the database for the user that has a successful login, and then insert the new refresh token you just generated, in the database.

By implementing this solution, if the user tries to log in again, he will be automatically logged out from previous logins.