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

feat: add Neurodyne provider #563

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
module github.com/markbates/goth

go 1.18
go 1.22

require (
github.com/golang-jwt/jwt/v4 v4.2.0
Expand Down
1 change: 1 addition & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ github.com/golang/protobuf v1.5.3 h1:KhyjKVUg7Usr/dYsdSqoFveMYd5ko72D+zANwlG1mmg
github.com/golang/protobuf v1.5.3/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY=
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38=
github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/gorilla/context v1.1.1 h1:AWwleXJkX/nhcU9bZSnZoi3h/qGYqQAGhq6zZe/aQW8=
github.com/gorilla/context v1.1.1/go.mod h1:kBGZzfjB9CEq2AlWe17Uuf7NDRt0dE0s8S51q0aT7Yg=
github.com/gorilla/mux v1.6.2 h1:Pgr17XVTNXAk3q/r4CpKzC5xBM/qW1uVLV+IhRZpIIk=
Expand Down
3 changes: 2 additions & 1 deletion providers/gitlab/session.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"time"

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

// Session stores data during the auth process with Gitlab.
Expand All @@ -30,7 +31,7 @@ func (s Session) GetAuthURL() (string, error) {
// Authorize the session with Gitlab 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"))
token, err := p.config.Exchange(goth.ContextForClient(p.Client()), params.Get("code"), oauth2.SetAuthURLParam("code_verifier", params.Get("code_verifier")))
if err != nil {
return "", err
}
Expand Down
159 changes: 159 additions & 0 deletions providers/neurodyne/neurodyne.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
// Package Neurodyne implements the OAuth2 protocol for authenticating users through Neurodyne.
// This package can be used as a reference implementation of an OAuth2 provider for Goth.
package neurodyne

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

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

const (
AuthURL string = "https://id.nws.neurodyne.pro/oauth2/auth"
TokenURL string = "https://id.nws.neurodyne.pro/oauth2/token"
ProfileURL string = "https://id.nws.neurodyne.pro/oauth/userinfo"
)

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

// New creates a new Neurodyne provider and sets up important connection details.
// You should always call `neurodyne.New` to get a new provider. Never try to
// create one manually.
func New(clientID, secret, callbackURL string, scopes ...string) *Provider {
p := &Provider{
ClientKey: clientID,
Secret: secret,
CallbackURL: callbackURL,
providerName: "neurodyne",
}
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
}

func (p *Provider) Client() *http.Client {
return goth.HTTPClientWithFallBack(p.HTTPClient)
}

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

// BeginAuth asks Neurodyne 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 Neurodyne 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", ProfileURL, nil)
if err != nil {
return user, err
}
req.Header.Set("Authorization", "Bearer "+s.AccessToken)
resp, err := p.Client().Do(req)
if err != nil {
if resp != nil {
resp.Body.Close()
}
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)
}

err = userFromReader(resp.Body, &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)
}
}

return c
}

func userFromReader(r io.Reader, user *goth.User) error {
u := struct {
Name string `json:"first_name"`
Email string `json:"email"`
ID string `json:"uuid"`
AvatarURL string `json:"picture"`
}{}
err := json.NewDecoder(r).Decode(&u)
if err != nil {
return err
}
user.Email = u.Email
user.Name = u.Name
user.UserID = u.ID
user.AvatarURL = u.AvatarURL
return nil
}

// 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
}
53 changes: 53 additions & 0 deletions providers/neurodyne/neurodyne_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
package neurodyne_test

import (
"os"
"testing"

"github.com/markbates/goth"
"github.com/markbates/goth/providers/neurodyne"
"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("NEURODYNE_KEY"))
a.Equal(p.Secret, os.Getenv("NEURODYNE_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.(*neurodyne.Session)
a.NoError(err)
a.Contains(s.AuthURL, "id.nws.neurodyne.pro/oauth2/auth")
}

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

p := provider()
session, err := p.UnmarshalSession(`{"AuthURL":"https://id.nws.neurodyne.pro/oauth2/auth","AccessToken":"1234567890"}`)
a.NoError(err)

s := session.(*neurodyne.Session)
a.Equal(s.AuthURL, "https://id.nws.neurodyne.pro/oauth2/auth")
a.Equal(s.AccessToken, "1234567890")
}

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

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

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

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

// Authorize the session with Neurodyne 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"), oauth2.SetAuthURLParam("code_verifier", params.Get("code_verifier")))
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/neurodyne/session_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package neurodyne_test

import (
"testing"

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

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

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

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

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