2011-11-03 36 views
6

雖然我對AppEngine/Python運行時非常有經驗,但我是Go運行時的新手。我的第一個應用程序即將準備推出,但我仍然需要提供用戶登錄的功能。我希望使用OpenID,因爲我不希望用戶擁有Google ID。使用AppEngine/Go Users API和OAuth:代碼示例,工作流程,任何幫助?

然而,似乎沒有或幾乎沒有工作的例子擺在那裏,和AppEngine上的文件明確地省略了功能的,我需要實現的內容:

func init() { 
    http.HandleFunc("/_ah/login_required", openIdHandler) 
} 

func openIdHandler(w http.ResponseWriter, r *http.Request) { 
    // ... 
} 

openIdHandler FUNC內善有善報?

據我所知,我需要提供一個頁面,允許用戶選擇多個OpenId提供程序之一併爲該系統輸入其Id。之後我不知道該怎麼做。什麼是工作流程?有誰知道我可以查看的任何示例代碼,以瞭解我必須做什麼以及我必須處理哪些數據的一般概念?我的所有精通Google-fu都沒有帶領我。

爲了清楚起見,我不打算與這些OpenId提供商提供的任何服務交互;我不想創建推文或Buzz。我不想訪問聯繫人,文檔,牆貼或其他任何東西。我只想要一個可以在我的應用程序中使用的認證credenital,以限制用戶只能訪問他或她自己的數據。

回答

10

如果我很好理解你 - 你需要,不。 我爲go-lang重寫了python示例(Federated login and logout)。希望這個幫助。

package gae_go_openid_demo 

import (
    "fmt" 
    "os" 
    "http" 

    "appengine" 
    "appengine/user" 
) 

func init() { 
    http.HandleFunc("/", hello) 
    http.HandleFunc("/_ah/login_required", openIdHandler) 
} 

func hello(w http.ResponseWriter, r *http.Request) { 
    c := appengine.NewContext(r) 
    u := user.Current(c) 
    if u != nil { 
     url, err := user.LogoutURL(c, "/") 
     check(err); 
     fmt.Fprintf(w, "Hello, %s! (<a href='%s'>Sign out</a>)", u, url) 
    } else { 
     fmt.Fprintf(w, "Please, <a href='/_ah/login_required'>login</a>.") 
    } 

} 

func openIdHandler(w http.ResponseWriter, r *http.Request) { 
    providers := map[string]string { 
     "Google" : "www.google.com/accounts/o8/id", // shorter alternative: "Gmail.com" 
     "Yahoo" : "yahoo.com", 
     "MySpace" : "myspace.com", 
     "AOL"  : "aol.com", 
     "MyOpenID" : "myopenid.com", 
     // add more here 
    } 

    c := appengine.NewContext(r) 
    fmt.Fprintf(w, "Sign in at: ") 
    for name, url := range providers { 
     login_url, err := user.LoginURLFederated(c, "/", url) 
     check(err); 
     fmt.Fprintf(w, "[<a href='%s'>%s</a>]", login_url, name) 
    } 
} 

// check aborts the current execution if err is non-nil. 
func check(err os.Error) { 
    if err != nil { 
     panic(err) 
    } 
}