oauth_twitter_callback.go: fix avatar icon and account url for Twitter

This commit is contained in:
evalphobia 2020-03-11 02:26:03 +09:00 committed by Adhityaa Chandrasekar
parent b14de2eb53
commit 7f323b5abe

View File

@ -2,6 +2,7 @@ package main
import ( import (
"encoding/json" "encoding/json"
"errors"
"fmt" "fmt"
"io/ioutil" "io/ioutil"
"net/http" "net/http"
@ -52,33 +53,20 @@ func twitterCallbackHandler(w http.ResponseWriter, r *http.Request) {
return return
} }
var res map[string]interface{} var res twitterOAuthReponse
if err = json.NewDecoder(resp.Body).Decode(&res); err != nil { if err = json.NewDecoder(resp.Body).Decode(&res); err != nil {
fmt.Fprintf(w, "Error: %s\n", err.Error()) fmt.Fprintf(w, "Error: %s\n", err.Error())
return return
} }
if err := res.validate(); err != nil {
if res["email"] == nil { fmt.Fprintf(w, "Error: %s\n", err.Error())
fmt.Fprintf(w, "Error: no email address returned by Twitter")
return return
} }
email := res["email"].(string) email := res.Email
name := res.Name
if res["name"] == nil { link := res.getLinkURL()
fmt.Fprintf(w, "Error: no name returned by Twitter") photo := res.getImageURL()
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"
}
c, err := commenterGetByEmail("twitter", email) c, err := commenterGetByEmail("twitter", email)
if err != nil && err != errorNoSuchCommenter { if err != nil && err != errorNoSuchCommenter {
@ -110,3 +98,38 @@ func twitterCallbackHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "<html><script>window.parent.close()</script></html>") fmt.Fprintf(w, "<html><script>window.parent.close()</script></html>")
} }
// 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
}