Skip to content

Commit

Permalink
Merge pull request #259 from is2ei/add-typetalk-provider
Browse files Browse the repository at this point in the history
Add Typetalk provider
  • Loading branch information
bentranter authored Jan 3, 2019
2 parents 3338abb + a82f5b6 commit 36164d2
Show file tree
Hide file tree
Showing 6 changed files with 371 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ $ go get github.com/markbates/goth
* Tumblr
* Twitch
* Twitter
* Typetalk
* Uber
* VK
* Wepay
Expand Down
3 changes: 3 additions & 0 deletions examples/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ import (
"github.com/markbates/goth/providers/stripe"
"github.com/markbates/goth/providers/twitch"
"github.com/markbates/goth/providers/twitter"
"github.com/markbates/goth/providers/typetalk"
"github.com/markbates/goth/providers/uber"
"github.com/markbates/goth/providers/vk"
"github.com/markbates/goth/providers/wepay"
Expand Down Expand Up @@ -92,6 +93,7 @@ func main() {
//Pointed localhost.com to http://localhost:3000/auth/yahoo/callback through proxy as yahoo
// does not allow to put custom ports in redirection uri
yahoo.New(os.Getenv("YAHOO_KEY"), os.Getenv("YAHOO_SECRET"), "http://localhost.com"),
typetalk.New(os.Getenv("TYPETALK_KEY"), os.Getenv("TYPETALK_SECRET"), "http://localhost:3000/auth/typetalk/callback", "my"),
slack.New(os.Getenv("SLACK_KEY"), os.Getenv("SLACK_SECRET"), "http://localhost:3000/auth/slack/callback"),
stripe.New(os.Getenv("STRIPE_KEY"), os.Getenv("STRIPE_SECRET"), "http://localhost:3000/auth/stripe/callback"),
wepay.New(os.Getenv("WEPAY_KEY"), os.Getenv("WEPAY_SECRET"), "http://localhost:3000/auth/wepay/callback", "view_user"),
Expand Down Expand Up @@ -162,6 +164,7 @@ func main() {
m["paypal"] = "Paypal"
m["twitter"] = "Twitter"
m["salesforce"] = "Salesforce"
m["typetalk"] = "Typetalk"
m["slack"] = "Slack"
m["meetup"] = "Meetup.com"
m["auth0"] = "Auth0"
Expand Down
63 changes: 63 additions & 0 deletions providers/typetalk/session.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
package typetalk

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

"github.com/markbates/goth"
)

// Session stores data during the auth process with Typetalk.
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 Typetalk provider.
func (s Session) GetAuthURL() (string, error) {
if s.AuthURL == "" {
return "", errors.New(goth.NoAuthUrlErrorMessage)
}
return s.AuthURL, nil
}

// Authorize the session with Typetalk 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/typetalk/session_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package typetalk_test

import (
"testing"

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

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

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

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

a.Equal(s.String(), s.Marshal())
}
203 changes: 203 additions & 0 deletions providers/typetalk/typetalk.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,203 @@
// Package typetalk implements the OAuth2 protocol for authenticating users through Typetalk.
// This package can be used as a reference implementation of an OAuth2 provider for Goth.
//
// Typetalk API Docs: https://developer.nulab-inc.com/docs/typetalk/auth/
package typetalk

import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"strconv"

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

const (
authURL string = "https://typetalk.com/oauth2/authorize"
tokenURL string = "https://typetalk.com/oauth2/access_token"
endpointProfile string = "https://typetalk.com/api/v1/profile"
endpointUser string = "https://typetalk.com/api/v1/accounts/profile/"
)

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

// New creates a new Typetalk provider and sets up important connection details.
// You should always call `typetalk.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: "typetalk",
}
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 os 1 type)
func (p *Provider) SetName(name string) {
p.providerName = name
}

// Client returns HTTP client.
func (p *Provider) Client() *http.Client {
return goth.HTTPClientWithFallBack(p.HTTPClient)
}

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

// BeginAuth asks Typetalk 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 Typetalk 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 user name
response, err := p.Client().Get(endpointProfile + "?access_token=" + url.QueryEscape(sess.AccessToken))
if err != nil {
if response != nil {
response.Body.Close()
}
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 name", p.providerName, response.StatusCode)
}

bits, err := ioutil.ReadAll(response.Body)
if err != nil {
return user, err
}

u := struct {
Account struct {
Name string `json:"name"`
} `json:"account"`
}{}

err = json.NewDecoder(bytes.NewReader(bits)).Decode(&u)

// Get user profile info
response, err = p.Client().Get(endpointUser + u.Account.Name + "?access_token=" + url.QueryEscape(sess.AccessToken))
if err != nil {
if response != nil {
response.Body.Close()
}
return user, err
}
defer response.Body.Close()

if response.StatusCode != http.StatusOK {
return user, fmt.Errorf("%s responded with a %d trying to fetch profile", 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
}

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)
}
} else {
c.Scopes = append(c.Scopes, "my")
}
return c
}

func userFromReader(r io.Reader, user *goth.User) error {
u := struct {
Account struct {
ID int64 `json:"id"`
Name string `json:"name"`
FullName string `json:"fullName"`
Suggestion string `json:"suggestion"`
MailAddress string `json:"mailAddress"`
ImageURL string `json:"imageUrl"`
CreatedAt string `json:"createdAt"`
UpdatedAt string `json:"updatedAt"`
ImageUpdatedAt string `json:"imageUpdatedAt"`
} `json:"account"`
}{}
err := json.NewDecoder(r).Decode(&u)
if err != nil {
return err
}
user.UserID = strconv.FormatInt(u.Account.ID, 10)
user.Email = u.Account.MailAddress
user.Name = u.Account.FullName
user.NickName = u.Account.Name
user.AvatarURL = u.Account.ImageURL
return nil
}

//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
}
Loading

0 comments on commit 36164d2

Please sign in to comment.