1
0
mirror of https://github.com/volatiletech/authboss.git synced 2025-01-10 04:17:59 +02:00
authboss/oauth2/providers.go

73 lines
1.7 KiB
Go
Raw Normal View History

package oauth2
import (
2017-02-21 01:56:26 +02:00
"context"
"encoding/json"
"net/http"
2017-07-31 04:39:33 +02:00
"github.com/volatiletech/authboss"
2017-02-21 01:56:26 +02:00
"golang.org/x/oauth2"
)
2015-08-04 00:25:06 +02:00
const (
googleInfoEndpoint = `https://www.googleapis.com/userinfo/v2/me`
facebookInfoEndpoint = `https://graph.facebook.com/me?fields=name,email`
)
type googleMeResponse struct {
ID string `json:"id"`
Email string `json:"email"`
}
// testing
var clientGet = (*http.Client).Get
// Google is a callback appropriate for use with Google's OAuth2 configuration.
2017-02-21 01:56:26 +02:00
func Google(ctx context.Context, cfg oauth2.Config, token *oauth2.Token) (map[string]string, error) {
client := cfg.Client(ctx, token)
resp, err := clientGet(client, googleInfoEndpoint)
if err != nil {
return nil, err
}
defer resp.Body.Close()
dec := json.NewDecoder(resp.Body)
var jsonResp googleMeResponse
if err = dec.Decode(&jsonResp); err != nil {
return nil, err
}
2017-02-21 01:56:26 +02:00
return map[string]string{
authboss.StoreOAuth2UID: jsonResp.ID,
authboss.StoreEmail: jsonResp.Email,
}, nil
}
2015-08-03 22:35:43 +02:00
type facebookMeResponse struct {
ID string `json:"id"`
Email string `json:"email"`
Name string `json:"name"`
}
// Facebook is a callback appropriate for use with Facebook's OAuth2 configuration.
2017-02-21 01:56:26 +02:00
func Facebook(ctx context.Context, cfg oauth2.Config, token *oauth2.Token) (map[string]string, error) {
client := cfg.Client(ctx, token)
2015-08-03 22:35:43 +02:00
resp, err := clientGet(client, facebookInfoEndpoint)
if err != nil {
return nil, err
}
defer resp.Body.Close()
dec := json.NewDecoder(resp.Body)
var jsonResp facebookMeResponse
if err = dec.Decode(&jsonResp); err != nil {
return nil, err
}
2017-02-21 01:56:26 +02:00
return map[string]string{
2015-08-03 22:35:43 +02:00
"name": jsonResp.Name,
authboss.StoreOAuth2UID: jsonResp.ID,
authboss.StoreEmail: jsonResp.Email,
}, nil
}