From 7f323b5abe39e44bc1c641a200a5cabe91d7f414 Mon Sep 17 00:00:00 2001 From: evalphobia Date: Wed, 11 Mar 2020 02:26:03 +0900 Subject: [PATCH] oauth_twitter_callback.go: fix avatar icon and account url for Twitter --- api/oauth_twitter_callback.go | 63 ++++++++++++++++++++++++----------- 1 file changed, 43 insertions(+), 20 deletions(-) diff --git a/api/oauth_twitter_callback.go b/api/oauth_twitter_callback.go index 3815a9c..6401465 100644 --- a/api/oauth_twitter_callback.go +++ b/api/oauth_twitter_callback.go @@ -2,6 +2,7 @@ package main import ( "encoding/json" + "errors" "fmt" "io/ioutil" "net/http" @@ -52,33 +53,20 @@ func twitterCallbackHandler(w http.ResponseWriter, r *http.Request) { return } - var res map[string]interface{} + var res twitterOAuthReponse if err = json.NewDecoder(resp.Body).Decode(&res); err != nil { fmt.Fprintf(w, "Error: %s\n", err.Error()) return } - - if res["email"] == nil { - fmt.Fprintf(w, "Error: no email address returned by Twitter") + if err := res.validate(); err != nil { + fmt.Fprintf(w, "Error: %s\n", err.Error()) return } - email := res["email"].(string) - - if res["name"] == nil { - fmt.Fprintf(w, "Error: no name returned by Twitter") - return - } - - name := res["name"].(string) - - link := "undefined" - photo := "undefined" - if res["handle"] != nil { - handle := res["screen_name"].(string) - link = "https://twitter.com/" + handle - photo = "https://twitter.com/" + handle + "/profile_image" - } + email := res.Email + name := res.Name + link := res.getLinkURL() + photo := res.getImageURL() c, err := commenterGetByEmail("twitter", email) if err != nil && err != errorNoSuchCommenter { @@ -110,3 +98,38 @@ func twitterCallbackHandler(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "") } + +// response from Twitter API. +// ref: https://developer.twitter.com/en/docs/tweets/data-dictionary/overview/user-object +type twitterOAuthReponse struct { + Email string `json:"email"` + Name string `json:"name"` + ScreenName string `json:"screen_name"` + // normal image size is 48x48. + // ref: https://developer.twitter.com/en/docs/accounts-and-users/user-profile-images-and-banners + ImageURL string `json:"profile_image_url_https"` +} + +func (r twitterOAuthReponse) validate() error { + if r.Email == "" { + return errors.New("no email address returned by Twitter") + } + if r.Name == "" { + return errors.New("no name returned by Twitter") + } + return nil +} + +func (r twitterOAuthReponse) getLinkURL() string { + if r.ScreenName == "" { + return "undefined" + } + return fmt.Sprintf("https://twitter.com/%s", r.ScreenName) +} + +func (r twitterOAuthReponse) getImageURL() string { + if r.ImageURL == "" { + return "undefined" + } + return r.ImageURL +}