diff --git a/go.mod b/go.mod index 7614f7604..6220b28b6 100644 --- a/go.mod +++ b/go.mod @@ -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 diff --git a/go.sum b/go.sum index 9aedbc5db..cea72a300 100644 --- a/go.sum +++ b/go.sum @@ -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= diff --git a/providers/gitlab/session.go b/providers/gitlab/session.go index a2f90647c..b9c0aef03 100644 --- a/providers/gitlab/session.go +++ b/providers/gitlab/session.go @@ -7,6 +7,7 @@ import ( "time" "github.com/markbates/goth" + "golang.org/x/oauth2" ) // Session stores data during the auth process with Gitlab. @@ -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 } diff --git a/providers/neurodyne/neurodyne.go b/providers/neurodyne/neurodyne.go new file mode 100644 index 000000000..ef8fef91b --- /dev/null +++ b/providers/neurodyne/neurodyne.go @@ -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 +} diff --git a/providers/neurodyne/neurodyne_test.go b/providers/neurodyne/neurodyne_test.go new file mode 100644 index 000000000..5efe7173f --- /dev/null +++ b/providers/neurodyne/neurodyne_test.go @@ -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") +} diff --git a/providers/neurodyne/session.go b/providers/neurodyne/session.go new file mode 100644 index 000000000..d86ad1037 --- /dev/null +++ b/providers/neurodyne/session.go @@ -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 +} diff --git a/providers/neurodyne/session_test.go b/providers/neurodyne/session_test.go new file mode 100644 index 000000000..43e0c82a2 --- /dev/null +++ b/providers/neurodyne/session_test.go @@ -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()) +}