Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Patreon Provider #478

Merged
merged 17 commits into from
Nov 4, 2022
186 changes: 186 additions & 0 deletions providers/patreon/patreon.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,186 @@
// Package patreon implements the OAuth protocol for authenticating users through Patreon.
package patreon

import (
"encoding/json"
"fmt"
"net/http"

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

//goland:noinspection GoUnusedConst
const (
// ScopeIdentity provides read access to data about the user. See the /identity endpoint documentation for details about what data is available.
ScopeIdentity = "identity"

// ScopeIdentityEmail provides read access to the user’s email.
ScopeIdentityEmail = "identity[email]"

// ScopeIdentityMemberships provides read access to the user’s memberships.
ScopeIdentityMemberships = "identity.memberships"

// ScopeCampaigns provides read access to basic campaign data. See the /campaign endpoint documentation for details about what data is available.
ScopeCampaigns = "campaigns"

// ScopeCampaignsWebhook provides read, write, update, and delete access to the campaign’s webhooks created by the client.
ScopeCampaignsWebhook = "w:campaigns.webhook"

// ScopeCampaignsMembers provides read access to data about a campaign’s members. See the /members endpoint documentation for details about what data is available. Also allows the same information to be sent via webhooks created by your client.
ScopeCampaignsMembers = "campaigns.members"

// ScopeCampaignsMembersEmail provides read access to the member’s email. Also allows the same information to be sent via webhooks created by your client.
ScopeCampaignsMembersEmail = "campaigns.members[email]"

// ScopeCampaignsMembersAddress provides read access to the member’s address, if an address was collected in the pledge flow. Also allows the same information to be sent via webhooks created by your client.
ScopeCampaignsMembersAddress = "campaigns.members.address"

// ScopeCampaignsPosts provides read access to the posts on a campaign.
ScopeCampaignsPosts = "campaigns.posts"
)

// New creates a new Patreon provider and sets up important connection details.
// You should always call `Patreon.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: "patreon",
}
p.config = newConfig(p, scopes)
return p
}

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

// Name gets the name used to retrieve this provider.
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)
}

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

// BeginAuth asks Patreon 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
}

// FetchUser will go to Patreon and access basic information about the user.
func (p *Provider) FetchUser(session goth.Session) (goth.User, error) {
s := session.(*Session)
user := goth.User{
AccessToken: s.AccessToken,
Provider: p.Name(),
RefreshToken: s.RefreshToken,
ExpiresAt: s.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)
}

req, err := http.NewRequest("GET", "https://www.patreon.com/api/oauth2/v2/identity", nil)
if err != nil {
return user, err
}
req.Header.Set("Authorization", "Bearer "+s.AccessToken)
resp, err := p.Client().Do(req)
if err != nil {
return user, err
}
defer resp.Body.Close()

if resp.StatusCode != http.StatusOK {
return user, fmt.Errorf("%s responded with a %d trying to fetch user information", p.providerName, resp.StatusCode)
}

u := User{}
err = json.NewDecoder(resp.Body).Decode(&u)
if err != nil {
return user, err
}

user.Name = u.Data.Attributes.FullName
user.Email = u.Data.Attributes.Email
user.UserID = u.Data.ID

return user, err
}

func newConfig(p *Provider, scopes []string) *oauth2.Config {
c := &oauth2.Config{
ClientID: p.ClientKey,
ClientSecret: p.Secret,
RedirectURL: p.CallbackURL,
Endpoint: oauth2.Endpoint{
AuthURL: "https://www.patreon.com/oauth2/authorize",
Jleagle marked this conversation as resolved.
Show resolved Hide resolved
TokenURL: "https://www.patreon.com/api/oauth2/token",
},
Scopes: []string{ScopeIdentity, ScopeIdentityEmail},
}

defaultScopes := map[string]struct{}{
ScopeIdentity: {},
ScopeIdentityEmail: {},
}

for _, scope := range scopes {
if _, exists := defaultScopes[scope]; !exists {
c.Scopes = append(c.Scopes, scope)
}
}

return c
}

// RefreshTokenAvailable refresh token is provided by auth provider or not
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
}

type User struct {
Data struct {
Attributes struct {
Email string `json:"email"`
FullName string `json:"full_name"`
} `json:"attributes"`
ID string `json:"id"`
} `json:"data"`
}
53 changes: 53 additions & 0 deletions providers/patreon/patreon_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
package patreon

import (
"os"
"testing"

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

func provider() *Provider {
return New(os.Getenv("PATREON_KEY"), os.Getenv("PATREON_SECRET"), "/foo", "user")
}

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

a.Equal(p.ClientKey, os.Getenv("PATREON_KEY"))
a.Equal(p.Secret, os.Getenv("PATREON_SECRET"))
a.Equal(p.CallbackURL, "/foo")
}

func Test_ImplementsProvider(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.(*Session)
a.NoError(err)
a.Contains(s.AuthURL, "www.patreon.com/oauth2/authorize")
}

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

p := provider()
session, err := p.UnmarshalSession(`{"AuthURL":"http://www.patreon.com/oauth2/authorize","AccessToken":"1234567890"}`)
a.NoError(err)

s := session.(*Session)
a.Equal(s.AuthURL, "http://www.patreon.com/oauth2/authorize")
a.Equal(s.AccessToken, "1234567890")
}
63 changes: 63 additions & 0 deletions providers/patreon/session.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
package patreon

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

"github.com/markbates/goth"
)

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

// Authorize completes the authorization with Patreon and returns 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 marshals a session into a JSON string.
func (s *Session) Marshal() string {
j, _ := json.Marshal(s)
return string(j)
}

// String is equivalent to Marshal. It returns a JSON representation of the session.
func (s *Session) String() string {
return s.Marshal()
}

// UnmarshalSession will unmarshal a JSON string into a session.
func (p *Provider) UnmarshalSession(data string) (goth.Session, error) {
s := Session{}
err := json.Unmarshal([]byte(data), &s)
return &s, err
}
37 changes: 37 additions & 0 deletions providers/patreon/session_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package patreon

import (
"testing"

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

func Test_ImplementsSession(t *testing.T) {
t.Parallel()
a := assert.New(t)
s := &Session{}
a.Implements((*goth.Session)(nil), s)
}

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

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