2015-04-04 21 views
1

我剛開始在Django工作,它很棒!用Authomatic驗證django - 最佳工作流程

我希望我的web應用程序能夠通過他們的twitter帳戶訪問有限數量的人。爲了實現這一點,我使用了插件Authomatic。

This是一個初學者的例子,展示瞭如何在Django中使用Authomatic。從此,我用下面的代碼片段:

def login(request, provider_name): 
    # We we need the response object for the adapter. 
    response = HttpResponse() 

    # Start the login procedure. 
    result = authomatic.login(DjangoAdapter(request, response), provider_name) 

    if result: 
     response.write('<a href="..">Home</a>') 

     elif result.user: 
      if not (result.user.name and result.user.id): 
       result.user.update() 

      var username = result.user.name 
      var id = result.user.id 
return response 

我的問題是:檢查用戶名是否允許Twitter用戶之一,以後我怎麼登錄,從而使用戶根瀏覽所有受保護的頁面?我習慣使用這樣的東西:

user = authenticate(username=username, password=password) 
if user is not None: 
    if user.is_active: 
     login(request, user) 

但問題是,Twitter用戶沒有分配給他們的用戶對象。我能想到的唯一的事情是硬編碼「允許」用戶在我的代碼默認,但似乎很狡猾......

編輯:我試圖執行阿什溫的回答,但是這給了我這樣的:

#我們需要適配器的響應對象。 響應=的HttpResponse()所有的

# Start the login procedure. 
result = authomatic.login(DjangoAdapter(request, response), provider_name) 
if result: 
    response.write('<a href="..">Home</a>') 
if result.error: 
    # Login procedure finished with an error. 
    response.write('<h2>Damn that error: {0}</h2>'.format(result.error.message)) 

elif result.user: 
    # We need to update the user to get more info. 
    if not (result.user.name and result.user.id): 
     result.user.update() 

    # Welcome the user. 
    response.write(u'<h1>Hi {0}</h1>'.format(result.user.name)) 
    response.write(u'<h2>Your id is: {0}</h2>'.format(result.user.id)) 
    response.write(u'<h2>Your email is: {0}</h2>'.format(result.user.email)) 

    # if result.user.id == 110740012624414845989: 
    uname = result.user.id 
    pwd = '** RANDOM PASSOWRD I SHOULD HAVE? **' 
    user = authenticate(username=uname, password=pwd) 
    login(request, user) 

首先,我無法想象,這是很好的做法,在我的代碼這樣的密碼writter。第二我得到錯誤提供者名稱「用戶名」未指定!

有人知道我在做什麼錯嗎?

回答

0

您可以爲所有允許的用戶創建單獨的用戶對象,然後該作業將非常簡單。只要檢查用戶名是否在數據庫中可用,驗證並登錄請求。

+0

感謝您的回答,但如果我沒有密碼,如何驗證這些用戶對象? – hY8vVpf3tyR57Xib 2015-04-04 12:03:17

+0

@ user3361028:您可以使用無密碼驗證。這應該有所幫助:http://stackoverflow.com/questions/2787650/manually-logging-in-a-user-without-password – 2015-04-04 13:30:28