forked from markbates/goth
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request markbates#219 from sunho/naver-provider
Naver provider
- Loading branch information
Showing
6 changed files
with
347 additions
and
0 deletions.
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,173 @@ | ||
package naver | ||
|
||
import ( | ||
"bytes" | ||
"encoding/json" | ||
"fmt" | ||
"io" | ||
"io/ioutil" | ||
"net/http" | ||
|
||
"github.com/markbates/goth" | ||
"golang.org/x/oauth2" | ||
) | ||
|
||
const ( | ||
authURL = "https://nid.naver.com/oauth2.0/authorize" | ||
tokenURL = "https://nid.naver.com/oauth2.0/token" | ||
profileURL = "https://openapi.naver.com/v1/nid/me" | ||
) | ||
|
||
// Provider is the implementation of `goth.Provider` for accessing naver.com. | ||
type Provider struct { | ||
ClientKey string | ||
Secret string | ||
CallbackURL string | ||
HTTPClient *http.Client | ||
config *oauth2.Config | ||
providerName string | ||
} | ||
|
||
// Name is the name used to retrive this provider later. | ||
func (p *Provider) Name() string { | ||
return p.providerName | ||
} | ||
|
||
// SetName is to update the name of the provider (needed in case of multiple providers of 1 type) | ||
func (p *Provider) SetName(name string) { | ||
p.providerName = name | ||
} | ||
|
||
func (p *Provider) Client() *http.Client { | ||
return goth.HTTPClientWithFallBack(p.HTTPClient) | ||
} | ||
|
||
// FetchUser will go to navercom and access basic information about the user. | ||
func (p *Provider) FetchUser(session goth.Session) (goth.User, error) { | ||
sess := session.(*Session) | ||
user := goth.User{ | ||
AccessToken: sess.AccessToken, | ||
Provider: p.Name(), | ||
RefreshToken: sess.RefreshToken, | ||
ExpiresAt: sess.ExpiresAt, | ||
} | ||
|
||
if user.AccessToken == "" { | ||
return user, fmt.Errorf("%s cannot get user information without accessToken", p.providerName) | ||
} | ||
|
||
request, err := http.NewRequest("GET", profileURL, nil) | ||
if err != nil { | ||
return user, err | ||
} | ||
|
||
request.Header.Set("Authorization", "Bearer "+sess.AccessToken) | ||
response, err := p.Client().Do(request) | ||
if err != nil { | ||
return user, err | ||
} | ||
defer response.Body.Close() | ||
|
||
if response.StatusCode != http.StatusOK { | ||
return user, fmt.Errorf("%s responded with a %d trying to fetch user information", p.providerName, response.StatusCode) | ||
} | ||
|
||
bits, err := ioutil.ReadAll(response.Body) | ||
if err != nil { | ||
return user, err | ||
} | ||
|
||
err = json.NewDecoder(bytes.NewReader(bits)).Decode(&user.RawData) | ||
if err != nil { | ||
return user, err | ||
} | ||
|
||
err = userFromReader(bytes.NewReader(bits), &user) | ||
return user, err | ||
} | ||
|
||
// Debug is a no-op for the naver package. | ||
func (p *Provider) Debug(debug bool) {} | ||
|
||
// BeginAuth asks naver.com for an authentication end-point. | ||
func (p *Provider) BeginAuth(state string) (goth.Session, error) { | ||
url := p.config.AuthCodeURL(state) | ||
session := &Session{ | ||
AuthURL: url, | ||
} | ||
return session, nil | ||
} | ||
|
||
//RefreshTokenAvailable refresh token is provided by naver | ||
func (p *Provider) RefreshTokenAvailable() bool { | ||
return true | ||
} | ||
|
||
//RefreshToken get new access token based on the refresh token | ||
func (p *Provider) RefreshToken(refreshToken string) (*oauth2.Token, error) { | ||
token := &oauth2.Token{RefreshToken: refreshToken} | ||
ts := p.config.TokenSource(goth.ContextForClient(p.Client()), token) | ||
newToken, err := ts.Token() | ||
if err != nil { | ||
return nil, err | ||
} | ||
return newToken, err | ||
} | ||
|
||
// New creates a New provider and sets up important connection details. | ||
// You should always call `naver.New` to get a new Provider. Never try to craete | ||
// one manually. | ||
// Currently Naver only supports pre-defined scopes. | ||
// You should visit Naver Developer page in order to define your application's oauth scope. | ||
func New(clientKey, secret, callbackURL string) *Provider { | ||
p := &Provider{ | ||
ClientKey: clientKey, | ||
Secret: secret, | ||
CallbackURL: callbackURL, | ||
providerName: "naver", | ||
} | ||
p.config = newConfig(p) | ||
return p | ||
} | ||
|
||
func newConfig(p *Provider) *oauth2.Config { | ||
c := &oauth2.Config{ | ||
ClientID: p.ClientKey, | ||
ClientSecret: p.Secret, | ||
RedirectURL: p.CallbackURL, | ||
Endpoint: oauth2.Endpoint{ | ||
AuthURL: authURL, | ||
TokenURL: tokenURL, | ||
}, | ||
Scopes: []string{}, | ||
} | ||
return c | ||
} | ||
|
||
func userFromReader(reader io.Reader, user *goth.User) error { | ||
u := struct { | ||
Response struct { | ||
ID string | ||
Nickname string | ||
Name string | ||
Email string | ||
Gender string | ||
Age string | ||
Birthday string | ||
ProfileImage string `json:"profile_image"` | ||
} | ||
}{} | ||
|
||
if err := json.NewDecoder(reader).Decode(&u); err != nil { | ||
return err | ||
} | ||
r := u.Response | ||
user.Email = r.Email | ||
user.Name = r.Name | ||
user.NickName = r.Nickname | ||
user.AvatarURL = r.ProfileImage | ||
user.UserID = r.ID | ||
user.Description = fmt.Sprintf(`{"gender":"%s","age":"%s","birthday":"%s"}`, r.Gender, r.Age, r.Birthday) | ||
|
||
return 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,56 @@ | ||
package naver_test | ||
|
||
import ( | ||
"fmt" | ||
"os" | ||
"testing" | ||
|
||
"github.com/markbates/goth" | ||
"github.com/stretchr/testify/assert" | ||
"github.com/markbates/goth/providers/naver" | ||
) | ||
|
||
func Test_New(t *testing.T) { | ||
t.Parallel() | ||
a := assert.New(t) | ||
p := provider() | ||
|
||
a.Equal(p.ClientKey, os.Getenv("NAVER_KEY")) | ||
a.Equal(p.Secret, os.Getenv("NAVER_SECRET")) | ||
a.Equal(p.CallbackURL, "/foo") | ||
} | ||
|
||
func Test_Implements_Provider(t *testing.T) { | ||
t.Parallel() | ||
a := assert.New(t) | ||
a.Implements((*goth.Provider)(nil), provider()) | ||
} | ||
|
||
func Test_BeginAuth(t *testing.T) { | ||
t.Parallel() | ||
a := assert.New(t) | ||
p := provider() | ||
session, err := p.BeginAuth("test_state") | ||
s := session.(*naver.Session) | ||
a.NoError(err) | ||
a.Contains(s.AuthURL, "https://nid.naver.com/oauth2.0/authorize") | ||
a.Contains(s.AuthURL, fmt.Sprintf("client_id=%s", os.Getenv("NAVER_KEY"))) | ||
a.Contains(s.AuthURL, "state=test_state") | ||
} | ||
|
||
func Test_SessionFromJSON(t *testing.T) { | ||
t.Parallel() | ||
a := assert.New(t) | ||
|
||
p := provider() | ||
session, err := p.UnmarshalSession(`{"AuthURL":"ttps://nid.naver.com/oauth2.0/authorize","AccessToken":"1234567890"}`) | ||
a.NoError(err) | ||
|
||
s := session.(*naver.Session) | ||
a.Equal(s.AuthURL, "ttps://nid.naver.com/oauth2.0/authorize") | ||
a.Equal(s.AccessToken, "1234567890") | ||
} | ||
|
||
func provider() *naver.Provider { | ||
return naver.New(os.Getenv("NAVER_KEY"), os.Getenv("NAVER_SECRET"), "/foo") | ||
} |
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,61 @@ | ||
package naver | ||
|
||
import ( | ||
"encoding/json" | ||
"errors" | ||
"strings" | ||
"time" | ||
|
||
"github.com/markbates/goth" | ||
) | ||
|
||
// Session stores data during the auth process with naver.com. | ||
type Session struct { | ||
AuthURL string | ||
AccessToken string | ||
RefreshToken string | ||
ExpiresAt time.Time | ||
} | ||
|
||
// GetAuthURL will return the URL set by calling the `BeginAuth` function on the meetup.com provider. | ||
func (s Session) GetAuthURL() (string, error) { | ||
if s.AuthURL == "" { | ||
return "", errors.New(goth.NoAuthUrlErrorMessage) | ||
} | ||
return s.AuthURL, nil | ||
} | ||
|
||
// Authorize the session with naver.com and return the access token to be stored for future use. | ||
func (s *Session) Authorize(provider goth.Provider, params goth.Params) (string, error) { | ||
p := provider.(*Provider) | ||
token, err := p.config.Exchange(goth.ContextForClient(p.Client()), params.Get("code")) | ||
if err != nil { | ||
return "", err | ||
} | ||
|
||
if !token.Valid() { | ||
return "", errors.New("Invalid token received from provider") | ||
} | ||
|
||
s.AccessToken = token.AccessToken | ||
s.RefreshToken = token.RefreshToken | ||
s.ExpiresAt = token.Expiry | ||
return token.AccessToken, err | ||
} | ||
|
||
// Marshal the session into a string | ||
func (s Session) Marshal() string { | ||
b, _ := json.Marshal(s) | ||
return string(b) | ||
} | ||
|
||
func (s Session) String() string { | ||
return s.Marshal() | ||
} | ||
|
||
// UnmarshalSession wil unmarshal a JSON string into a session. | ||
func (p *Provider) UnmarshalSession(data string) (goth.Session, error) { | ||
s := &Session{} | ||
err := json.NewDecoder(strings.NewReader(data)).Decode(s) | ||
return s, err | ||
} |
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,53 @@ | ||
package naver_test | ||
|
||
import ( | ||
"testing" | ||
|
||
"github.com/markbates/goth" | ||
"github.com/stretchr/testify/assert" | ||
"github.com/markbates/goth/providers/naver" | ||
) | ||
|
||
func Test_Implements_Session(t *testing.T) { | ||
t.Parallel() | ||
a := assert.New(t) | ||
s := &naver.Session{} | ||
|
||
a.Implements((*goth.Session)(nil), s) | ||
} | ||
|
||
func Test_GetAuthURL(t *testing.T) { | ||
t.Parallel() | ||
a := assert.New(t) | ||
s := &naver.Session{} | ||
|
||
_, err := s.GetAuthURL() | ||
a.Error(err) | ||
|
||
s.AuthURL = "/foo" | ||
|
||
url, _ := s.GetAuthURL() | ||
a.Equal(url, "/foo") | ||
} | ||
|
||
func Test_ToJSON(t *testing.T) { | ||
t.Parallel() | ||
a := assert.New(t) | ||
s := &naver.Session{ | ||
AuthURL: "https://nid.naver.com/oauth2.0/authorize", | ||
AccessToken: "1234567890", | ||
} | ||
data := s.Marshal() | ||
a.Equal(`{"AuthURL":"https://nid.naver.com/oauth2.0/authorize","AccessToken":"1234567890","RefreshToken":"","ExpiresAt":"0001-01-01T00:00:00Z"}`, data) | ||
} | ||
|
||
func Test_String(t *testing.T) { | ||
t.Parallel() | ||
a := assert.New(t) | ||
s := &naver.Session{ | ||
AuthURL: "https://nid.naver.com/oauth2.0/authorize", | ||
AccessToken: "1234567890", | ||
} | ||
|
||
a.Equal(s.String(), s.Marshal()) | ||
} |