1
0
mirror of https://github.com/pocketbase/pocketbase.git synced 2025-01-10 00:43:36 +02:00
pocketbase/tools/auth/github.go

109 lines
2.5 KiB
Go
Raw Normal View History

2022-07-06 23:19:05 +02:00
package auth
import (
"encoding/json"
2022-12-16 17:06:03 +02:00
"io"
2022-07-06 23:19:05 +02:00
"strconv"
"golang.org/x/oauth2"
"golang.org/x/oauth2/github"
2022-07-06 23:19:05 +02:00
)
var _ Provider = (*Github)(nil)
// NameGithub is the unique name of the Github provider.
const NameGithub string = "github"
// Github allows authentication via Github OAuth2.
type Github struct {
*baseProvider
}
// NewGithubProvider creates new Github provider instance with some defaults.
func NewGithubProvider() *Github {
return &Github{&baseProvider{
scopes: []string{"read:user", "user:email"},
authUrl: github.Endpoint.AuthURL,
tokenUrl: github.Endpoint.TokenURL,
2022-07-06 23:19:05 +02:00
userApiUrl: "https://api.github.com/user",
}}
}
// FetchAuthUser returns an AuthUser instance based the Github's user api.
//
// API reference: https://docs.github.com/en/rest/reference/users#get-the-authenticated-user
2022-07-06 23:19:05 +02:00
func (p *Github) 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 {
Login string `json:"login"`
2022-07-06 23:19:05 +02:00
Id int `json:"id"`
Name string `json:"name"`
Email string `json:"email"`
AvatarUrl string `json:"avatar_url"`
}{}
if err := json.Unmarshal(data, &extracted); err != nil {
2022-07-06 23:19:05 +02:00
return nil, err
}
user := &AuthUser{
Id: strconv.Itoa(extracted.Id),
Name: extracted.Name,
Username: extracted.Login,
Email: extracted.Email,
AvatarUrl: extracted.AvatarUrl,
RawUser: rawUser,
AccessToken: token.AccessToken,
2022-07-06 23:19:05 +02:00
}
// in case user has set "Keep my email address private", send an
// **optional** API request to retrieve the verified primary email
2022-07-06 23:19:05 +02:00
if user.Email == "" {
client := p.Client(token)
response, err := client.Get(p.userApiUrl + "/emails")
if err != nil {
return user, err
}
defer response.Body.Close()
// ignore not found errors caused by unsufficient scope permissions
// (the email field is optional, return the auth user without it)
if response.StatusCode == 404 {
return user, nil
}
2022-12-16 17:06:03 +02:00
content, err := io.ReadAll(response.Body)
2022-07-06 23:19:05 +02:00
if err != nil {
return user, err
}
emails := []struct {
Email string
Verified bool
Primary bool
}{}
if err := json.Unmarshal(content, &emails); err != nil {
return user, err
}
// extract the verified primary email
for _, email := range emails {
if email.Verified && email.Primary {
user.Email = email.Email
break
}
}
}
return user, nil
}