2013-10-01 59 views
5

我是Django的新手。使用django-allauth我设置了单击登录。我从google api控制台获取了我的域凭据(client_id和secret_key)。但问题是,Django的allauth是让我从谷歌的任何帐号登录,而我想要的电子邮件地址被限制到我的域名(@ example.com,而不是@ gmail.com)django-allauth:只允许来自特定谷歌应用程序域的用户

Django的社会身份验证为此列出了白名单域参数,如何在allauth中包含此信息? 我发现Django的allauth更容易在Django的社会身份验证

任何帮助,将不胜感激花费数小时后成立。

回答

9

回答我的question-

这其实是非常简单的。你想要做的就是在用户通过社交账户提供者认证之后并且在他可以进入他的个人资料页面之前停止登录。您可以与DefaultSocialAccountAdapter类的

pre_social_login方法做到这一点allauth/socialaccount/adaptor.py

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. 

这样做

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')) 

这个不是一个确切的实现,但像这样的作品。

+1

并在创建自定义适配器后,根据插件文档中的配置部分将其注册为'settings.SOCIALACCOUNT_ADAPTER'。 – Matt

+2

供将来参考我发现我不得不使用'u = sociallogin.user',否则如果用户之前不存在,我会得到一个错误。 –

0

你可以在重写allauth的allauth.socialaccount.forms.SignupForm中执行一些操作,并在注册过程中检查域。 Discalmer:这一切都是在没有测试的情况下编写的,但是其中的一些内容应该可以工作。

# settings.py 
# not necesarry, but it would be a smart way to go instead of hardcoding it 
ALLOWED_DOMAIN = 'example.com' 

# forms.py 
from django.conf import settings 
from allauth.socialaccount.forms import SignupForm 


class MySignupForm(SignupForm): 

    def clean_email(self): 
     data = self.cleaned_data['email'] 
     if data.split('@')[1].lower() == settings.ALLOWED_DOMAIN: 
      raise forms.ValidationError(_(u'domena!')) 
     return data 

在你的URL重写allauth默认值(之前包括Django的allauth的把这个)

# urls.py 

from allauth.socialaccount.views import SignupView 
from .forms import MySignupForm 


urlpatterns = patterns('', 
    # ... 
    url(r"^social/signup/$", SignupView.as_view(form_class=MySignupForm), name="account_signup"), 
    # ... 
) 

我不知道对于 “^社会/注册/ $”,重新检查。

+0

正确的网址是accounts/social/signup。但这不起作用。我不想在用Google登录后显示allauth注册表单。我想要的是,在谷歌登录后立即,他们被引导到他们的个人资料页面或他们得到一个错误消息说 - 我们只接受来自example.com域的用户。 – aishpant

+0

我应该使用django-allauth的pre_social_login信号来进行域匹配吗? – aishpant

相关问题