Skip to content

Commit 5d315f4

Browse files
authored
Merge pull request #323 from nedenwalker/master
Added Strava Provider.
2 parents 7e4de08 + 967a859 commit 5d315f4

File tree

6 files changed

+356
-1
lines changed

6 files changed

+356
-1
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,7 @@ $ go get github.com/markbates/goth
5858
* Soundcloud
5959
* Spotify
6060
* Steam
61+
* Strava
6162
* Stripe
6263
* Tumblr
6364
* Twitch

examples/main.go

+4-1
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@ package main
22

33
import (
44
"fmt"
5-
"github.com/markbates/goth/providers/apple"
65
"html/template"
76
"net/http"
87
"os"
@@ -15,6 +14,7 @@ import (
1514
"github.com/markbates/goth"
1615
"github.com/markbates/goth/gothic"
1716
"github.com/markbates/goth/providers/amazon"
17+
"github.com/markbates/goth/providers/apple"
1818
"github.com/markbates/goth/providers/auth0"
1919
"github.com/markbates/goth/providers/azuread"
2020
"github.com/markbates/goth/providers/battlenet"
@@ -53,6 +53,7 @@ import (
5353
"github.com/markbates/goth/providers/soundcloud"
5454
"github.com/markbates/goth/providers/spotify"
5555
"github.com/markbates/goth/providers/steam"
56+
"github.com/markbates/goth/providers/strava"
5657
"github.com/markbates/goth/providers/stripe"
5758
"github.com/markbates/goth/providers/twitch"
5859
"github.com/markbates/goth/providers/twitter"
@@ -128,6 +129,7 @@ func main() {
128129
gitea.New(os.Getenv("GITEA_KEY"), os.Getenv("GITEA_SECRET"), "http://localhost:3000/auth/gitea/callback"),
129130
shopify.New(os.Getenv("SHOPIFY_KEY"), os.Getenv("SHOPIFY_SECRET"), "http://localhost:3000/auth/shopify/callback", shopify.ScopeReadCustomers, shopify.ScopeReadOrders),
130131
apple.New(os.Getenv("APPLE_KEY"), os.Getenv("APPLE_SECRET"), "http://localhost:3000/auth/apple/callback", nil, apple.ScopeName, apple.ScopeEmail),
132+
strava.New(os.Getenv("STRAVA_KEY"), os.Getenv("STRAVA_SECRET"), "http://localhost:3000/auth/strava/callback"),
131133
)
132134

133135
// OpenID Connect is based on OpenID Connect Auto Discovery URL (https://openid.net/specs/openid-connect-discovery-1_0-17.html)
@@ -190,6 +192,7 @@ func main() {
190192
m["nextcloud"] = "NextCloud"
191193
m["seatalk"] = "SeaTalk"
192194
m["apple"] = "Apple"
195+
m["strava"] = "Strava"
193196

194197
var keys []string
195198
for k := range m {

providers/strava/session.go

+61
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
package strava
2+
3+
import (
4+
"encoding/json"
5+
"errors"
6+
"strings"
7+
"time"
8+
9+
"github.com/markbates/goth"
10+
)
11+
12+
// Session stores data during the auth process with Strava.
13+
type Session struct {
14+
AuthURL string
15+
AccessToken string
16+
RefreshToken string
17+
ExpiresAt time.Time
18+
}
19+
20+
// GetAuthURL will return the URL set by calling the `BeginAuth` function on the Strava provider.
21+
func (s Session) GetAuthURL() (string, error) {
22+
if s.AuthURL == "" {
23+
return "", errors.New(goth.NoAuthUrlErrorMessage)
24+
}
25+
return s.AuthURL, nil
26+
}
27+
28+
// Authorize the session with Strava and return the access token to be stored for future use.
29+
func (s *Session) Authorize(provider goth.Provider, params goth.Params) (string, error) {
30+
p := provider.(*Provider)
31+
token, err := p.config.Exchange(goth.ContextForClient(p.Client()), params.Get("code"))
32+
if err != nil {
33+
return "", err
34+
}
35+
36+
if !token.Valid() {
37+
return "", errors.New("Invalid token received from provider")
38+
}
39+
40+
s.AccessToken = token.AccessToken
41+
s.RefreshToken = token.RefreshToken
42+
s.ExpiresAt = token.Expiry
43+
return token.AccessToken, err
44+
}
45+
46+
// Marshal the session into a string
47+
func (s Session) Marshal() string {
48+
b, _ := json.Marshal(s)
49+
return string(b)
50+
}
51+
52+
func (s Session) String() string {
53+
return s.Marshal()
54+
}
55+
56+
// UnmarshalSession will unmarshal a JSON string into a session.
57+
func (p *Provider) UnmarshalSession(data string) (goth.Session, error) {
58+
s := &Session{}
59+
err := json.NewDecoder(strings.NewReader(data)).Decode(s)
60+
return s, err
61+
}

providers/strava/session_test.go

+48
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
package strava_test
2+
3+
import (
4+
"testing"
5+
6+
"github.com/markbates/goth"
7+
"github.com/markbates/goth/providers/strava"
8+
"github.com/stretchr/testify/assert"
9+
)
10+
11+
func Test_Implements_Session(t *testing.T) {
12+
t.Parallel()
13+
a := assert.New(t)
14+
s := &strava.Session{}
15+
16+
a.Implements((*goth.Session)(nil), s)
17+
}
18+
19+
func Test_GetAuthURL(t *testing.T) {
20+
t.Parallel()
21+
a := assert.New(t)
22+
s := &strava.Session{}
23+
24+
_, err := s.GetAuthURL()
25+
a.Error(err)
26+
27+
s.AuthURL = "/foo"
28+
29+
url, _ := s.GetAuthURL()
30+
a.Equal(url, "/foo")
31+
}
32+
33+
func Test_ToJSON(t *testing.T) {
34+
t.Parallel()
35+
a := assert.New(t)
36+
s := &strava.Session{}
37+
38+
data := s.Marshal()
39+
a.Equal(data, `{"AuthURL":"","AccessToken":"","RefreshToken":"","ExpiresAt":"0001-01-01T00:00:00Z"}`)
40+
}
41+
42+
func Test_String(t *testing.T) {
43+
t.Parallel()
44+
a := assert.New(t)
45+
s := &strava.Session{}
46+
47+
a.Equal(s.String(), s.Marshal())
48+
}

providers/strava/strava.go

+183
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,183 @@
1+
// Package strava implements the OAuth2 protocol for authenticating users through Strava.
2+
// This package can be used as a reference implementation of an OAuth2 provider for Goth.
3+
package strava
4+
5+
import (
6+
"bytes"
7+
"encoding/json"
8+
"fmt"
9+
"github.com/markbates/goth"
10+
"golang.org/x/oauth2"
11+
"io"
12+
"io/ioutil"
13+
"net/http"
14+
"net/url"
15+
)
16+
17+
const (
18+
authURL string = "https://www.strava.com/oauth/authorize"
19+
tokenURL string = "https://www.strava.com/oauth/token"
20+
endpointProfile string = "https://www.strava.com/api/v3/athlete"
21+
)
22+
23+
// New creates a new Strava provider, and sets up important connection details.
24+
// You should always call `strava.New` to get a new Provider. Never try to create
25+
// one manually.
26+
func New(clientKey, secret, callbackURL string, scopes ...string) *Provider {
27+
p := &Provider{
28+
ClientKey: clientKey,
29+
Secret: secret,
30+
CallbackURL: callbackURL,
31+
providerName: "strava",
32+
}
33+
p.config = newConfig(p, scopes)
34+
return p
35+
}
36+
37+
// Provider is the implementation of `goth.Provider` for accessing Strava.
38+
type Provider struct {
39+
ClientKey string
40+
Secret string
41+
CallbackURL string
42+
HTTPClient *http.Client
43+
config *oauth2.Config
44+
providerName string
45+
}
46+
47+
// Name is the name used to retrieve this provider later.
48+
func (p *Provider) Name() string {
49+
return p.providerName
50+
}
51+
52+
// SetName is to update the name of the provider (needed in case of multiple providers of 1 type)
53+
func (p *Provider) SetName(name string) {
54+
p.providerName = name
55+
}
56+
57+
// Client returns an HTTP client to be used in all fetch operations.
58+
func (p *Provider) Client() *http.Client {
59+
return goth.HTTPClientWithFallBack(p.HTTPClient)
60+
}
61+
62+
// Debug is a no-op for the strava package.
63+
func (p *Provider) Debug(debug bool) {}
64+
65+
// BeginAuth asks Strava for an authentication endpoint.
66+
func (p *Provider) BeginAuth(state string) (goth.Session, error) {
67+
authUrl := p.config.AuthCodeURL(state)
68+
session := &Session{
69+
AuthURL: authUrl,
70+
}
71+
return session, nil
72+
}
73+
74+
// FetchUser will go to Strava and access basic information about the user.
75+
func (p *Provider) FetchUser(session goth.Session) (goth.User, error) {
76+
sess := session.(*Session)
77+
user := goth.User{
78+
AccessToken: sess.AccessToken,
79+
Provider: p.Name(),
80+
RefreshToken: sess.RefreshToken,
81+
ExpiresAt: sess.ExpiresAt,
82+
}
83+
84+
if user.AccessToken == "" {
85+
// data is not yet retrieved since accessToken is still empty
86+
return user, fmt.Errorf("%s cannot get user information without accessToken", p.providerName)
87+
}
88+
89+
reqUrl := fmt.Sprint(endpointProfile,
90+
"?access_token=", url.QueryEscape(sess.AccessToken),
91+
)
92+
response, err := p.Client().Get(reqUrl)
93+
if err != nil {
94+
return user, err
95+
}
96+
defer response.Body.Close()
97+
98+
if response.StatusCode != http.StatusOK {
99+
return user, fmt.Errorf("%s responded with a %d trying to fetch user information", p.providerName, response.StatusCode)
100+
}
101+
102+
bits, err := ioutil.ReadAll(response.Body)
103+
if err != nil {
104+
return user, err
105+
}
106+
107+
err = json.NewDecoder(bytes.NewReader(bits)).Decode(&user.RawData)
108+
if err != nil {
109+
return user, err
110+
}
111+
112+
err = userFromReader(bytes.NewReader(bits), &user)
113+
return user, err
114+
}
115+
116+
func userFromReader(reader io.Reader, user *goth.User) error {
117+
u := struct {
118+
ID int64 `json:"id"`
119+
Username string `json:"username"`
120+
FirstName string `json:"firstname"`
121+
LastName string `json:"lastname"`
122+
City string `json:"city"`
123+
Region string `json:"state"`
124+
Country string `json:"country"`
125+
Gender string `json:"sex"`
126+
Picture string `json:"profile"`
127+
}{}
128+
129+
err := json.NewDecoder(reader).Decode(&u)
130+
if err != nil {
131+
return err
132+
}
133+
134+
user.UserID = fmt.Sprintf("%d", u.ID)
135+
user.Name = fmt.Sprintf("%s %s", u.FirstName, u.LastName)
136+
user.FirstName = u.FirstName
137+
user.LastName = u.LastName
138+
user.NickName = u.Username
139+
user.AvatarURL = u.Picture
140+
user.Description = fmt.Sprintf(`{"gender":"%s"}`, u.Gender)
141+
user.Location = fmt.Sprintf(`{"city":"%s","region":"%s","country":"%s"}`, u.City, u.Region, u.Country)
142+
143+
return err
144+
}
145+
146+
func newConfig(provider *Provider, scopes []string) *oauth2.Config {
147+
c := &oauth2.Config{
148+
ClientID: provider.ClientKey,
149+
ClientSecret: provider.Secret,
150+
RedirectURL: provider.CallbackURL,
151+
Endpoint: oauth2.Endpoint{
152+
AuthURL: authURL,
153+
TokenURL: tokenURL,
154+
},
155+
Scopes: []string{},
156+
}
157+
158+
if len(scopes) > 0 {
159+
for _, scope := range scopes {
160+
c.Scopes = append(c.Scopes, scope)
161+
}
162+
} else {
163+
c.Scopes = []string{"read"}
164+
}
165+
166+
return c
167+
}
168+
169+
// RefreshTokenAvailable refresh token is not provided by Strava
170+
func (p *Provider) RefreshTokenAvailable() bool {
171+
return true
172+
}
173+
174+
// RefreshToken refresh token is not provided by Strava
175+
func (p *Provider) RefreshToken(refreshToken string) (*oauth2.Token, error) {
176+
token := &oauth2.Token{RefreshToken: refreshToken}
177+
ts := p.config.TokenSource(goth.ContextForClient(p.Client()), token)
178+
newToken, err := ts.Token()
179+
if err != nil {
180+
return nil, err
181+
}
182+
return newToken, err
183+
}

0 commit comments

Comments
 (0)