2015-03-30 19:30:27 +00:00
|
|
|
package providers
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/base64"
|
2015-05-21 03:23:48 +00:00
|
|
|
"encoding/json"
|
|
|
|
"errors"
|
2015-03-30 19:30:27 +00:00
|
|
|
"net/url"
|
|
|
|
"strings"
|
|
|
|
)
|
|
|
|
|
|
|
|
type GoogleProvider struct {
|
|
|
|
*ProviderData
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewGoogleProvider(p *ProviderData) *GoogleProvider {
|
2015-03-31 16:59:07 +00:00
|
|
|
p.ProviderName = "Google"
|
2015-03-30 19:30:27 +00:00
|
|
|
if p.LoginUrl.String() == "" {
|
|
|
|
p.LoginUrl = &url.URL{Scheme: "https",
|
|
|
|
Host: "accounts.google.com",
|
|
|
|
Path: "/o/oauth2/auth"}
|
|
|
|
}
|
|
|
|
if p.RedeemUrl.String() == "" {
|
|
|
|
p.RedeemUrl = &url.URL{Scheme: "https",
|
|
|
|
Host: "accounts.google.com",
|
|
|
|
Path: "/o/oauth2/token"}
|
|
|
|
}
|
2015-05-08 21:13:35 +00:00
|
|
|
if p.ValidateUrl.String() == "" {
|
|
|
|
p.ValidateUrl = &url.URL{Scheme: "https",
|
|
|
|
Host: "www.googleapis.com",
|
|
|
|
Path: "/oauth2/v1/tokeninfo"}
|
|
|
|
}
|
2015-03-30 19:30:27 +00:00
|
|
|
if p.Scope == "" {
|
|
|
|
p.Scope = "profile email"
|
|
|
|
}
|
|
|
|
return &GoogleProvider{ProviderData: p}
|
|
|
|
}
|
|
|
|
|
2015-05-21 03:23:48 +00:00
|
|
|
func (s *GoogleProvider) GetEmailAddress(body []byte, access_token string) (string, error) {
|
|
|
|
var response struct {
|
|
|
|
IdToken string `json:"id_token"`
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := json.Unmarshal(body, &response); err != nil {
|
2015-03-30 19:30:27 +00:00
|
|
|
return "", err
|
|
|
|
}
|
2015-05-21 03:23:48 +00:00
|
|
|
|
2015-03-30 19:30:27 +00:00
|
|
|
// id_token is a base64 encode ID token payload
|
|
|
|
// https://developers.google.com/accounts/docs/OAuth2Login#obtainuserinfo
|
2015-05-21 03:23:48 +00:00
|
|
|
jwt := strings.Split(response.IdToken, ".")
|
2015-03-30 19:30:27 +00:00
|
|
|
b, err := jwtDecodeSegment(jwt[1])
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
2015-05-21 03:23:48 +00:00
|
|
|
|
|
|
|
var email struct {
|
|
|
|
Email string `json:"email"`
|
2015-03-30 19:30:27 +00:00
|
|
|
}
|
2015-05-21 03:23:48 +00:00
|
|
|
err = json.Unmarshal(b, &email)
|
2015-03-30 19:30:27 +00:00
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
2015-05-21 03:23:48 +00:00
|
|
|
if email.Email == "" {
|
|
|
|
return "", errors.New("missing email")
|
|
|
|
}
|
|
|
|
return email.Email, nil
|
2015-03-30 19:30:27 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func jwtDecodeSegment(seg string) ([]byte, error) {
|
|
|
|
if l := len(seg) % 4; l > 0 {
|
|
|
|
seg += strings.Repeat("=", 4-l)
|
|
|
|
}
|
|
|
|
|
|
|
|
return base64.URLEncoding.DecodeString(seg)
|
|
|
|
}
|
2015-05-13 01:48:13 +00:00
|
|
|
|
|
|
|
func (p *GoogleProvider) ValidateToken(access_token string) bool {
|
|
|
|
return validateToken(p, access_token, nil)
|
|
|
|
}
|