-
Notifications
You must be signed in to change notification settings - Fork 386
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Feat: Add Naver To Provider #1251
Open
hoeseong19
wants to merge
2
commits into
supabase:master
Choose a base branch
from
hoeseong19:hoeseong19/provider/naver
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+312
−0
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,184 @@ | ||
package api | ||
|
||
import ( | ||
"fmt" | ||
"net/http" | ||
"net/http/httptest" | ||
"net/url" | ||
|
||
jwt "github.com/golang-jwt/jwt" | ||
) | ||
|
||
const ( | ||
naverResponse string = `{"resultcode":"resultcode","message":"message","response":{"id":"123","nickname":"Naver Test","name":"Naver Test","email":"[email protected]","gender":"gender","age":"age","birthday":"birthday","profile_image":"http://example.com/avatar","birthyear":"birthyear","mobile":"mobile"}}` | ||
naverResponseAnotherEmail string = `{"resultcode":"resultcode","message":"message","response":{"id":"123","nickname":"Naver Test","name":"Naver Test","email":"[email protected]","gender":"gender","age":"age","birthday":"birthday","profile_image":"http://example.com/avatar","birthyear":"birthyear","mobile":"mobile"}}` | ||
naverResponseNoEmail string = `{"resultcode":"resultcode","message":"message","response":{"id":"123","nickname":"Naver Test","name":"Naver Test","gender":"gender","age":"age","birthday":"birthday","profile_image":"http://example.com/avatar","birthyear":"birthyear","mobile":"mobile"}}` | ||
) | ||
|
||
func (ts *ExternalTestSuite) TestSignupExternalNaver() { | ||
req := httptest.NewRequest(http.MethodGet, "http://localhost/authorize?provider=naver", nil) | ||
w := httptest.NewRecorder() | ||
ts.API.handler.ServeHTTP(w, req) | ||
ts.Require().Equal(http.StatusFound, w.Code) | ||
u, err := url.Parse(w.Header().Get("Location")) | ||
ts.Require().NoError(err, "redirect url parse failed") | ||
q := u.Query() | ||
ts.Equal(ts.Config.External.Naver.RedirectURI, q.Get("redirect_uri")) | ||
ts.Equal(ts.Config.External.Naver.ClientID, []string{q.Get("client_id")}) | ||
ts.Equal("code", q.Get("response_type")) | ||
|
||
claims := ExternalProviderClaims{} | ||
p := jwt.Parser{ValidMethods: []string{jwt.SigningMethodHS256.Name}} | ||
_, err = p.ParseWithClaims(q.Get("state"), &claims, func(token *jwt.Token) (interface{}, error) { | ||
return []byte(ts.Config.JWT.Secret), nil | ||
}) | ||
ts.Require().NoError(err) | ||
|
||
ts.Equal("naver", claims.Provider) | ||
ts.Equal(ts.Config.SiteURL, claims.SiteURL) | ||
} | ||
|
||
func NaverTestSignupSetup(ts *ExternalTestSuite, tokenCount *int, userCount *int, code string, response string) *httptest.Server { | ||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | ||
switch r.URL.Path { | ||
case "/oauth2.0/token": | ||
*tokenCount++ | ||
ts.Equal(code, r.FormValue("code")) | ||
ts.Equal("authorization_code", r.FormValue("grant_type")) | ||
ts.Equal(ts.Config.External.Naver.RedirectURI, r.FormValue("redirect_uri")) | ||
w.Header().Add("Content-Type", "application/json") | ||
fmt.Fprint(w, `{"access_token":"naver_token","expires_in":100000}`) | ||
case "/v1/nid/me": | ||
*userCount++ | ||
w.Header().Add("Content-Type", "application/json") | ||
fmt.Fprint(w, response) | ||
default: | ||
w.WriteHeader(500) | ||
ts.Fail("unknown naver oauth call %s", r.URL.Path) | ||
} | ||
})) | ||
ts.Config.External.Naver.URL = server.URL | ||
return server | ||
} | ||
|
||
func (ts *ExternalTestSuite) TestSignupExternalNaver_AuthorizationCode() { | ||
tokenCount, userCount := 0, 0 | ||
code := "authcode" | ||
response := naverResponse | ||
server := NaverTestSignupSetup(ts, &tokenCount, &userCount, code, response) | ||
defer server.Close() | ||
u := performAuthorization(ts, "naver", code, "") | ||
assertAuthorizationSuccess(ts, u, tokenCount, userCount, "[email protected]", "Naver Test", "123", "http://example.com/avatar") | ||
} | ||
|
||
func (ts *ExternalTestSuite) TestSignupExternalNaverDisableSignupErrorWhenNoUser() { | ||
ts.Config.DisableSignup = true | ||
tokenCount, userCount := 0, 0 | ||
code := "authcode" | ||
response := naverResponse | ||
server := NaverTestSignupSetup(ts, &tokenCount, &userCount, code, response) | ||
defer server.Close() | ||
|
||
u := performAuthorization(ts, "naver", code, "") | ||
|
||
assertAuthorizationFailure(ts, u, "Signups not allowed for this instance", "access_denied", "[email protected]") | ||
} | ||
|
||
func (ts *ExternalTestSuite) TestSignupExternalNaverDisableSignupErrorWhenEmptyEmail() { | ||
ts.Config.DisableSignup = true | ||
tokenCount, userCount := 0, 0 | ||
code := "authcode" | ||
response := naverResponseNoEmail | ||
server := NaverTestSignupSetup(ts, &tokenCount, &userCount, code, response) | ||
defer server.Close() | ||
|
||
u := performAuthorization(ts, "naver", code, "") | ||
|
||
assertAuthorizationFailure(ts, u, "Error getting user email from external provider", "server_error", "[email protected]") | ||
} | ||
|
||
func (ts *ExternalTestSuite) TestSignupExternalNaverDisableSignupSuccessWithPrimaryEmail() { | ||
ts.Config.DisableSignup = true | ||
|
||
ts.createUser("123", "[email protected]", "Naver Test", "http://example.com/avatar", "") | ||
|
||
tokenCount, userCount := 0, 0 | ||
code := "authcode" | ||
response := naverResponse | ||
server := NaverTestSignupSetup(ts, &tokenCount, &userCount, code, response) | ||
defer server.Close() | ||
|
||
u := performAuthorization(ts, "naver", code, "") | ||
|
||
assertAuthorizationSuccess(ts, u, tokenCount, userCount, "[email protected]", "Naver Test", "123", "http://example.com/avatar") | ||
} | ||
|
||
func (ts *ExternalTestSuite) TestInviteTokenExternalNaverSuccessWhenMatchingToken() { | ||
// name and avatar should be populated from Naver API | ||
ts.createUser("123", "[email protected]", "", "", "invite_token") | ||
|
||
tokenCount, userCount := 0, 0 | ||
code := "authcode" | ||
response := naverResponse | ||
server := NaverTestSignupSetup(ts, &tokenCount, &userCount, code, response) | ||
defer server.Close() | ||
|
||
u := performAuthorization(ts, "naver", code, "invite_token") | ||
|
||
assertAuthorizationSuccess(ts, u, tokenCount, userCount, "[email protected]", "Naver Test", "123", "http://example.com/avatar") | ||
} | ||
|
||
func (ts *ExternalTestSuite) TestInviteTokenExternalNaverErrorWhenNoMatchingToken() { | ||
tokenCount, userCount := 0, 0 | ||
code := "authcode" | ||
response := naverResponse | ||
server := NaverTestSignupSetup(ts, &tokenCount, &userCount, code, response) | ||
defer server.Close() | ||
|
||
w := performAuthorizationRequest(ts, "naver", "invite_token") | ||
ts.Require().Equal(http.StatusNotFound, w.Code) | ||
} | ||
|
||
func (ts *ExternalTestSuite) TestInviteTokenExternalNaverErrorWhenWrongToken() { | ||
ts.createUser("123", "[email protected]", "", "", "invite_token") | ||
|
||
tokenCount, userCount := 0, 0 | ||
code := "authcode" | ||
response := naverResponse | ||
server := NaverTestSignupSetup(ts, &tokenCount, &userCount, code, response) | ||
defer server.Close() | ||
|
||
w := performAuthorizationRequest(ts, "naver", "wrong_token") | ||
ts.Require().Equal(http.StatusNotFound, w.Code) | ||
} | ||
|
||
func (ts *ExternalTestSuite) TestInviteTokenExternalNaverErrorWhenEmailDoesntMatch() { | ||
ts.createUser("123", "[email protected]", "", "", "invite_token") | ||
|
||
tokenCount, userCount := 0, 0 | ||
code := "authcode" | ||
response := naverResponseAnotherEmail | ||
server := NaverTestSignupSetup(ts, &tokenCount, &userCount, code, response) | ||
defer server.Close() | ||
|
||
u := performAuthorization(ts, "naver", code, "invite_token") | ||
|
||
assertAuthorizationFailure(ts, u, "Invited email does not match emails from external provider", "invalid_request", "") | ||
} | ||
|
||
// func (ts *ExternalTestSuite) TestSignupExternalNaverErrorWhenVerifiedFalse() { | ||
// tokenCount, userCount := 0, 0 | ||
// code := "authcode" | ||
// emails := `[{"email":"[email protected]", "primary": true, "verified": false}]` | ||
// server := NaverTestSignupSetup(ts, &tokenCount, &userCount, code, emails) | ||
// defer server.Close() | ||
|
||
// u := performAuthorization(ts, "naver", code, "") | ||
|
||
// v, err := url.ParseQuery(u.Fragment) | ||
// ts.Require().NoError(err) | ||
// ts.Equal("unauthorized_client", v.Get("error")) | ||
// ts.Equal("401", v.Get("error_code")) | ||
// ts.Equal("Unverified email with naver", v.Get("error_description")) | ||
// assertAuthorizationFailure(ts, u, "", "", "") | ||
// } | ||
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,112 @@ | ||
package provider | ||
|
||
import ( | ||
"context" | ||
"errors" | ||
"strings" | ||
|
||
"github.com/supabase/gotrue/internal/conf" | ||
"golang.org/x/oauth2" | ||
) | ||
|
||
const ( | ||
defaultNaverAuthBase = "nid.naver.com" | ||
defaultNaverAPIBase = "openapi.naver.com" | ||
) | ||
|
||
type naverProvider struct { | ||
*oauth2.Config | ||
APIHost string | ||
} | ||
|
||
type naverResponse struct { | ||
Resultcode string `json:"resultcode"` | ||
Message string `json:"message"` | ||
Response struct { | ||
ID string `json:"id"` | ||
Nickname string `json:"nickname"` | ||
Name string `json:"name"` | ||
Email string `json:"email"` | ||
Gender string `json:"gender"` | ||
Age string `json:"age"` | ||
Birthday string `json:"birthday"` | ||
ProfileImage string `json:"profile_image"` | ||
Birthyear string `json:"birthyear"` | ||
Mobile string `json:"mobile"` | ||
} `json:"response"` | ||
} | ||
|
||
func (p naverProvider) GetOAuthToken(code string) (*oauth2.Token, error) { | ||
return p.Exchange(context.Background(), code) | ||
} | ||
|
||
func (p naverProvider) GetUserData(ctx context.Context, tok *oauth2.Token) (*UserProvidedData, error) { | ||
var r naverResponse | ||
|
||
if err := makeRequest(ctx, tok, p.Config, p.APIHost+"/v1/nid/me", &r); err != nil { | ||
return nil, err | ||
} | ||
|
||
if r.Response.Email == "" { | ||
return nil, errors.New("unable to find email with Naver provider") | ||
} | ||
|
||
data := &UserProvidedData{ | ||
Emails: []Email{ | ||
{ | ||
Email: r.Response.Email, | ||
Verified: true, // Naver dosen't provide data on if email is verified. | ||
Primary: true, | ||
}, | ||
}, | ||
Metadata: &Claims{ | ||
Issuer: p.APIHost, | ||
Subject: r.Response.ID, | ||
Email: r.Response.Email, | ||
EmailVerified: true, // Naver dosen't provide data on if email is verified. | ||
|
||
Name: r.Response.Name, | ||
PreferredUsername: r.Response.Name, | ||
|
||
// To be deprecated | ||
AvatarURL: r.Response.ProfileImage, | ||
FullName: r.Response.Name, | ||
ProviderId: r.Response.ID, | ||
UserNameKey: r.Response.Name, | ||
}, | ||
} | ||
return data, nil | ||
} | ||
|
||
func NewNaverProvider(ext conf.OAuthProviderConfiguration, scopes string) (OAuthProvider, error) { | ||
if err := ext.ValidateOAuth(); err != nil { | ||
return nil, err | ||
} | ||
|
||
authHost := chooseHost(ext.URL, defaultNaverAuthBase) | ||
apiHost := chooseHost(ext.URL, defaultNaverAPIBase) | ||
|
||
oauthScopes := []string{ | ||
"email", | ||
"profile_image", | ||
} | ||
|
||
if scopes != "" { | ||
oauthScopes = append(oauthScopes, strings.Split(scopes, ",")...) | ||
} | ||
|
||
return &naverProvider{ | ||
Config: &oauth2.Config{ | ||
ClientID: ext.ClientID[0], | ||
ClientSecret: ext.Secret, | ||
Endpoint: oauth2.Endpoint{ | ||
AuthStyle: oauth2.AuthStyleInParams, | ||
AuthURL: authHost + "/oauth2.0/authorize", | ||
TokenURL: authHost + "/oauth2.0/token", | ||
}, | ||
RedirectURL: ext.RedirectURI, | ||
Scopes: oauthScopes, | ||
}, | ||
APIHost: apiHost, | ||
}, nil | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Please remove the commented-out code
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Oops, I just commented it out.
I'll remove it.