1
0
mirror of https://github.com/pocketbase/pocketbase.git synced 2024-11-25 09:21:11 +02:00
pocketbase/tools/auth/twitter.go

79 lines
2.2 KiB
Go
Raw Normal View History

2022-09-01 15:46:06 +02:00
package auth
import (
2023-03-01 23:29:45 +02:00
"context"
"encoding/json"
2022-09-01 15:46:06 +02:00
"golang.org/x/oauth2"
)
var _ Provider = (*Twitter)(nil)
// NameTwitter is the unique name of the Twitter provider.
const NameTwitter string = "twitter"
// Twitter allows authentication via Twitter OAuth2.
type Twitter struct {
*baseProvider
}
// NewTwitterProvider creates new Twitter provider instance with some defaults.
func NewTwitterProvider() *Twitter {
return &Twitter{&baseProvider{
2023-03-01 23:29:45 +02:00
ctx: context.Background(),
2022-09-01 15:46:06 +02:00
scopes: []string{
"users.read",
// we don't actually use this scope, but for some reason it is required by the `/2/users/me` endpoint
// (see https://developer.twitter.com/en/docs/twitter-api/users/lookup/api-reference/get-users-me)
"tweet.read",
},
authUrl: "https://twitter.com/i/oauth2/authorize",
tokenUrl: "https://api.twitter.com/2/oauth2/token",
userApiUrl: "https://api.twitter.com/2/users/me?user.fields=id,name,username,profile_image_url",
2022-09-01 15:46:06 +02:00
}}
}
// FetchAuthUser returns an AuthUser instance based on the Twitter's user api.
//
// API reference: https://developer.twitter.com/en/docs/twitter-api/users/lookup/api-reference/get-users-me
2022-09-01 15:46:06 +02:00
func (p *Twitter) FetchAuthUser(token *oauth2.Token) (*AuthUser, error) {
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-09-01 15:46:06 +02:00
Data struct {
Id string `json:"id"`
Name string `json:"name"`
Username string `json:"username"`
2022-09-01 15:46:06 +02:00
ProfileImageUrl string `json:"profile_image_url"`
// NB! At the time of writing, Twitter OAuth2 doesn't support returning the user email address
// (see https://twittercommunity.com/t/which-api-to-get-user-after-oauth2-authorization/162417/33)
// Email string `json:"email"`
2022-09-01 15:46:06 +02:00
} `json:"data"`
}{}
if err := json.Unmarshal(data, &extracted); err != nil {
2022-09-01 15:46:06 +02:00
return nil, err
}
user := &AuthUser{
2023-01-07 22:25:56 +02:00
Id: extracted.Data.Id,
Name: extracted.Data.Name,
Username: extracted.Data.Username,
AvatarUrl: extracted.Data.ProfileImageUrl,
RawUser: rawUser,
AccessToken: token.AccessToken,
RefreshToken: token.RefreshToken,
2022-09-01 15:46:06 +02:00
}
return user, nil
}