django-allauth:仅允许来自特定Google Apps域的用户

ais*_*ant 5 django django-allauth

我是Django的新手.使用django-allauth我已经设置了单击登录.我从google api console获取了我的域凭据(client_id和secret_key).但问题是django-allauth 让我从任何谷歌帐户登录,而我希望将电子邮件地址限制在我的域名(@ example.com而非@gmail.com)

django-social-auth具有白名单域名参数,如何在allauth中包含此信息?在django-social-auth上花了几个小时后,我发现django-allauth更容易设置

任何帮助将非常感激.

ais*_*ant 11

回答我自己的问题 -

这实际上非常简单.您想要做的是在用户通过社交帐户提供商进行身份验证之后以及可以进入其个人资料页面之前停止登录.你可以这样做

allauth / socialaccount/adaptor.py中DefaultSocialAccountAdapter类的pre_social_login 方法

    Invoked just after a user successfully authenticates via a
    social provider, but before the login is actually processed
    (and before the pre_social_login signal is emitted).
    You can use this hook to intervene, e.g. abort the login by
    raising an ImmediateHttpResponse
    Why both an adapter hook and the signal? Intervening in
    e.g. the flow from within a signal handler is bad -- multiple
    handlers may be active and are executed in undetermined order.
Run Code Online (Sandbox Code Playgroud)

做点什么

from allauth.socialaccount.adaptor import DefaultSocialAccountAdapter

class MySocialAccount(DefaultSocialAccountAdapter):
    def pre_social_login(self, request, sociallogin):
        u = sociallogin.account.user
        if not u.email.split('@')[1] == "example.com"
            raise ImmediateHttpResponse(render_to_response('error.html'))
Run Code Online (Sandbox Code Playgroud)

这不是一个确切的实现,但这样的工作.

  • 为了将来的参考我发现我必须使用`u = sociallogin.user`否则如果用户以前不存在我将收到错误. (3认同)