更改django-allauth的render_authentication_error行为

5
我是 Python/Django 新手,刚开始进行一项非常棒的项目。我需要让我的用户通过 Facebook 登录,并拥有特定的用户流程。我已经设置好了 django-allauth,一切都按照我需要的方式工作。我覆盖了 LOGIN_REDIRECT_URL,以便用户在登录时可以进入我想要的页面。
但是,当用户打开 Facebook 登录对话框并在不登录的情况下关闭它时,allauth.socialaccount.helpers.render_authentication_error 会呈现 authentication_error.html 模板,这不是我想要的行为。我希望用户简单地重定向到登录页面。
是的,我知道我可以通过将其放入 TEMPLATE_DIRS 来简单地覆盖模板,但那样 URL 将不同。
我得出结论,我需要一个中间件来拦截 HTTP 请求的响应。
from django.shortcuts import redirect

class Middleware():
    """
    A middleware to override allauth user flow
    """
    def __init__(self):
        self.url_to_check = "/accounts/facebook/login/token/"

    def process_response(self, request, response):
        """
        In case of failed faceboook login
        """
        if request.path == self.url_to_check and\
                not request.user.is_authenticated():
            return redirect('/')

        return response 

但是我不确定我的解决方案的效率和它的Python风格(我刚刚想出这个词)。除了使用中间件或信号外,我是否还能做些什么来改变默认的django-allauth行为?

谢谢!

2个回答

0

我决定使用中间件,在URL形式为^/accounts/.*$的情况下,重定向到主页URL。

from django.shortcuts import redirect
import re


class AllauthOverrideMiddleware():
    """
    A middleware to implement a custom user flow
    """
    def __init__(self):
        # allauth urls
        self.url_social = re.compile("^/accounts/.*$")

    def process_request(self, request):

        # WE CAN ONLY POST TO ALLAUTH URLS
        if request.method == "GET" and\
           self.url_social.match(request.path):
            return redirect("/")

0
是的,我知道我可以通过将其放在我的TEMPLATE_DIRS中来简单地覆盖模板,但那么URL将不同。
覆盖模板不会更改URL。在您重写的模板中,您可以执行{{link1:客户端重定向}}到您喜欢的任何URL。

我的意思是URL与我想要在登录错误时重定向的根URL不同。无论如何,我选择简单地使用中间件,并将GET请求重定向到/accounts/*到根URL。 - Felix D.
很酷,很高兴你找到了解决方案。 - Matt Cooper

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接