[Fixed]-Allowing login depending on hostname (remote)

1👍

I’ve done similar things in the past, it’s quite easy actually. You simply need to replace the normal authentication backend with your own: https://docs.djangoproject.com/en/1.8/topics/auth/customizing/#writing-an-authentication-backend

The default backend looks like this: https://github.com/django/django/blob/master/django/contrib/auth/backends.py#L113-143

class ModelBackend(object):
    ...

    def authenticate(self, remote_user):
        """
        The username passed as ``remote_user`` is considered trusted.  This
        method simply returns the ``User`` object with the given username,
        creating a new ``User`` object if ``create_unknown_user`` is ``True``.
        Returns None if ``create_unknown_user`` is ``False`` and a ``User``
        object with the given username is not found in the database.
        """
        if not remote_user:
            return
        user = None
        username = self.clean_username(remote_user)

        UserModel = get_user_model()

        # Note that this could be accomplished in one try-except clause, but
        # instead we use get_or_create when creating unknown users since it has
        # built-in safeguards for multiple threads.
        if self.create_unknown_user:
            user, created = UserModel._default_manager.get_or_create(**{
                UserModel.USERNAME_FIELD: username
            })
            if created:
                user = self.configure_user(user)
        else:
            try:
                user = UserModel._default_manager.get_by_natural_key(username)
            except UserModel.DoesNotExist:
                pass
        return user

What you need to do is inherit this class and add the remote host check to it.

Something along the lines of this:

class HostnameAuthenticationBackend(backends.ModelBackend):
    def authenticate(self, username=None, password=None,
                     hostname=None, **kwargs):
        user = backends.ModelBackend.authenticate(
            username=username, password=password, **kwargs)
        if user:
            # check the hostname and groups here
            if hostname_correct:
                return user

The one tiny snag you’ll hit is that by default the hostname won’t be available, you’ll have to pass it along from the login view to the authentication backend.

👤Wolph

0👍

If you want to allow users from outside of the intranet to access the page, but not to be able to login (except of those with special permissions), then I suggest overriding the default login view and check whether the user that is trying to log in has appropriate permissions.

Leave a comment