Skip to content

Commit

Permalink
Merge pull request #281 from mattevans/shopify
Browse files Browse the repository at this point in the history
New provider: Shopify
  • Loading branch information
bentranter authored Jun 14, 2019
2 parents c7b58e2 + 1824858 commit d72fa8b
Show file tree
Hide file tree
Showing 7 changed files with 451 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ $ go get github.com/markbates/goth
* OpenID Connect (auto discovery)
* Paypal
* SalesForce
* Shopify
* Slack
* Soundcloud
* Spotify
Expand Down
3 changes: 3 additions & 0 deletions examples/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ import (
"github.com/markbates/goth/providers/openidConnect"
"github.com/markbates/goth/providers/paypal"
"github.com/markbates/goth/providers/salesforce"
"github.com/markbates/goth/providers/shopify"
"github.com/markbates/goth/providers/slack"
"github.com/markbates/goth/providers/soundcloud"
"github.com/markbates/goth/providers/spotify"
Expand Down Expand Up @@ -122,6 +123,7 @@ func main() {
yandex.New(os.Getenv("YANDEX_KEY"), os.Getenv("YANDEX_SECRET"), "http://localhost:3000/auth/yandex/callback"),
nextcloud.NewCustomisedDNS(os.Getenv("NEXTCLOUD_KEY"), os.Getenv("NEXTCLOUD_SECRET"), "http://localhost:3000/auth/nextcloud/callback", os.Getenv("NEXTCLOUD_URL")),
gitea.New(os.Getenv("GITEA_KEY"), os.Getenv("GITEA_SECRET"), "http://localhost:3000/auth/gitea/callback"),
shopify.New(os.Getenv("SHOPIFY_KEY"), os.Getenv("SHOPIFY_SECRET"), "http://localhost:3000/auth/shopify/callback", shopify.ScopeReadCustomers, shopify.ScopeReadOrders),
)

// OpenID Connect is based on OpenID Connect Auto Discovery URL (https://openid.net/specs/openid-connect-discovery-1_0-17.html)
Expand Down Expand Up @@ -149,6 +151,7 @@ func main() {
m["gitlab"] = "Gitlab"
m["google"] = "Google"
m["gplus"] = "Google Plus"
m["shopify"] = "Shopify"
m["soundcloud"] = "SoundCloud"
m["spotify"] = "Spotify"
m["steam"] = "Steam"
Expand Down
49 changes: 49 additions & 0 deletions providers/shopify/scopes.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package shopify

// Define scopes supported by Shopify.
// See: https://help.shopify.com/en/api/getting-started/authentication/oauth/scopes#authenticated-access-scopes
const (
ScopeReadContent = "read_content"
ScopeWriteContent = "write_content"
ScopeReadThemes = "read_themes"
ScopeWriteThemes = "write_themes"
ScopeReadProducts = "read_products"
ScopeWriteProducts = "write_products"
ScopeReadProductListings = "read_product_listings"
ScopeReadCustomers = "read_customers"
ScopeWriteCustomers = "write_customers"
ScopeReadOrders = "read_orders"
ScopeWriteOrders = "write_orders"
ScopeReadDrafOrders = "read_draft_orders"
ScopeWriteDrafOrders = "write_draft_orders"
ScopeReadInventory = "read_inventory"
ScopeWriteInventory = "write_inventory"
ScopeReadLocations = "read_locations"
ScopeReadScriptTags = "read_script_tags"
ScopeWriteScriptTags = "write_script_tags"
ScopeReadFulfillments = "read_fulfillments"
ScopeWriteFulfillments = "write_fulfillments"
ScopeReadShipping = "read_shipping"
ScopeWriteShipping = "write_shipping"
ScopeReadAnalytics = "read_analytics"
ScopeReadUsers = "read_users"
ScopeWriteUsers = "write_users"
ScopeReadCheckouts = "read_checkouts"
ScopeWriteCheckouts = "write_checkouts"
ScopeReadReports = "read_reports"
ScopeWriteReports = "write_reports"
ScopeReadPriceRules = "read_price_rules"
ScopeWritePriceRules = "write_price_rules"
ScopeMarketingEvents = "read_marketing_events"
ScopeWriteMarketingEvents = "write_marketing_events"
ScopeReadResourceFeedbacks = "read_resource_feedbacks"
ScopeWriteResourceFeedbacks = "write_resource_feedbacks"
ScopeReadShopifyPaymentsPayouts = "read_shopify_payments_payouts"
ScopeReadShopifyPaymentsDisputes = "read_shopify_payments_disputes"

// Special:
// Grants access to all orders rather than the default window of 60 days worth of orders.
// This OAuth scope is used in conjunction with read_orders, or write_orders. You need to request
// this scope from your Partner Dashboard before adding it to your app.
ScopeReadAllOrders = "read_all_orders"
)
102 changes: 102 additions & 0 deletions providers/shopify/session.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
package shopify

import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"os"
"regexp"
"strings"
"time"

"github.com/markbates/goth"
)

const (
shopifyHostnameRegex = `^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$`
)

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

var _ goth.Session = &Session{}

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

// Authorize the session with Shopify and return the access token to be stored for future use.
func (s *Session) Authorize(provider goth.Provider, params goth.Params) (string, error) {
// Validate the incoming HMAC is valid.
// See: https://help.shopify.com/en/api/getting-started/authentication/oauth#verification
digest := fmt.Sprintf(
"code=%s&shop=%s&state=%s&timestamp=%s",
params.Get("code"),
params.Get("shop"),
params.Get("state"),
params.Get("timestamp"),
)
h := hmac.New(sha256.New, []byte(os.Getenv("SHOPIFY_SECRET")))
h.Write([]byte(digest))
sha := hex.EncodeToString(h.Sum(nil))

// Ensure our HMAC hash's match.
if sha != params.Get("hmac") {
return "", errors.New("Invalid HMAC received")
}

// Validate the hostname matches what we're expecting.
// See: https://help.shopify.com/en/api/getting-started/authentication/oauth#step-3-confirm-installation
re := regexp.MustCompile(shopifyHostnameRegex)
if !re.MatchString(params.Get("shop")) {
return "", errors.New("Invalid hostname received")
}

// Make the exchange for an access token.
p := provider.(*Provider)
token, err := p.config.Exchange(goth.ContextForClient(p.Client()), params.Get("code"))
if err != nil {
return "", err
}

// Ensure it's valid.
if !token.Valid() {
return "", errors.New("Invalid token received from provider")
}

s.AccessToken = token.AccessToken
s.Hostname = params.Get("hostname")
s.HMAC = params.Get("hmac")

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/shopify/session_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package shopify_test

import (
"testing"

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

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

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

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

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

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

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

0 comments on commit d72fa8b

Please sign in to comment.