Created
April 19, 2015 13:23
-
-
Save keima/4ef7fd13a3de3318b351 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package discipline | |
import ( | |
"github.com/gorilla/securecookie" | |
"github.com/hnakamur/gaesessions" | |
"github.com/ChimeraCoder/anaconda" | |
"net/http" | |
"appengine" | |
"github.com/garyburd/go-oauth/oauth" | |
) | |
var sessionStore = gaesessions.NewMemcacheDatastoreStore("", "", | |
gaesessions.DefaultNonPersistentSessionDuration, | |
securecookie.GenerateRandomKey(128)) | |
func GetTwitterHandler(w http.ResponseWriter, r *http.Request) { | |
c := appengine.NewContext(r) | |
// OAuth通すだけなので返り値の取得不要 | |
NewTwitterApi(c, "","") | |
url, tempCred, err := anaconda.AuthorizationURL("") // redirectUrl(c) | |
if err != nil { | |
http.Error(w, err.Error(), http.StatusInternalServerError) | |
return | |
} | |
session, _ := sessionStore.Get(r, "discipline") | |
session.Values["temp_token"] = tempCred.Token | |
session.Values["temp_secret"] = tempCred.Secret | |
session.Options.HttpOnly = true | |
err = session.Save(r, w) | |
if err != nil { | |
http.Error(w, err.Error(), http.StatusInternalServerError) | |
return | |
} | |
w.Header().Set("Location", url) | |
w.WriteHeader(http.StatusFound) | |
} | |
func GetTwitterCallbackHandler(w http.ResponseWriter, r *http.Request) { | |
session, err := sessionStore.Get(r, "discipline") | |
if err != nil { | |
http.Error(w, err.Error(), http.StatusInternalServerError) | |
return | |
} | |
if session.IsNew { | |
http.Error(w, "Session error", http.StatusBadRequest) | |
return | |
} | |
tempCred := oauth.Credentials{ | |
Token: session.Values["temp_token"].(string), | |
Secret: session.Values["temp_secret"].(string), | |
} | |
verifier := r.FormValue("oauth_verifier") | |
cred, _, err := anaconda.GetCredentials(&tempCred, verifier) | |
if err != nil { | |
http.Error(w, err.Error(), http.StatusInternalServerError) | |
return | |
} | |
session.Values["token"] = cred.Token | |
session.Values["secret"] = cred.Secret | |
err = session.Save(r, w) | |
if err != nil { | |
http.Error(w, err.Error(), http.StatusInternalServerError) | |
return | |
} | |
w.Header().Set("Location", "/") | |
w.WriteHeader(http.StatusFound) | |
} | |
func RemoveExpiredSessionsHandler(w http.ResponseWriter, r *http.Request) { | |
c := appengine.NewContext(r) | |
gaesessions.RemoveExpiredDatastoreSessions(c, "") | |
} | |
func redirectUrl(c appengine.Context) string { | |
scheme := "https://" | |
if appengine.IsDevAppServer() { | |
scheme = "http://" | |
} | |
return scheme + appengine.DefaultVersionHostname(c) + "/api/auth/twitter/callback" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment