0

In my project, I should create personal type user and company type user they have different attributes. I can create them with different models but I cannot implement both in auth system at the same time? I wonder if it is possible?

ihsancemil
  • 432
  • 5
  • 16
  • what about inheriting the `AbstractUser` in both models? – Ravi Kumar Jun 20 '16 at 16:14
  • @RaviKumar I can create users like you said but in settings.py I have to choise which model did I used for auth – ihsancemil Jun 20 '16 at 17:37
  • 1
    I hope this [link 1](http://stackoverflow.com/questions/30495979/django-1-8-multiple-custom-user-types) and [link 2](http://stackoverflow.com/questions/19253842/whats-the-proper-way-to-use-multiple-auth-user-model-in-django-1-5) may help you to get start. – Ravi Kumar Jun 20 '16 at 18:10
  • @RaviKumar thanks. I hope second link is enough for me :)) – ihsancemil Jun 20 '16 at 19:04

1 Answers1

0

As stated in django docs you can write your own AUTHENTICATION_BACKENDS. For example:

class UserProfileModelBackend(ModelBackend):
    def authenticate(self, username=None, password=None):
        try:
            user = self.user_class.objects.get(username=username)
            if user.check_password(password):
                return user
        except self.user_class.DoesNotExist:
            return None

    def get_user(self, user_id):
        try:
            return self.user_class.objects.get(pk=user_id)
        except self.user_class.DoesNotExist:
            return None

    @property
    def user_class(self):
        if not hasattr(self, '_user_class'):
            self._user_class = apps.get_model(*settings.AUTH_USER_MODEL.split('.', 2))
            if not self._user_class:
                raise ImproperlyConfigured('Could not get custom user model')
        return self._user_class

And then add this auth-backend to in AUTHENTICATION_BACKENDS in settings.py. For more information see Writing an authentication backend

When somebody calls django.contrib.auth.authenticate() Django tries authenticating across all of its authentication backends. If the first authentication method fails, Django tries the second one, and so on, until all backends have been attempted.

Be careful:

The order of AUTHENTICATION_BACKENDS matters, so if the same username and password is valid in multiple backends, Django will stop processing at the first positive match.

M.Void
  • 2,764
  • 2
  • 29
  • 44