1
0
mirror of https://github.com/pocketbase/pocketbase.git synced 2025-03-20 14:31:09 +02:00

87 lines
2.2 KiB
Go
Raw Permalink Normal View History

2022-11-13 13:05:06 +02:00
package auth
import (
2023-03-01 23:29:45 +02:00
"context"
"encoding/json"
2022-11-13 13:05:06 +02:00
"strconv"
"github.com/pocketbase/pocketbase/tools/types"
2022-11-13 13:05:06 +02:00
"golang.org/x/oauth2"
"golang.org/x/oauth2/kakao"
)
2024-09-29 19:23:19 +03:00
func init() {
Providers[NameKakao] = wrapFactory(NewKakaoProvider)
}
2022-11-13 13:05:06 +02:00
var _ Provider = (*Kakao)(nil)
// NameKakao is the unique name of the Kakao provider.
const NameKakao string = "kakao"
// Kakao allows authentication via Kakao OAuth2.
type Kakao struct {
2024-09-29 19:23:19 +03:00
BaseProvider
2022-11-13 13:05:06 +02:00
}
// NewKakaoProvider creates a new Kakao provider instance with some defaults.
func NewKakaoProvider() *Kakao {
2024-09-29 19:23:19 +03:00
return &Kakao{BaseProvider{
ctx: context.Background(),
displayName: "Kakao",
pkce: true,
scopes: []string{"account_email", "profile_nickname", "profile_image"},
2024-09-29 19:23:19 +03:00
authURL: kakao.Endpoint.AuthURL,
tokenURL: kakao.Endpoint.TokenURL,
userInfoURL: "https://kapi.kakao.com/v2/user/me",
2022-11-13 13:05:06 +02:00
}}
}
// FetchAuthUser returns an AuthUser instance based on the Kakao's user api.
//
// API reference: https://developers.kakao.com/docs/latest/en/kakaologin/rest-api#req-user-info-response
2022-11-13 13:05:06 +02:00
func (p *Kakao) 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-13 13:05:06 +02:00
Profile struct {
Nickname string `json:"nickname"`
2024-09-29 19:23:19 +03:00
ImageURL string `json:"profile_image"`
2022-11-13 13:05:06 +02:00
} `json:"properties"`
KakaoAccount struct {
Email string `json:"email"`
IsEmailVerified bool `json:"is_email_verified"`
IsEmailValid bool `json:"is_email_valid"`
} `json:"kakao_account"`
Id int64 `json:"id"`
2022-11-13 13:05:06 +02:00
}{}
if err := json.Unmarshal(data, &extracted); err != nil {
2022-11-13 13:05:06 +02:00
return nil, err
}
user := &AuthUser{
Id: strconv.FormatInt(extracted.Id, 10),
2023-01-07 22:25:56 +02:00
Username: extracted.Profile.Nickname,
2024-09-29 19:23:19 +03:00
AvatarURL: extracted.Profile.ImageURL,
2023-01-07 22:25:56 +02:00
RawUser: rawUser,
AccessToken: token.AccessToken,
RefreshToken: token.RefreshToken,
2022-11-13 13:05:06 +02:00
}
user.Expiry, _ = types.ParseDateTime(token.Expiry)
if extracted.KakaoAccount.IsEmailValid && extracted.KakaoAccount.IsEmailVerified {
user.Email = extracted.KakaoAccount.Email
2022-11-13 13:05:06 +02:00
}
return user, nil
}