1
0
mirror of https://github.com/pocketbase/pocketbase.git synced 2025-03-19 06:07:48 +02:00
pocketbase/tools/auth/spotify.go

88 lines
2.2 KiB
Go
Raw Permalink Normal View History

2022-11-01 16:06:06 +01:00
package auth
import (
2023-03-01 23:29:45 +02:00
"context"
"encoding/json"
"github.com/pocketbase/pocketbase/tools/types"
2022-11-01 16:06:06 +01:00
"golang.org/x/oauth2"
"golang.org/x/oauth2/spotify"
)
2024-09-29 19:23:19 +03:00
func init() {
Providers[NameSpotify] = wrapFactory(NewSpotifyProvider)
}
2022-11-01 16:06:06 +01:00
var _ Provider = (*Spotify)(nil)
// NameSpotify is the unique name of the Spotify provider.
const NameSpotify string = "spotify"
// Spotify allows authentication via Spotify OAuth2.
type Spotify struct {
2024-09-29 19:23:19 +03:00
BaseProvider
2022-11-01 16:06:06 +01:00
}
// NewSpotifyProvider creates a new Spotify provider instance with some defaults.
func NewSpotifyProvider() *Spotify {
2024-09-29 19:23:19 +03:00
return &Spotify{BaseProvider{
ctx: context.Background(),
displayName: "Spotify",
pkce: true,
scopes: []string{
"user-read-private",
// currently Spotify doesn't return information whether the email is verified or not
// "user-read-email",
},
2024-09-29 19:23:19 +03:00
authURL: spotify.Endpoint.AuthURL,
tokenURL: spotify.Endpoint.TokenURL,
userInfoURL: "https://api.spotify.com/v1/me",
2022-11-01 16:06:06 +01:00
}}
}
// FetchAuthUser returns an AuthUser instance based on the Spotify's user api.
//
// API reference: https://developer.spotify.com/documentation/web-api/reference/#/operations/get-current-users-profile
2022-11-01 16:06:06 +01:00
func (p *Spotify) FetchAuthUser(token *oauth2.Token) (*AuthUser, error) {
2024-09-29 19:23:19 +03:00
data, err := p.FetchRawUserInfo(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-11-01 16:06:06 +01:00
Id string `json:"id"`
Name string `json:"display_name"`
Images []struct {
2024-09-29 19:23:19 +03:00
URL string `json:"url"`
2022-11-01 16:06:06 +01:00
} `json:"images"`
// don't map the email because per the official docs
// the email field is "unverified" and there is no proof
// that it actually belongs to the user
// Email string `json:"email"`
2022-11-01 16:06:06 +01:00
}{}
if err := json.Unmarshal(data, &extracted); err != nil {
2022-11-01 16:06:06 +01:00
return nil, err
}
user := &AuthUser{
2023-01-07 22:25:56 +02:00
Id: extracted.Id,
Name: extracted.Name,
RawUser: rawUser,
AccessToken: token.AccessToken,
RefreshToken: token.RefreshToken,
2022-11-01 16:06:06 +01:00
}
user.Expiry, _ = types.ParseDateTime(token.Expiry)
if len(extracted.Images) > 0 {
2024-09-29 19:23:19 +03:00
user.AvatarURL = extracted.Images[0].URL
2022-11-01 16:06:06 +01:00
}
return user, nil
}