'how to create login authentication based on some condition in django restframework

Hi Everyone current I am using default token base authentication, but now I need to some restriction on login time, I have a model called as Team where I assign a team name to multiple managers(users) I need to login only those users have team. also login based on username, password and get output token and team name, please help me out.

models.py

class Team(BaseModel):
    name = models.CharField(max_length=30)
    Logo = models.ImageField(upload_to=team_directory_path, null=True, blank=True)
    managers = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True)
    city = models.ForeignKey(City, models.CASCADE, verbose_name='City')

    def __str__(self):
        return self.name


Solution 1:[1]

You need to implement custom authentication backend:

Customizing authentication in Django

in the authenticate method of your custom AuthBackend you must return only those users which have team. sample code:

from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend

User = get_user_model()


class AuthBackend(ModelBackend):
    """
    Authenticates against settings.AUTH_USER_MODEL.
    """

    def authenticate(self, request, username=None, password=None, **kwargs):
        if username is None:
            username = kwargs.get(User.USERNAME_FIELD)
        if username is None or password is None:
            return
        try:
            user = User.objects.get(username=username)
        except User.DoesNotExist:
            # Run the default password hasher once to reduce the timing
            # difference between an existing and a nonexistent user (#20760).
            User().set_password(password)
        else:
            user_is_active = self.user_can_authenticate(user)
            user_has_team = user.team_set.all().count() > 0  # Check this line
            if user.check_password(password) and user_is_active and user_has_team:
                return user

    def get_user(self, user_id):
        try:
            user = User.objects.get(pk=user_id)
        except User.DoesNotExist:
            return None
        return user if self.user_can_authenticate(user) else None

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1