2023-01-16 11:47:08 +02:00
|
|
|
package auth
|
|
|
|
|
|
|
|
import (
|
2023-03-01 23:29:45 +02:00
|
|
|
"context"
|
2023-01-16 11:47:08 +02:00
|
|
|
"encoding/json"
|
|
|
|
|
2023-11-27 20:32:28 +02:00
|
|
|
"github.com/pocketbase/pocketbase/tools/types"
|
2023-01-16 11:47:08 +02:00
|
|
|
"golang.org/x/oauth2"
|
|
|
|
)
|
|
|
|
|
2023-02-23 21:07:00 +02:00
|
|
|
var _ Provider = (*OIDC)(nil)
|
2023-01-16 11:47:08 +02:00
|
|
|
|
2023-02-23 21:07:00 +02:00
|
|
|
// NameOIDC is the unique name of the OpenID Connect (OIDC) provider.
|
|
|
|
const NameOIDC string = "oidc"
|
2023-01-16 11:47:08 +02:00
|
|
|
|
2023-02-23 21:07:00 +02:00
|
|
|
// OIDC allows authentication via OpenID Connect (OIDC) OAuth2 provider.
|
|
|
|
type OIDC struct {
|
2023-01-16 11:47:08 +02:00
|
|
|
*baseProvider
|
|
|
|
}
|
|
|
|
|
2023-02-23 21:07:00 +02:00
|
|
|
// NewOIDCProvider creates new OpenID Connect (OIDC) provider instance with some defaults.
|
|
|
|
func NewOIDCProvider() *OIDC {
|
|
|
|
return &OIDC{&baseProvider{
|
2023-11-29 20:19:54 +02:00
|
|
|
ctx: context.Background(),
|
|
|
|
displayName: "OIDC",
|
|
|
|
pkce: true,
|
2023-01-16 11:47:08 +02:00
|
|
|
scopes: []string{
|
|
|
|
"openid", // minimal requirement to return the id
|
|
|
|
"email",
|
|
|
|
"profile",
|
|
|
|
},
|
|
|
|
}}
|
|
|
|
}
|
|
|
|
|
2023-02-23 21:07:00 +02:00
|
|
|
// FetchAuthUser returns an AuthUser instance based the provider's user api.
|
2023-01-16 11:47:08 +02:00
|
|
|
//
|
2023-02-23 21:07:00 +02:00
|
|
|
// API reference: https://openid.net/specs/openid-connect-core-1_0.html#StandardClaims
|
|
|
|
func (p *OIDC) FetchAuthUser(token *oauth2.Token) (*AuthUser, error) {
|
2023-01-16 11:47:08 +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 {
|
|
|
|
Id string `json:"sub"`
|
|
|
|
Name string `json:"name"`
|
|
|
|
Username string `json:"preferred_username"`
|
|
|
|
Picture string `json:"picture"`
|
|
|
|
Email string `json:"email"`
|
|
|
|
EmailVerified bool `json:"email_verified"`
|
|
|
|
}{}
|
|
|
|
if err := json.Unmarshal(data, &extracted); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
user := &AuthUser{
|
|
|
|
Id: extracted.Id,
|
|
|
|
Name: extracted.Name,
|
|
|
|
Username: extracted.Username,
|
|
|
|
AvatarUrl: extracted.Picture,
|
|
|
|
RawUser: rawUser,
|
|
|
|
AccessToken: token.AccessToken,
|
|
|
|
RefreshToken: token.RefreshToken,
|
|
|
|
}
|
|
|
|
|
2023-11-27 20:32:28 +02:00
|
|
|
user.Expiry, _ = types.ParseDateTime(token.Expiry)
|
|
|
|
|
2023-01-16 11:47:08 +02:00
|
|
|
if extracted.EmailVerified {
|
|
|
|
user.Email = extracted.Email
|
|
|
|
}
|
|
|
|
|
|
|
|
return user, nil
|
|
|
|
}
|