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 (
"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, "<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
}