overflow_probe/oauth_api/oauth.go

62 lines
1.3 KiB
Go
Raw Normal View History

2017-08-03 10:08:34 +00:00
package main
import (
"encoding/json"
"fmt"
"golang.org/x/net/context"
"golang.org/x/oauth2"
"io/ioutil"
"log"
"net/http"
)
type UserSNSInfo struct {
//Id string `json:"id"`
Name string `json:"name"`
Email string `json:"email"`
AccessToken string
}
func GetAccessToken(config *oauth2.Config, code string) *oauth2.Token {
token, err := config.Exchange(context.Background(), code)
if err != nil {
log.Fatal(err)
}
fmt.Println(token.AccessToken, "Expire :", token.Expiry, "type: ", token.TokenType)
return token
}
func GetSNSInfo(config *oauth2.Config, code string, snsType SNSType) UserSNSInfo {
var response *http.Response
var err error
accessToken := GetAccessToken(config, code)
if snsType == FB_TYPE {
response, err = http.Get("https://graph.facebook.com/me?fields=id,name,email&access_token=" + accessToken.AccessToken)
} else if snsType == GG_TYPE {
response, err = http.Get("https://www.googleapis.com/oauth2/v3/userinfo?access_token=" + accessToken.AccessToken)
}
if err != nil {
fmt.Println(err.Error())
}
data, err := ioutil.ReadAll(response.Body)
if err != nil {
fmt.Println(err.Error())
}
userinfo := UserSNSInfo{}
json.Unmarshal([]byte(data), &userinfo)
userinfo.AccessToken = accessToken.AccessToken
fmt.Printf("Username %s and email is %s<br>", userinfo.Name, userinfo.Email)
return userinfo
}