go-bouquins/bouquins/google.go
2017-09-09 12:28:46 +02:00

80 lines
2.2 KiB
Go

package bouquins
import (
"encoding/json"
"fmt"
"log"
"net/http"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
)
// GoogleProvider implements OAuth2 client with google account
type GoogleProvider string
type GoogleTokenInfo struct {
IssuedTo string `json:"issued_to"`
Audience string `json:"audience"`
UserId string `json:"user_id"`
Scope string `json:"scope"`
ExpiresIn int64 `json:"expires_in"`
Email string `json:"email"`
VerifiedEmail bool `json:"verified_email"`
AccessType string `json:"access_type"`
}
func init() {
Providers = append(Providers, GoogleProvider("google"))
}
// Name returns name of provider
func (p GoogleProvider) Name() string {
return string(p)
}
// Label returns label of provider
func (p GoogleProvider) Label() string {
return "Google"
}
// Icon returns icon path for provider
func (p GoogleProvider) Icon() string {
return "googleicon"
}
func (p GoogleProvider) Config(conf *BouquinsConf) *oauth2.Config {
// FIXME client ID and secret in conf file
return &oauth2.Config{
ClientID: "51149464161-8mu7ohfujn655p0qas5uj1echn36m9uu.apps.googleusercontent.com",
ClientSecret: "5IWFxm_9NoWb5hfGt6Wj1oSV",
Scopes: []string{"https://www.googleapis.com/auth/userinfo.email"},
Endpoint: google.Endpoint,
RedirectURL: "http://localhost:9000" + URLCallback, // FIXME
}
}
// GetUser returns github primary email
func (p GoogleProvider) GetUser(token *oauth2.Token) (string, error) {
// POST https://www.googleapis.com/oauth2/v2/tokeninfo access_token
apiRes, err := http.Post("https://www.googleapis.com/oauth2/v2/tokeninfo?access_token="+token.AccessToken, "application/json", nil)
defer apiRes.Body.Close()
if err != nil {
log.Println("Auth error", err)
return "", fmt.Errorf("Authentification error")
}
dec := json.NewDecoder(apiRes.Body)
var tokenInfo GoogleTokenInfo
err = dec.Decode(&tokenInfo)
if err != nil {
log.Println("Error reading google API response", err)
return "", fmt.Errorf("Error reading google API response")
}
var userEmail string
if tokenInfo.VerifiedEmail {
userEmail = tokenInfo.Email
}
log.Println("User email:", userEmail)
return userEmail, nil
}