go-bouquins/bouquins/google.go

84 lines
2.1 KiB
Go
Raw Normal View History

2017-09-09 09:06:04 +00:00
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
2017-09-09 11:27:07 +00:00
type googleTokenInfo struct {
2017-09-09 09:06:04 +00:00
IssuedTo string `json:"issued_to"`
Audience string `json:"audience"`
2017-09-09 11:27:07 +00:00
UserID string `json:"user_id"`
2017-09-09 09:06:04 +00:00
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 {
2017-09-09 10:28:46 +00:00
return "googleicon"
2017-09-09 09:06:04 +00:00
}
2017-09-09 11:27:07 +00:00
// Config returns OAuth configuration for this provider
func (p GoogleProvider) Config(conf *Conf) *oauth2.Config {
2017-09-09 11:10:29 +00:00
for _, c := range conf.ProvidersConf {
if c.Name == p.Name() {
return &oauth2.Config{
ClientID: c.ClientID,
ClientSecret: c.ClientSecret,
Scopes: []string{"https://www.googleapis.com/auth/userinfo.email"},
Endpoint: google.Endpoint,
2017-09-09 11:27:07 +00:00
RedirectURL: conf.ExternalURL + URLCallback,
2017-09-09 11:10:29 +00:00
}
}
2017-09-09 09:06:04 +00:00
}
2017-09-09 11:10:29 +00:00
return nil
2017-09-09 09:06:04 +00:00
}
// GetUser returns github primary email
2019-09-08 09:23:22 +00:00
func (p GoogleProvider) GetUser(app *Bouquins, token *oauth2.Token) (string, error) {
2017-09-09 09:06:04 +00:00
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)
2017-09-09 11:27:07 +00:00
var tokenInfo googleTokenInfo
2017-09-09 09:06:04 +00:00
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
}