允许登录取决于主机名(远程)

时间:2015-07-30 08:33:04

标签: django

我有一个Django内部网,可以使用ALLOWED_HOSTS设置在http(s):// somename /和http(s)://10.10.0.30/上访问:

  

ALLOWED_HOSTS = [u' 10.10.0.30',u' somename',]

现在我想允许某些用户同时登录远程网站。首先,我必须将我的外部网址(如somename.com)添加到ALLOWED_HOSTS;没问题。但从那一刻开始,每个的帐户都可以登录,这不是我想要的。

我在考虑使用一个名为PermitRemoteLogin的组 - 当用户属于该组时,将允许从主机somename.com登录。但我不确定实际的实施和/或这是否可行(?)。

搜索时,例如DjangoPackages,未找到任何结果。不知道以前是否已经这样做了吗?

2 个答案:

答案 0 :(得分:1)

我过去做过类似的事情,实际上很容易。您只需要用自己的https://docs.djangoproject.com/en/1.8/topics/auth/customizing/#writing-an-authentication-backend

替换普通的身份验证后端

默认后端如下所示:https://github.com/django/django/blob/master/django/contrib/auth/backends.py#L113-143

 case "remove":
        if(!empty($_SESSION["cart_item"])) {
            foreach($_SESSION["cart_item"] as $k => $v) {
                    if($_GET["id"] == $_SESSION["cart_item"][$k]['id'])
                        unset($_SESSION["cart_item"][$k]);      
                    if(empty($_SESSION["cart_item"]))
                        unset($_SESSION["cart_item"]);
            }
        }

    break;

您需要做的是继承此类并向其添加远程主机检查。

有些事情如下:

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

你要点击的一个小问题是,默认情况下主机名将不可用,你必须将它从登录视图传递到身份验证后端。

答案 1 :(得分:0)

如果您想允许来自Intranet外部的用户访问该页面,但不能登录(除了具有特殊权限的用户),那么我建议覆盖默认登录视图并检查用户是否是尝试登录具有适当的权限。