Skip to content

Commit

Permalink
Merge pull request #275 from rbo13/master
Browse files Browse the repository at this point in the history
Added LINE Provider
  • Loading branch information
bentranter authored May 8, 2019
2 parents 9db6207 + 3bd14d0 commit a3114a0
Show file tree
Hide file tree
Showing 6 changed files with 327 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ $ go get github.com/markbates/goth
* Intercom
* Lastfm
* Linkedin
* LINE
* Mailru
* Meetup
* MicrosoftOnline
Expand Down
3 changes: 3 additions & 0 deletions examples/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ import (
"github.com/markbates/goth/providers/instagram"
"github.com/markbates/goth/providers/intercom"
"github.com/markbates/goth/providers/lastfm"
"github.com/markbates/goth/providers/line"
"github.com/markbates/goth/providers/linkedin"
"github.com/markbates/goth/providers/meetup"
"github.com/markbates/goth/providers/microsoftonline"
Expand Down Expand Up @@ -74,6 +75,7 @@ func main() {
github.New(os.Getenv("GITHUB_KEY"), os.Getenv("GITHUB_SECRET"), "http://localhost:3000/auth/github/callback"),
spotify.New(os.Getenv("SPOTIFY_KEY"), os.Getenv("SPOTIFY_SECRET"), "http://localhost:3000/auth/spotify/callback"),
linkedin.New(os.Getenv("LINKEDIN_KEY"), os.Getenv("LINKEDIN_SECRET"), "http://localhost:3000/auth/linkedin/callback"),
line.New(os.Getenv("LINE_KEY"), os.Getenv("LINE_SECRET"), "http://localhost:3000/auth/line/callback", "profile", "openid", "email"),
lastfm.New(os.Getenv("LASTFM_KEY"), os.Getenv("LASTFM_SECRET"), "http://localhost:3000/auth/lastfm/callback"),
twitch.New(os.Getenv("TWITCH_KEY"), os.Getenv("TWITCH_SECRET"), "http://localhost:3000/auth/twitch/callback"),
dropbox.New(os.Getenv("DROPBOX_KEY"), os.Getenv("DROPBOX_SECRET"), "http://localhost:3000/auth/dropbox/callback"),
Expand Down Expand Up @@ -158,6 +160,7 @@ func main() {
m["intercom"] = "Intercom"
m["lastfm"] = "Last FM"
m["linkedin"] = "Linkedin"
m["line"] = "LINE"
m["onedrive"] = "Onedrive"
m["azuread"] = "Azure AD"
m["microsoftonline"] = "Microsoft Online"
Expand Down
159 changes: 159 additions & 0 deletions providers/line/line.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
// Package line implements the OAuth2 protocol for authenticating users through line.
// This package can be used as a reference implementation of an OAuth2 provider for Goth.
package line

import (
"bytes"
"encoding/json"
"io/ioutil"
"net/http"

"fmt"

"github.com/markbates/goth"
"golang.org/x/oauth2"
)

const (
authURL string = "https://access.line.me/oauth2/v2.1/authorize"
tokenURL string = "https://api.line.me/oauth2/v2.1/token"
endpointUser string = "https://api.line.me/v2/profile"
)

// Provider is the implementation of `goth.Provider` for accessing Line.me.
type Provider struct {
ClientKey string
Secret string
CallbackURL string
HTTPClient *http.Client
config *oauth2.Config
providerName string
}

// New creates a new Line provider and sets up important connection details.
// You should always call `line.New` to get a new provider. Never try to
// create one manually.
func New(clientKey, secret, callbackURL string, scopes ...string) *Provider {
p := &Provider{
ClientKey: clientKey,
Secret: secret,
CallbackURL: callbackURL,
providerName: "line",
}
p.config = newConfig(p, scopes)
return p
}

// Name is the name used to retrieve 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
}

// Client returns a pointer to http.Client setting some client fallback.
func (p *Provider) Client() *http.Client {
return goth.HTTPClientWithFallBack(p.HTTPClient)
}

// Debug is a no-op for the line package.
func (p *Provider) Debug(debug bool) {}

// BeginAuth asks line.me for an authentication end-point.
func (p *Provider) BeginAuth(state string) (goth.Session, error) {
return &Session{
AuthURL: p.config.AuthCodeURL(state),
}, nil
}

// FetchUser will go to line.me 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 == "" {
// data is not yet retrieved since accessToken is still empty
return user, fmt.Errorf("%s cannot get user information without accessToken", p.providerName)
}

// Get the userID, line needs userID in order to get user profile info
c := p.Client()
req, err := http.NewRequest("GET", endpointUser, nil)
if err != nil {
return user, err
}

req.Header.Add("Authorization", "Bearer "+sess.AccessToken)

response, err := c.Do(req)
if err != nil {
if response != nil {
response.Body.Close()
}
return user, err
}

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
}

u := struct {
Name string `json:"name"`
UserID string `json:"userId"`
DisplayName string `json:"displayName"`
PictureURL string `json:"pictureUrl"`
StatusMessage string `json:"statusMessage"`
}{}

if err = json.NewDecoder(bytes.NewReader(bits)).Decode(&u); err != nil {
return user, err
}

user.NickName = u.DisplayName
user.AvatarURL = u.PictureURL
user.UserID = u.UserID
return user, err
}

func newConfig(provider *Provider, scopes []string) *oauth2.Config {
c := &oauth2.Config{
ClientID: provider.ClientKey,
ClientSecret: provider.Secret,
RedirectURL: provider.CallbackURL,
Endpoint: oauth2.Endpoint{
AuthURL: authURL,
TokenURL: tokenURL,
},
Scopes: []string{},
}

if len(scopes) > 0 {
for _, scope := range scopes {
c.Scopes = append(c.Scopes, scope)
}
}
return c
}

//RefreshTokenAvailable refresh token is provided by auth provider or not
func (p *Provider) RefreshTokenAvailable() bool {
return false
}

//RefreshToken get new access token based on the refresh token
func (p *Provider) RefreshToken(refreshToken string) (*oauth2.Token, error) {
return nil, nil
}
53 changes: 53 additions & 0 deletions providers/line/line_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
package line_test

import (
"os"
"testing"

"github.com/markbates/goth"
"github.com/markbates/goth/providers/line"
"github.com/stretchr/testify/assert"
)

func Test_New(t *testing.T) {
t.Parallel()
a := assert.New(t)
p := provider()

a.Equal(p.ClientKey, os.Getenv("LINE_CLIENT_ID"))
a.Equal(p.Secret, os.Getenv("LINE_CLIENT_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.(*line.Session)
a.NoError(err)
a.Contains(s.AuthURL, "https://access.line.me/oauth2/v2.1/authorize")
}

func Test_SessionFromJSON(t *testing.T) {
t.Parallel()
a := assert.New(t)

p := provider()
session, err := p.UnmarshalSession(`{"AuthURL":"https://access.line.me/oauth2/v2.1/authorize","AccessToken":"1234567890"}`)
a.NoError(err)

s := session.(*line.Session)
a.Equal(s.AuthURL, "https://access.line.me/oauth2/v2.1/authorize")
a.Equal(s.AccessToken, "1234567890")
}

func provider() *line.Provider {
return line.New(os.Getenv("LINE_CLIENT_ID"), os.Getenv("LINE_CLIENT_SECRET"), "/foo")
}
63 changes: 63 additions & 0 deletions providers/line/session.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
package line

import (
"encoding/json"
"errors"
"strings"
"time"

"github.com/markbates/goth"
)

// Session stores data during the auth process with Line.
type Session struct {
AuthURL string
AccessToken string
RefreshToken string
ExpiresAt time.Time
}

var _ goth.Session = &Session{}

// GetAuthURL will return the URL set by calling the `BeginAuth` function on the Line provider.
func (s Session) GetAuthURL() (string, error) {
if s.AuthURL == "" {
return "", errors.New(goth.NoAuthUrlErrorMessage)
}
return s.AuthURL, nil
}

// Authorize the session with Line 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
}
48 changes: 48 additions & 0 deletions providers/line/session_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package line_test

import (
"testing"

"github.com/markbates/goth"
"github.com/markbates/goth/providers/line"
"github.com/stretchr/testify/assert"
)

func Test_Implements_Session(t *testing.T) {
t.Parallel()
a := assert.New(t)
s := &line.Session{}

a.Implements((*goth.Session)(nil), s)
}

func Test_GetAuthURL(t *testing.T) {
t.Parallel()
a := assert.New(t)
s := &line.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 := &line.Session{}

data := s.Marshal()
a.Equal(data, `{"AuthURL":"","AccessToken":"","RefreshToken":"","ExpiresAt":"0001-01-01T00:00:00Z"}`)
}

func Test_String(t *testing.T) {
t.Parallel()
a := assert.New(t)
s := &line.Session{}

a.Equal(s.String(), s.Marshal())
}

0 comments on commit a3114a0

Please sign in to comment.