2013-10-01 64 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

相關問題