如何'monkey patch'或覆盖User.is_authenticated()?使用 django-lazysignup 时产生问题



我安装了django-lazysignup,现在面临着User.is_authenticated((返回True的挑战,因为这些用户实际上并不是经过身份验证的用户,而是懒惰的注册用户。我可以用自己的函数更新代码中对User.is_authenticated((的任何检查。然而,其他包,如django-allauth,检查此方法以确定用户是否已经登录,并从尝试访问登录页面重定向。

class RedirectAuthenticatedUserMixin(object):
    def dispatch(self, request, *args, **kwargs):
        self.request = request
        if request.user.is_authenticated():
            redirect_to = self.get_authenticated_redirect_url()
            response = HttpResponseRedirect(redirect_to)
            return _ajax_response(request, response)
...

是否有任何建议不需要在我包含的每个包中替换is_authenticated((?他们中的大多数人似乎都希望它能以一种特殊的方式发挥作用,而django-lazysgup却对此不以为然。我可以用一个新的is_authenticated((方法对用户模型进行猴子补丁吗?如果可能的话,我在哪里可以这样做,以便将其附加到页面请求中?

您正在使用的

django-lazysignup允许您提供自定义的LazyUser类(此处(。您所需要做的就是用定义的is_authenticated方法编写lazysignup.models.LazyUser的子类,并将其设置为settings.LAZYSIGNUP_USER_MODEL

但这并不是你麻烦的结束。很多django应用程序假设经过身份验证的用户具有某些属性。主要是is_staffis_superuserpermissionsgroups。首先,django.contrib.admin需要他们检查是否可以让用户进入,以及向他展示什么。看看django.contrib.auth.models.AnonymousUser是如何模拟它们并复制的。备注:看看AnonymousUser是如何而不是子类化任何用户类或db.Model的。提供的用户类只需要嘎嘎作响。

最终只需要替换对User.is_authenticated((.的所有调用

为了防止django-allauth从登录页面重定向懒惰用户,这看起来像这样:

from allauth.account.views import AjaxCapableProcessFormViewMixin
def _ajax_response(request, response, form=None):
    if request.is_ajax():
        if (isinstance(response, HttpResponseRedirect)
            or isinstance(response, HttpResponsePermanentRedirect)):
            redirect_to = response['Location']
        else:
            redirect_to = None
        response = get_adapter().ajax_response(request,
                                           response,
                                           form=form,
                                           redirect_to=redirect_to)
    return response

class RedirectUserWithAccountMixin(object):
    def dispatch(self, request, *args, **kwargs):
        self.request = request
        if user_has_account(request.user):
            redirect_to = self.get_authenticated_redirect_url()
            response = HttpResponseRedirect(redirect_to)
            return _ajax_response(request, response)
        else:
            response = super(RedirectUserWithAccountMixin,
                             self).dispatch(request,
                                            *args,
                                            **kwargs)
        return response
    def get_authenticated_redirect_url(self):
        redirect_field_name = self.redirect_field_name
        return get_login_redirect_url(self.request,
                                      url=self.get_success_url(),
                                      redirect_field_name=redirect_field_name)
class LoginView(RedirectUserWithAccountMixin,
            AjaxCapableProcessFormViewMixin,
            FormView):
...

其中user_has_account((是我自己检查用户是否真的登录的方法。

最新更新