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

89 lines
2.1 KiB
Go
Raw Normal View History

package oauth2
import (
2017-02-21 01:56:26 +02:00
"context"
"encoding/json"
"io/ioutil"
"net/http"
"github.com/pkg/errors"
2017-02-21 01:56:26 +02:00
"golang.org/x/oauth2"
)
// Constants for returning in the FindUserDetails call
const (
OAuth2UID = "uid"
OAuth2Email = "email"
OAuth2Name = "name"
)
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
// GoogleUserDetails can be used as a FindUserDetails function for an authboss.OAuth2Provider
func GoogleUserDetails(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()
byt, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, errors.Wrap(err, "failed to read body from google oauth2 endpoint")
}
var response googleMeResponse
if err = json.Unmarshal(byt, &response); err != nil {
return nil, err
}
2017-02-21 01:56:26 +02:00
return map[string]string{
OAuth2UID: response.ID,
OAuth2Email: response.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"`
}
// FacebookUserDetails can be used as a FindUserDetails function for an authboss.OAuth2Provider
func FacebookUserDetails(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()
byt, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, errors.Wrap(err, "failed to read body from facebook oauth2 endpoint")
}
var response facebookMeResponse
if err = json.Unmarshal(byt, &response); err != nil {
return nil, errors.Wrap(err, "failed to parse json from facebook oauth2 endpoint")
2015-08-03 22:35:43 +02:00
}
2017-02-21 01:56:26 +02:00
return map[string]string{
OAuth2UID: response.ID,
OAuth2Email: response.Email,
OAuth2Name: response.Name,
2015-08-03 22:35:43 +02:00
}, nil
}