2022-07-06 23:19:05 +02:00
|
|
|
package auth
|
|
|
|
|
|
|
|
import (
|
2023-03-01 23:29:45 +02:00
|
|
|
"context"
|
2022-11-30 15:16:09 +02:00
|
|
|
"encoding/json"
|
|
|
|
|
2023-11-27 20:32:28 +02:00
|
|
|
"github.com/pocketbase/pocketbase/tools/types"
|
2022-07-06 23:19:05 +02:00
|
|
|
"golang.org/x/oauth2"
|
2022-11-13 13:25:14 +02:00
|
|
|
"golang.org/x/oauth2/facebook"
|
2022-07-06 23:19:05 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
var _ Provider = (*Facebook)(nil)
|
|
|
|
|
|
|
|
// NameFacebook is the unique name of the Facebook provider.
|
|
|
|
const NameFacebook string = "facebook"
|
|
|
|
|
|
|
|
// Facebook allows authentication via Facebook OAuth2.
|
|
|
|
type Facebook struct {
|
|
|
|
*baseProvider
|
|
|
|
}
|
|
|
|
|
|
|
|
// NewFacebookProvider creates new Facebook provider instance with some defaults.
|
|
|
|
func NewFacebookProvider() *Facebook {
|
|
|
|
return &Facebook{&baseProvider{
|
2023-11-29 20:19:54 +02:00
|
|
|
ctx: context.Background(),
|
|
|
|
displayName: "Facebook",
|
|
|
|
pkce: true,
|
|
|
|
scopes: []string{"email"},
|
|
|
|
authUrl: facebook.Endpoint.AuthURL,
|
|
|
|
tokenUrl: facebook.Endpoint.TokenURL,
|
|
|
|
userApiUrl: "https://graph.facebook.com/me?fields=name,email,picture.type(large)",
|
2022-07-06 23:19:05 +02:00
|
|
|
}}
|
|
|
|
}
|
|
|
|
|
|
|
|
// FetchAuthUser returns an AuthUser instance based on the Facebook's user api.
|
2022-11-30 15:16:09 +02:00
|
|
|
//
|
|
|
|
// API reference: https://developers.facebook.com/docs/graph-api/reference/user/
|
2022-07-06 23:19:05 +02:00
|
|
|
func (p *Facebook) FetchAuthUser(token *oauth2.Token) (*AuthUser, error) {
|
2022-11-30 15:16:09 +02:00
|
|
|
data, err := p.FetchRawUserData(token)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
rawUser := map[string]any{}
|
|
|
|
if err := json.Unmarshal(data, &rawUser); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
extracted := struct {
|
2022-07-06 23:19:05 +02:00
|
|
|
Id string
|
|
|
|
Name string
|
|
|
|
Email string
|
|
|
|
Picture struct {
|
|
|
|
Data struct{ Url string }
|
|
|
|
}
|
|
|
|
}{}
|
2022-11-30 15:16:09 +02:00
|
|
|
if err := json.Unmarshal(data, &extracted); err != nil {
|
2022-07-06 23:19:05 +02:00
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
user := &AuthUser{
|
2023-01-07 22:25:56 +02:00
|
|
|
Id: extracted.Id,
|
|
|
|
Name: extracted.Name,
|
|
|
|
Email: extracted.Email,
|
|
|
|
AvatarUrl: extracted.Picture.Data.Url,
|
|
|
|
RawUser: rawUser,
|
|
|
|
AccessToken: token.AccessToken,
|
|
|
|
RefreshToken: token.RefreshToken,
|
2022-07-06 23:19:05 +02:00
|
|
|
}
|
|
|
|
|
2023-11-27 20:32:28 +02:00
|
|
|
user.Expiry, _ = types.ParseDateTime(token.Expiry)
|
|
|
|
|
2022-07-06 23:19:05 +02:00
|
|
|
return user, nil
|
|
|
|
}
|