[#979] added Kakao OAuth2 provider

This commit is contained in:
Gani Georgiev
2022-11-13 13:05:06 +02:00
parent 521df149a2
commit 50fce1f3cf
7 changed files with 118 additions and 5 deletions
+2
View File
@@ -99,6 +99,8 @@ func NewProviderByName(name string) (Provider, error) {
return NewMicrosoftProvider(), nil
case NameSpotify:
return NewSpotifyProvider(), nil
case NameKakao:
return NewKakaoProvider(), nil
default:
return nil, errors.New("Missing provider " + name)
}
+18
View File
@@ -55,6 +55,15 @@ func TestNewProviderByName(t *testing.T) {
t.Error("Expected to be instance of *auth.Gitlab")
}
// twitter
p, err = auth.NewProviderByName(auth.NameTwitter)
if err != nil {
t.Errorf("Expected nil, got error %v", err)
}
if _, ok := p.(*auth.Twitter); !ok {
t.Error("Expected to be instance of *auth.Twitter")
}
// discord
p, err = auth.NewProviderByName(auth.NameDiscord)
if err != nil {
@@ -81,4 +90,13 @@ func TestNewProviderByName(t *testing.T) {
if _, ok := p.(*auth.Spotify); !ok {
t.Error("Expected to be instance of *auth.Spotify")
}
// kakao
p, err = auth.NewProviderByName(auth.NameKakao)
if err != nil {
t.Errorf("Expected nil, got error %v", err)
}
if _, ok := p.(*auth.Kakao); !ok {
t.Error("Expected to be instance of *auth.Kakao")
}
}
+60
View File
@@ -0,0 +1,60 @@
package auth
import (
"strconv"
"golang.org/x/oauth2"
"golang.org/x/oauth2/kakao"
)
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 {
*baseProvider
}
// NewKakaoProvider creates a new Kakao provider instance with some defaults.
func NewKakaoProvider() *Kakao {
return &Kakao{&baseProvider{
scopes: []string{"account_email", "profile_nickname", "profile_image"},
authUrl: kakao.Endpoint.AuthURL,
tokenUrl: kakao.Endpoint.TokenURL,
userApiUrl: "https://kapi.kakao.com/v2/user/me",
}}
}
// FetchAuthUser returns an AuthUser instance based on the Kakao's user api.
func (p *Kakao) FetchAuthUser(token *oauth2.Token) (*AuthUser, error) {
// https://developers.kakao.com/docs/latest/en/kakaologin/rest-api#req-user-info-response
rawData := struct {
Id int `json:"id"`
Profile struct {
Nickname string `json:"nickname"`
ImageUrl string `json:"profile_image"`
} `json:"properties"`
KakaoAccount struct {
Email string `json:"email"`
IsEmailVerified bool `json:"is_email_verified"`
IsEmailValid bool `json:"is_email_valid"`
} `json:"kakao_account"`
}{}
if err := p.FetchRawUserData(token, &rawData); err != nil {
return nil, err
}
user := &AuthUser{
Id: strconv.Itoa(rawData.Id),
Username: rawData.Profile.Nickname,
AvatarUrl: rawData.Profile.ImageUrl,
}
if rawData.KakaoAccount.IsEmailValid && rawData.KakaoAccount.IsEmailVerified {
user.Email = rawData.KakaoAccount.Email
}
return user, nil
}