From eb2ff2ab23a70298c65f19d52b76c794b2f4937c Mon Sep 17 00:00:00 2001 From: tsmethurst Date: Wed, 17 Mar 2021 11:33:06 +0100 Subject: Some more messing around with oauth2 --- internal/oauth/oauth_test.go | 115 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 115 insertions(+) create mode 100644 internal/oauth/oauth_test.go (limited to 'internal/oauth/oauth_test.go') diff --git a/internal/oauth/oauth_test.go b/internal/oauth/oauth_test.go new file mode 100644 index 000000000..4d942c51d --- /dev/null +++ b/internal/oauth/oauth_test.go @@ -0,0 +1,115 @@ +package oauth + +import ( + "context" + "testing" + "time" + + "github.com/go-pg/pg/v10" + "github.com/go-pg/pg/v10/orm" + "github.com/gotosocial/gotosocial/internal/api" + "github.com/gotosocial/gotosocial/internal/config" + "github.com/gotosocial/gotosocial/internal/gtsmodel" + "github.com/gotosocial/oauth2/v4" + "github.com/sirupsen/logrus" + "github.com/stretchr/testify/suite" + "golang.org/x/crypto/bcrypt" +) + +type OauthTestSuite struct { + suite.Suite + tokenStore oauth2.TokenStore + clientStore oauth2.ClientStore + conn *pg.DB + testClientID string + testClientSecret string + testClientDomain string + testClientUserID string + testUser *gtsmodel.User + config *config.Config +} + +const () + +// SetupSuite sets some variables on the suite that we can use as consts (more or less) throughout +func (suite *OauthTestSuite) SetupSuite() { + suite.testClientID = "test-client-id" + suite.testClientSecret = "test-client-secret" + suite.testClientDomain = "https://example.org" + suite.testClientUserID = "test-client-user-id" + encryptedPassword, err := bcrypt.GenerateFromPassword([]byte("test-password"), bcrypt.DefaultCost) + if err != nil { + logrus.Panicf("error encrypting user pass: %s", err) + } + suite.testUser = >smodel.User{ + EncryptedPassword: string(encryptedPassword), + Email: "user@example.org", + CreatedAt: time.Now(), + UpdatedAt: time.Now(), + AccountID: "whatever", + } +} + +// SetupTest creates a postgres connection and creates the oauth_clients table before each test +func (suite *OauthTestSuite) SetupTest() { + suite.conn = pg.Connect(&pg.Options{}) + if err := suite.conn.Ping(context.Background()); err != nil { + logrus.Panicf("db connection error: %s", err) + } + + models := []interface{}{ + &oauthClient{}, + &oauthToken{}, + >smodel.User{}, + } + + for _, m := range models { + if err := suite.conn.Model(m).CreateTable(&orm.CreateTableOptions{ + IfNotExists: true, + }); err != nil { + logrus.Panicf("db connection error: %s", err) + } + } + + suite.tokenStore = NewPGTokenStore(context.Background(), suite.conn, logrus.New()) + suite.clientStore = NewPGClientStore(suite.conn) + + if _, err := suite.conn.Model(suite.testUser).Insert(); err != nil { + logrus.Panicf("could not insert test user into db: %s", err) + } + +} + +// TearDownTest drops the oauth_clients table and closes the pg connection after each test +func (suite *OauthTestSuite) TearDownTest() { + models := []interface{}{ + &oauthClient{}, + &oauthToken{}, + >smodel.User{}, + } + for _, m := range models { + if err := suite.conn.Model(m).DropTable(&orm.DropTableOptions{}); err != nil { + logrus.Panicf("drop table error: %s", err) + } + } + if err := suite.conn.Close(); err != nil { + logrus.Panicf("error closing db connection: %s", err) + } + suite.conn = nil +} + +func (suite *OauthTestSuite) TestAPIInitialize() { + log := logrus.New() + log.SetLevel(logrus.DebugLevel) + + r := api.New(suite.config, log) + api := New(suite.tokenStore, suite.clientStore, suite.conn, log) + api.AddRoutes(r) + go r.Start() + time.Sleep(30 * time.Second) + // http://localhost:8080/oauth/authorize?client_id=whatever +} + +func TestOauthTestSuite(t *testing.T) { + suite.Run(t, new(OauthTestSuite)) +} -- cgit v1.2.3 From 6eab00e05e6e65a2b8fc738ae25be5fa6c5283b3 Mon Sep 17 00:00:00 2001 From: tsmethurst Date: Wed, 17 Mar 2021 16:01:31 +0100 Subject: getting there....... --- go.mod | 4 +- go.sum | 3 +- internal/api/server.go | 4 +- internal/oauth/oauth.go | 194 +++++++++++++++++++++-------------- internal/oauth/oauth_test.go | 39 ++++--- internal/oauth/pgclientstore.go | 13 ++- internal/oauth/pgclientstore_test.go | 1 - internal/oauth/pgtokenstore.go | 33 ++++-- 8 files changed, 180 insertions(+), 111 deletions(-) (limited to 'internal/oauth/oauth_test.go') diff --git a/go.mod b/go.mod index 75b82ea18..6f1ede9ed 100644 --- a/go.mod +++ b/go.mod @@ -3,12 +3,12 @@ module github.com/gotosocial/gotosocial go 1.16 require ( - github.com/gin-contrib/sessions v0.0.3 // indirect + github.com/gin-contrib/sessions v0.0.3 github.com/gin-gonic/gin v1.6.3 github.com/go-fed/activity v1.0.0 github.com/go-pg/pg/extra/pgdebug v0.2.0 github.com/go-pg/pg/v10 v10.8.0 - github.com/go-session/session v3.1.2+incompatible // indirect + github.com/go-session/session v3.1.2+incompatible github.com/golang/mock v1.4.4 // indirect github.com/google/uuid v1.2.0 // indirect github.com/gotosocial/oauth2/v4 v4.2.1-0.20210316171520-7b12112bbb88 diff --git a/go.sum b/go.sum index 6edb85cb4..f482187af 100644 --- a/go.sum +++ b/go.sum @@ -105,8 +105,6 @@ github.com/gorilla/sessions v1.1.3 h1:uXoZdcdA5XdXF3QzuSlheVRUvjl+1rKY7zBXL68L9R github.com/gorilla/sessions v1.1.3/go.mod h1:8KCfur6+4Mqcc6S0FEfKuN15Vl5MgXW92AE8ovaJD0w= github.com/gorilla/websocket v1.4.2 h1:+/TMaTYc4QFitKJxsQ7Yye35DkWvkdLcvGKqM+x0Ufc= github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= -github.com/gotosocial/oauth2/v4 v4.2.1-0.20210315164102-1f7842217e57 h1:+zKsBEkg1cbz7zJDms1KMU9vJBeBAlElS1SbK/x0Rvc= -github.com/gotosocial/oauth2/v4 v4.2.1-0.20210315164102-1f7842217e57/go.mod h1:zl5kwHf/atRUrY5yOyDnk49Us1Ygs0BzdW4jKAgoiP8= github.com/gotosocial/oauth2/v4 v4.2.1-0.20210316171520-7b12112bbb88 h1:YJ//HmHOYJ4srm/LA6VPNjNisneMbY6TTM1xttV/ZQU= github.com/gotosocial/oauth2/v4 v4.2.1-0.20210316171520-7b12112bbb88/go.mod h1:zl5kwHf/atRUrY5yOyDnk49Us1Ygs0BzdW4jKAgoiP8= github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= @@ -163,6 +161,7 @@ github.com/onsi/gomega v1.10.5/go.mod h1:gza4q3jKQJijlu05nKWRCW/GavJumGt8aNRxWg7 github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/quasoft/memstore v0.0.0-20180925164028-84a050167438 h1:jnz/4VenymvySjE+Ez511s0pqVzkUOmr1fwCVytNNWk= github.com/quasoft/memstore v0.0.0-20180925164028-84a050167438/go.mod h1:wTPjTepVu7uJBYgZ0SdWHQlIas582j6cn2jgk4DDdlg= github.com/russross/blackfriday/v2 v2.0.1 h1:lPqVAte+HuHNfhJ/0LC98ESWRz8afy9tM/0RK8m9o+Q= github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= diff --git a/internal/api/server.go b/internal/api/server.go index 0cfe23531..321c932cd 100644 --- a/internal/api/server.go +++ b/internal/api/server.go @@ -69,8 +69,8 @@ func (s *server) AttachHandler(method string, path string, handler gin.HandlerFu func New(config *config.Config, logger *logrus.Logger) Server { engine := gin.New() - store := memstore.NewStore([]byte("authentication-key"), []byte("encryption-key")) - engine.Use(sessions.Sessions("mysession", store)) + store := memstore.NewStore([]byte("authentication-key"), []byte("encryption-keyencryption-key----")) + engine.Use(sessions.Sessions("gotosocial-session", store)) return &server{ APIGroup: engine.Group("/api").Group("/v1"), logger: logger, diff --git a/internal/oauth/oauth.go b/internal/oauth/oauth.go index 94258b806..d1f3bcf54 100644 --- a/internal/oauth/oauth.go +++ b/internal/oauth/oauth.go @@ -19,16 +19,12 @@ package oauth import ( - "bytes" - "fmt" "net/http" "net/url" - "time" "github.com/gin-contrib/sessions" "github.com/gin-gonic/gin" "github.com/go-pg/pg/v10" - "github.com/go-session/session" "github.com/gotosocial/gotosocial/internal/api" "github.com/gotosocial/gotosocial/internal/gtsmodel" "github.com/gotosocial/oauth2/v4" @@ -48,6 +44,19 @@ type API struct { log *logrus.Logger } +type login struct { + Username string `form:"username"` + Password string `form:"password"` +} + +type authorize struct { + ForceLogin string `form:"force_login,omitempty"` + ResponseType string `form:"response_type"` + ClientID string `form:"client_id"` + RedirectURI string `form:"redirect_uri"` + Scope string `form:"scope,omitempty"` +} + func New(ts oauth2.TokenStore, cs oauth2.ClientStore, conn *pg.DB, log *logrus.Logger) *API { manager := manage.NewDefaultManager() manager.MapTokenStorage(ts) @@ -77,10 +86,11 @@ func New(ts oauth2.TokenStore, cs oauth2.ClientStore, conn *pg.DB, log *logrus.L } func (a *API) AddRoutes(s api.Server) error { - s.AttachHandler(methodAny, "/auth/sign_in", a.SignInHandler) - s.AttachHandler(methodAny, "/oauth/token", gin.WrapF(a.TokenHandler)) - s.AttachHandler(methodAny, "/oauth/authorize", gin.WrapF(a.AuthorizeHandler)) - s.AttachHandler(methodAny, "/auth", gin.WrapF(a.AuthHandler)) + s.AttachHandler(http.MethodGet, "/auth/sign_in", a.SignInGETHandler) + s.AttachHandler(http.MethodPost, "/auth/sign_in", a.SignInPOSTHandler) + s.AttachHandler(methodAny, "/oauth/token", a.TokenHandler) + s.AttachHandler(http.MethodGet, "/oauth/authorize", a.AuthorizeHandler) + s.AttachHandler(methodAny, "/auth", a.AuthHandler) return nil } @@ -92,78 +102,132 @@ func incorrectPassword() (string, error) { MAIN HANDLERS -- serve these through a server/router */ -// SignInHandler should be served at https://example.org/auth/sign_in. +// SignInGETHandler should be served at https://example.org/auth/sign_in. +// The idea is to present a sign in page to the user, where they can enter their username and password. +// The form will then POST to the sign in page, which will be handled by SignInPOSTHandler +func (a *API) SignInGETHandler(c *gin.Context) { + c.Data(http.StatusOK, "text/html; charset=utf-8", []byte(signInHTML)) +} + +// SignInPOSTHandler should be served at https://example.org/auth/sign_in. // The idea is to present a sign in page to the user, where they can enter their username and password. // The handler will then redirect to the auth handler served at /auth -func (a *API) SignInHandler(c *gin.Context) { +func (a *API) SignInPOSTHandler(c *gin.Context) { s := sessions.Default(c) - if r.Method == "POST" { - if r.Form == nil { - if err := r.ParseForm(); err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } - } - s.Set("username", r.Form.Get("username")) - s.Save() - - w.Header().Set("Location", "/auth") - w.WriteHeader(http.StatusFound) + form := &login{} + if err := c.ShouldBind(form); err != nil || form.Username == "" || form.Password == "" { + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) return } - http.ServeContent(w, r, "sign_in.html", time.Unix(0, 0), bytes.NewReader([]byte(signInHTML))) + s.Set("username", form.Username) + if err := s.Save(); err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + c.Redirect(http.StatusFound, "/auth") } // TokenHandler should be served at https://example.org/oauth/token // The idea here is to serve an oauth access token to a user, which can be used for authorizing against non-public APIs. // See https://docs.joinmastodon.org/methods/apps/oauth/#obtain-a-token -func (a *API) TokenHandler(w http.ResponseWriter, r *http.Request) { - if err := a.server.HandleTokenRequest(w, r); err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) +func (a *API) TokenHandler(c *gin.Context) { + if err := a.server.HandleTokenRequest(c.Writer, c.Request); err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) } } -// AuthorizeHandler should be served at https://example.org/oauth/authorize +// AuthorizeHandler should be served as GET at https://example.org/oauth/authorize // The idea here is to present an oauth authorize page to the user, with a button // that they have to click to accept. See here: https://docs.joinmastodon.org/methods/apps/oauth/#authorize-a-user -func (a *API) AuthorizeHandler(w http.ResponseWriter, r *http.Request) { - store, err := session.Start(nil, w, r) - if err != nil { +func (a *API) AuthorizeHandler(c *gin.Context) { + s := sessions.Default(c) + form := &authorize{} - http.Error(w, err.Error(), http.StatusInternalServerError) + if err := c.ShouldBind(form); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) return } - if _, ok := store.Get("username"); !ok { - w.Header().Set("Location", "/auth/sign_in") - w.WriteHeader(http.StatusFound) + if form.ResponseType == "" || form.ClientID == "" || form.RedirectURI == "" { + c.JSON(http.StatusBadRequest, gin.H{"error": "missing one of: response_type, client_id or redirect_uri"}) return } - http.ServeContent(w, r, "authorize.html", time.Unix(0, 0), bytes.NewReader([]byte(authorizeHTML))) + s.Set("force_login", form.ForceLogin) + s.Set("response_type", form.ResponseType) + s.Set("client_id", form.ClientID) + s.Set("redirect_uri", form.RedirectURI) + s.Set("scope", form.Scope) + if err := s.Save(); err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + } + + v := s.Get("username") + if username, ok := v.(string); !ok || username == "" { + c.Redirect(http.StatusFound, "/auth/sign_in") + return + } + + c.Data(http.StatusOK, "text/html; charset=utf-8", []byte(authorizeHTML)) } // AuthHandler should be served at https://example.org/auth -func (a *API) AuthHandler(w http.ResponseWriter, r *http.Request) { - store, err := session.Start(r.Context(), w, r) - if err != nil { - a.log.Errorf("error creating session in authhandler: %s", err) - http.Error(w, err.Error(), http.StatusInternalServerError) +func (a *API) AuthHandler(c *gin.Context) { + s := sessions.Default(c) + + values := url.Values{} + + if v, ok := s.Get("force_login").(string); !ok { + c.JSON(http.StatusBadRequest, gin.H{"error": "session missing force_login"}) + return + } else { + values.Add("force_login", v) + } + + if v, ok := s.Get("response_type").(string); !ok { + c.JSON(http.StatusBadRequest, gin.H{"error": "session missing response_type"}) + return + } else { + values.Add("response_type", v) + } + + if v, ok := s.Get("client_id").(string); !ok { + c.JSON(http.StatusBadRequest, gin.H{"error": "session missing client_id"}) + return + } else { + values.Add("client_id", v) + } + + if v, ok := s.Get("redirect_uri").(string); !ok { + c.JSON(http.StatusBadRequest, gin.H{"error": "session missing redirect_uri"}) + return + } else { + values.Add("redirect_uri", v) + } + + if v, ok := s.Get("scope").(string); !ok { + c.JSON(http.StatusBadRequest, gin.H{"error": "session missing scope"}) return + } else { + values.Add("scope", v) } - var form url.Values - if v, ok := store.Get("ReturnUri"); ok { - form = v.(url.Values) + if v, ok := s.Get("username").(string); !ok { + c.JSON(http.StatusBadRequest, gin.H{"error": "session missing username"}) + return + } else { + values.Add("username", v) } - r.Form = form - store.Delete("ReturnUri") - store.Save() + c.Request.Form = values - if err := a.server.HandleAuthorizeRequest(w, r); err != nil { - a.log.Errorf("error in authhandler during handleauthorizerequest: %s", err) - http.Error(w, err.Error(), http.StatusBadRequest) + if err := s.Save(); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + return + } + + if err := a.server.HandleAuthorizeRequest(c.Writer, c.Request); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) } } @@ -203,34 +267,14 @@ func (a *API) PasswordAuthorizationHandler(email string, password string) (useri return } -// UserAuthorizationHandler gets the user's email address from the session key 'username' +// UserAuthorizationHandler gets the user's email address from the form key 'username' // or redirects to the /auth/sign_in page, if this key is not present. func (a *API) UserAuthorizationHandler(w http.ResponseWriter, r *http.Request) (string, error) { - a.log.Errorf("entering userauthorizationhandler") - - sessionStore, err := session.Start(r.Context(), w, r) - if err != nil { - a.log.Errorf("error starting session: %s", err) - return "", err + username := r.FormValue("username") + if username == "" { + http.Redirect(w, r, "/auth/sign_in", http.StatusFound) + return "", nil } - - v, ok := sessionStore.Get("username") - if !ok { - if err := r.ParseForm(); err != nil { - a.log.Errorf("error parsing form: %s", err) - return "", err - } - - sessionStore.Set("ReturnUri", r.Form) - sessionStore.Save() - - w.Header().Set("Location", "/auth/sign_in") - w.WriteHeader(http.StatusFound) - return v.(string), nil - } - - sessionStore.Delete("username") - sessionStore.Save() - return v.(string), nil + return username, nil } diff --git a/internal/oauth/oauth_test.go b/internal/oauth/oauth_test.go index 4d942c51d..f786df396 100644 --- a/internal/oauth/oauth_test.go +++ b/internal/oauth/oauth_test.go @@ -7,6 +7,7 @@ import ( "github.com/go-pg/pg/v10" "github.com/go-pg/pg/v10/orm" + "github.com/google/uuid" "github.com/gotosocial/gotosocial/internal/api" "github.com/gotosocial/gotosocial/internal/config" "github.com/gotosocial/gotosocial/internal/gtsmodel" @@ -18,35 +19,37 @@ import ( type OauthTestSuite struct { suite.Suite - tokenStore oauth2.TokenStore - clientStore oauth2.ClientStore - conn *pg.DB - testClientID string - testClientSecret string - testClientDomain string - testClientUserID string - testUser *gtsmodel.User - config *config.Config + tokenStore oauth2.TokenStore + clientStore oauth2.ClientStore + conn *pg.DB + testUser *gtsmodel.User + testClient *oauthClient + config *config.Config } const () // SetupSuite sets some variables on the suite that we can use as consts (more or less) throughout func (suite *OauthTestSuite) SetupSuite() { - suite.testClientID = "test-client-id" - suite.testClientSecret = "test-client-secret" - suite.testClientDomain = "https://example.org" - suite.testClientUserID = "test-client-user-id" encryptedPassword, err := bcrypt.GenerateFromPassword([]byte("test-password"), bcrypt.DefaultCost) if err != nil { logrus.Panicf("error encrypting user pass: %s", err) } + + userID := uuid.NewString() suite.testUser = >smodel.User{ + ID: userID, EncryptedPassword: string(encryptedPassword), - Email: "user@example.org", + Email: "user@localhost", CreatedAt: time.Now(), UpdatedAt: time.Now(), - AccountID: "whatever", + AccountID: "some-account-id-it-doesn't-matter-really", + } + suite.testClient = &oauthClient{ + ID: "a-known-client-id", + Secret: "some-secret", + Domain: "localhost", + UserID: userID, } } @@ -78,6 +81,10 @@ func (suite *OauthTestSuite) SetupTest() { logrus.Panicf("could not insert test user into db: %s", err) } + if _, err := suite.conn.Model(suite.testClient).Insert(); err != nil { + logrus.Panicf("could not insert test client into db: %s", err) + } + } // TearDownTest drops the oauth_clients table and closes the pg connection after each test @@ -107,7 +114,7 @@ func (suite *OauthTestSuite) TestAPIInitialize() { api.AddRoutes(r) go r.Start() time.Sleep(30 * time.Second) - // http://localhost:8080/oauth/authorize?client_id=whatever + // http://localhost:8080/oauth/authorize?client_id=a-known-client-id&redirect_uri=urn:ietf:wg:oauth:2.0:oob&response_type=code } func TestOauthTestSuite(t *testing.T) { diff --git a/internal/oauth/pgclientstore.go b/internal/oauth/pgclientstore.go index 22bb54f55..1df46fedb 100644 --- a/internal/oauth/pgclientstore.go +++ b/internal/oauth/pgclientstore.go @@ -20,6 +20,7 @@ package oauth import ( "context" + "fmt" "github.com/go-pg/pg/v10" "github.com/gotosocial/oauth2/v4" @@ -42,7 +43,7 @@ func (pcs *pgClientStore) GetByID(ctx context.Context, clientID string) (oauth2. ID: clientID, } if err := pcs.conn.WithContext(ctx).Model(poc).Where("id = ?", poc.ID).Select(); err != nil { - return nil, err + return nil, fmt.Errorf("error in clientstore getbyid searching for client %s: %s", clientID, err) } return models.New(poc.ID, poc.Secret, poc.Domain, poc.UserID), nil } @@ -55,7 +56,10 @@ func (pcs *pgClientStore) Set(ctx context.Context, id string, cli oauth2.ClientI UserID: cli.GetUserID(), } _, err := pcs.conn.WithContext(ctx).Model(poc).OnConflict("(id) DO UPDATE").Insert() - return err + if err != nil { + return fmt.Errorf("error in clientstore set: %s", err) + } + return nil } func (pcs *pgClientStore) Delete(ctx context.Context, id string) error { @@ -63,7 +67,10 @@ func (pcs *pgClientStore) Delete(ctx context.Context, id string) error { ID: id, } _, err := pcs.conn.WithContext(ctx).Model(poc).Where("id = ?", poc.ID).Delete() - return err + if err != nil { + return fmt.Errorf("error in clientstore delete: %s", err) + } + return nil } type oauthClient struct { diff --git a/internal/oauth/pgclientstore_test.go b/internal/oauth/pgclientstore_test.go index d6a76981f..eb011fe01 100644 --- a/internal/oauth/pgclientstore_test.go +++ b/internal/oauth/pgclientstore_test.go @@ -96,7 +96,6 @@ func (suite *PgClientStoreTestSuite) TestClientSetAndDelete() { deletedClient, err := cs.GetByID(context.Background(), suite.testClientID) suite.Assert().Nil(deletedClient) suite.Assert().NotNil(err) - suite.EqualValues("pg: no rows in result set", err.Error()) } func TestPgClientStoreTestSuite(t *testing.T) { diff --git a/internal/oauth/pgtokenstore.go b/internal/oauth/pgtokenstore.go index a927be862..0271afafb 100644 --- a/internal/oauth/pgtokenstore.go +++ b/internal/oauth/pgtokenstore.go @@ -21,6 +21,7 @@ package oauth import ( "context" "errors" + "fmt" "time" "github.com/go-pg/pg/v10" @@ -98,32 +99,44 @@ func (pts *pgTokenStore) Create(ctx context.Context, info oauth2.TokenInfo) erro return errors.New("info param was not a models.Token") } _, err := pts.conn.WithContext(ctx).Model(oauthTokenToPGToken(t)).Insert() - return err + if err != nil { + return fmt.Errorf("error in tokenstore create: %s", err) + } + return nil } // RemoveByCode deletes a token from the DB based on the Code field func (pts *pgTokenStore) RemoveByCode(ctx context.Context, code string) error { _, err := pts.conn.Model(&oauthToken{}).Where("code = ?", code).Delete() - return err + if err != nil { + return fmt.Errorf("error in tokenstore removebycode: %s", err) + } + return nil } // RemoveByAccess deletes a token from the DB based on the Access field func (pts *pgTokenStore) RemoveByAccess(ctx context.Context, access string) error { _, err := pts.conn.Model(&oauthToken{}).Where("access = ?", access).Delete() - return err + if err != nil { + return fmt.Errorf("error in tokenstore removebyaccess: %s", err) + } + return nil } // RemoveByRefresh deletes a token from the DB based on the Refresh field func (pts *pgTokenStore) RemoveByRefresh(ctx context.Context, refresh string) error { _, err := pts.conn.Model(&oauthToken{}).Where("refresh = ?", refresh).Delete() - return err + if err != nil { + return fmt.Errorf("error in tokenstore removebyrefresh: %s", err) + } + return nil } // GetByCode selects a token from the DB based on the Code field func (pts *pgTokenStore) GetByCode(ctx context.Context, code string) (oauth2.TokenInfo, error) { pgt := &oauthToken{} if err := pts.conn.Model(pgt).Where("code = ?", code).Select(); err != nil { - return nil, err + return nil, fmt.Errorf("error in tokenstore getbycode: %s", err) } return pgTokenToOauthToken(pgt), nil } @@ -132,7 +145,7 @@ func (pts *pgTokenStore) GetByCode(ctx context.Context, code string) (oauth2.Tok func (pts *pgTokenStore) GetByAccess(ctx context.Context, access string) (oauth2.TokenInfo, error) { pgt := &oauthToken{} if err := pts.conn.Model(pgt).Where("access = ?", access).Select(); err != nil { - return nil, err + return nil, fmt.Errorf("error in tokenstore getbyaccess: %s", err) } return pgTokenToOauthToken(pgt), nil } @@ -141,7 +154,7 @@ func (pts *pgTokenStore) GetByAccess(ctx context.Context, access string) (oauth2 func (pts *pgTokenStore) GetByRefresh(ctx context.Context, refresh string) (oauth2.TokenInfo, error) { pgt := &oauthToken{} if err := pts.conn.Model(pgt).Where("refresh = ?", refresh).Select(); err != nil { - return nil, err + return nil, fmt.Errorf("error in tokenstore getbyrefresh: %s", err) } return pgTokenToOauthToken(pgt), nil } @@ -165,15 +178,15 @@ type oauthToken struct { UserID string RedirectURI string Scope string - Code string `pg:",pk"` + Code string `pg:"default:'',pk"` CodeChallenge string CodeChallengeMethod string CodeCreateAt time.Time `pg:"type:timestamp"` CodeExpiresAt time.Time `pg:"type:timestamp"` - Access string `pg:",pk"` + Access string `pg:"default:'',pk"` AccessCreateAt time.Time `pg:"type:timestamp"` AccessExpiresAt time.Time `pg:"type:timestamp"` - Refresh string `pg:",pk"` + Refresh string `pg:"default:'',pk"` RefreshCreateAt time.Time `pg:"type:timestamp"` RefreshExpiresAt time.Time `pg:"type:timestamp"` } -- cgit v1.2.3 From b6087cc08d0228f2304bbc3c6b97b86aa8d3c3f1 Mon Sep 17 00:00:00 2001 From: tsmethurst Date: Wed, 17 Mar 2021 19:52:36 +0100 Subject: almost there --- internal/oauth/oauth.go | 77 +++++++++++++++++++++++++++++++++----------- internal/oauth/oauth_test.go | 6 ++-- 2 files changed, 61 insertions(+), 22 deletions(-) (limited to 'internal/oauth/oauth_test.go') diff --git a/internal/oauth/oauth.go b/internal/oauth/oauth.go index d1f3bcf54..97913549a 100644 --- a/internal/oauth/oauth.go +++ b/internal/oauth/oauth.go @@ -45,7 +45,7 @@ type API struct { } type login struct { - Username string `form:"username"` + Email string `form:"username"` Password string `form:"password"` } @@ -61,8 +61,27 @@ func New(ts oauth2.TokenStore, cs oauth2.ClientStore, conn *pg.DB, log *logrus.L manager := manage.NewDefaultManager() manager.MapTokenStorage(ts) manager.MapClientStorage(cs) + manager.SetAuthorizeCodeTokenCfg(manage.DefaultAuthorizeCodeTokenCfg) + sc := &server.Config{ + TokenType: "Bearer", + // Must follow the spec. + AllowGetAccessRequest: false, + // Support only the non-implicit flow. + AllowedResponseTypes: []oauth2.ResponseType{oauth2.Code}, + // Allow: + // - Authorization Code (for first & third parties) + // - Refreshing Tokens + // + // Deny: + // - Resource owner secrets (password grant) + // - Client secrets + AllowedGrantTypes: []oauth2.GrantType{ + oauth2.AuthorizationCode, + oauth2.Refreshing, + }, + } - srv := server.NewDefaultServer(manager) + srv := server.NewServer(sc, manager) srv.SetInternalErrorHandler(func(err error) *errors.Response { log.Errorf("internal oauth error: %s", err) return nil @@ -79,7 +98,6 @@ func New(ts oauth2.TokenStore, cs oauth2.ClientStore, conn *pg.DB, log *logrus.L log: log, } - api.server.SetPasswordAuthorizationHandler(api.PasswordAuthorizationHandler) api.server.SetUserAuthorizationHandler(api.UserAuthorizationHandler) api.server.SetClientInfoHandler(server.ClientFormHandler) return api @@ -88,8 +106,8 @@ func New(ts oauth2.TokenStore, cs oauth2.ClientStore, conn *pg.DB, log *logrus.L func (a *API) AddRoutes(s api.Server) error { s.AttachHandler(http.MethodGet, "/auth/sign_in", a.SignInGETHandler) s.AttachHandler(http.MethodPost, "/auth/sign_in", a.SignInPOSTHandler) - s.AttachHandler(methodAny, "/oauth/token", a.TokenHandler) - s.AttachHandler(http.MethodGet, "/oauth/authorize", a.AuthorizeHandler) + s.AttachHandler(http.MethodPost, "/oauth/token", a.TokenHandler) + s.AttachHandler(http.MethodGet, "/oauth/authorize", a.AuthorizeGETHandler) s.AttachHandler(methodAny, "/auth", a.AuthHandler) return nil } @@ -106,6 +124,7 @@ func incorrectPassword() (string, error) { // The idea is to present a sign in page to the user, where they can enter their username and password. // The form will then POST to the sign in page, which will be handled by SignInPOSTHandler func (a *API) SignInGETHandler(c *gin.Context) { + a.log.WithField("func", "SignInGETHandler").Trace("serving sign in html") c.Data(http.StatusOK, "text/html; charset=utf-8", []byte(signInHTML)) } @@ -113,17 +132,26 @@ func (a *API) SignInGETHandler(c *gin.Context) { // The idea is to present a sign in page to the user, where they can enter their username and password. // The handler will then redirect to the auth handler served at /auth func (a *API) SignInPOSTHandler(c *gin.Context) { + l := a.log.WithField("func", "SignInPOSTHandler") s := sessions.Default(c) form := &login{} - if err := c.ShouldBind(form); err != nil || form.Username == "" || form.Password == "" { + if err := c.ShouldBind(form); err != nil || form.Email == "" || form.Password == "" { c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) return } - s.Set("username", form.Username) + l.Tracef("parsed form: %+v", form) + + userid, err := a.ValidatePassword(form.Email, form.Password); + if err != nil { + c.String(http.StatusForbidden, err.Error()) + } + + s.Set("username", userid) if err := s.Save(); err != nil { c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) return } + l.Trace("redirecting to auth page") c.Redirect(http.StatusFound, "/auth") } @@ -131,6 +159,8 @@ func (a *API) SignInPOSTHandler(c *gin.Context) { // The idea here is to serve an oauth access token to a user, which can be used for authorizing against non-public APIs. // See https://docs.joinmastodon.org/methods/apps/oauth/#obtain-a-token func (a *API) TokenHandler(c *gin.Context) { + l := a.log.WithField("func", "TokenHandler") + l.Trace("entered token handler, will now go to server.HandleTokenRequest") if err := a.server.HandleTokenRequest(c.Writer, c.Request); err != nil { c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) } @@ -139,7 +169,8 @@ func (a *API) TokenHandler(c *gin.Context) { // AuthorizeHandler should be served as GET at https://example.org/oauth/authorize // The idea here is to present an oauth authorize page to the user, with a button // that they have to click to accept. See here: https://docs.joinmastodon.org/methods/apps/oauth/#authorize-a-user -func (a *API) AuthorizeHandler(c *gin.Context) { +func (a *API) AuthorizeGETHandler(c *gin.Context) { + l := a.log.WithField("func", "AuthorizeHandler") s := sessions.Default(c) form := &authorize{} @@ -147,6 +178,7 @@ func (a *API) AuthorizeHandler(c *gin.Context) { c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) return } + l.Tracef("parsed form: %+v", form) if form.ResponseType == "" || form.ClientID == "" || form.RedirectURI == "" { c.JSON(http.StatusBadRequest, gin.H{"error": "missing one of: response_type, client_id or redirect_uri"}) @@ -164,15 +196,18 @@ func (a *API) AuthorizeHandler(c *gin.Context) { v := s.Get("username") if username, ok := v.(string); !ok || username == "" { + l.Trace("username was empty, redirecting to sign in page") c.Redirect(http.StatusFound, "/auth/sign_in") return } + l.Trace("serving authorize html") c.Data(http.StatusOK, "text/html; charset=utf-8", []byte(authorizeHTML)) } // AuthHandler should be served at https://example.org/auth func (a *API) AuthHandler(c *gin.Context) { + l := a.log.WithField("func", "AuthHandler") s := sessions.Default(c) values := url.Values{} @@ -220,9 +255,10 @@ func (a *API) AuthHandler(c *gin.Context) { } c.Request.Form = values + l.Tracef("values on request set to %+v", c.Request.Form) if err := s.Save(); err != nil { - c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) return } @@ -239,42 +275,45 @@ func (a *API) AuthHandler(c *gin.Context) { // and a password. The goal is to authenticate the password against the one for that email // address stored in the database. If OK, we return the userid (a uuid) for that user, // so that it can be used in further Oauth flows to generate a token/retreieve an oauth client from the db. -func (a *API) PasswordAuthorizationHandler(email string, password string) (userid string, err error) { - a.log.Debugf("entering password authorization handler with email: %s and password: %s", email, password) - +func (a *API) ValidatePassword(email string, password string) (userid string, err error) { + l := a.log.WithField("func", "PasswordAuthorizationHandler") + l.Tracef("email %s password %s", email, password) // first we select the user from the database based on email address, bail if no user found for that email gtsUser := >smodel.User{} if err := a.conn.Model(gtsUser).Where("email = ?", email).Select(); err != nil { - a.log.Debugf("user %s was not retrievable from db during oauth authorization attempt: %s", email, err) + l.Debugf("user %s was not retrievable from db during oauth authorization attempt: %s", email, err) return incorrectPassword() } // make sure a password is actually set and bail if not if gtsUser.EncryptedPassword == "" { - a.log.Warnf("encrypted password for user %s was empty for some reason", gtsUser.Email) + l.Warnf("encrypted password for user %s was empty for some reason", gtsUser.Email) return incorrectPassword() } // compare the provided password with the encrypted one from the db, bail if they don't match if err := bcrypt.CompareHashAndPassword([]byte(gtsUser.EncryptedPassword), []byte(password)); err != nil { - a.log.Debugf("password hash didn't match for user %s during login attempt: %s", gtsUser.Email, err) + l.Debugf("password hash didn't match for user %s during login attempt: %s", gtsUser.Email, err) return incorrectPassword() } // If we've made it this far the email/password is correct so we need the oauth client-id of the user // This is, conveniently, the same as the user ID, so we can just return it. userid = gtsUser.ID + l.Tracef("returning (%s, %s)", userid, err) return } // UserAuthorizationHandler gets the user's email address from the form key 'username' // or redirects to the /auth/sign_in page, if this key is not present. -func (a *API) UserAuthorizationHandler(w http.ResponseWriter, r *http.Request) (string, error) { - - username := r.FormValue("username") +func (a *API) UserAuthorizationHandler(w http.ResponseWriter, r *http.Request) (username string, err error) { + l := a.log.WithField("func", "UserAuthorizationHandler") + username = r.FormValue("username") if username == "" { + l.Trace("username was empty, redirecting to sign in page") http.Redirect(w, r, "/auth/sign_in", http.StatusFound) return "", nil } - return username, nil + l.Tracef("returning (%s, %s)", username, err) + return username, err } diff --git a/internal/oauth/oauth_test.go b/internal/oauth/oauth_test.go index f786df396..404ea5c20 100644 --- a/internal/oauth/oauth_test.go +++ b/internal/oauth/oauth_test.go @@ -48,7 +48,7 @@ func (suite *OauthTestSuite) SetupSuite() { suite.testClient = &oauthClient{ ID: "a-known-client-id", Secret: "some-secret", - Domain: "localhost", + Domain: "http://localhost:8080", UserID: userID, } } @@ -107,14 +107,14 @@ func (suite *OauthTestSuite) TearDownTest() { func (suite *OauthTestSuite) TestAPIInitialize() { log := logrus.New() - log.SetLevel(logrus.DebugLevel) + log.SetLevel(logrus.TraceLevel) r := api.New(suite.config, log) api := New(suite.tokenStore, suite.clientStore, suite.conn, log) api.AddRoutes(r) go r.Start() time.Sleep(30 * time.Second) - // http://localhost:8080/oauth/authorize?client_id=a-known-client-id&redirect_uri=urn:ietf:wg:oauth:2.0:oob&response_type=code + // http://localhost:8080/oauth/authorize?client_id=a-known-client-id&redirect_uri=''&response_type=code } func TestOauthTestSuite(t *testing.T) { -- cgit v1.2.3 From 1b118841211da90381dd950cafa13ead78b7f589 Mon Sep 17 00:00:00 2001 From: tsmethurst Date: Thu, 18 Mar 2021 23:27:43 +0100 Subject: auth flow working for code --- .gitignore | 3 ++ cmd/gotosocial/main.go | 12 ++++- example/config.yaml | 7 +++ go.mod | 2 +- go.sum | 6 +++ internal/api/server.go | 8 ++++ internal/config/config.go | 53 ++++++++++++++------- internal/config/template.go | 25 ++++++++++ internal/oauth/html.go | 63 +------------------------ internal/oauth/oauth.go | 110 ++++++++++++++++++++++++++----------------- internal/oauth/oauth_test.go | 15 ++++-- pkg/mastotypes/oauth.go | 37 +++++++++++++++ web/template/authorize.tmpl | 33 +++++++++++++ web/template/sign-in.tmpl | 28 +++++++++++ 14 files changed, 274 insertions(+), 128 deletions(-) create mode 100644 internal/config/template.go create mode 100644 pkg/mastotypes/oauth.go create mode 100644 web/template/authorize.tmpl create mode 100644 web/template/sign-in.tmpl (limited to 'internal/oauth/oauth_test.go') diff --git a/.gitignore b/.gitignore index fe72fe018..6f9b97023 100644 --- a/.gitignore +++ b/.gitignore @@ -3,3 +3,6 @@ # exclude built documentation, since readthedocs will build it for us anyway /docs/_build + +# exclude coverage report +cp.out diff --git a/cmd/gotosocial/main.go b/cmd/gotosocial/main.go index 0b4110656..96798035e 100644 --- a/cmd/gotosocial/main.go +++ b/cmd/gotosocial/main.go @@ -95,6 +95,14 @@ func main() { Value: "postgres", EnvVars: []string{envNames.DbDatabase}, }, + + // TEMPLATE FLAGS + &cli.StringFlag{ + Name: flagNames.TemplateBaseDir, + Usage: "Basedir for html templating files for rendering pages and composing emails", + Value: "./web/template/", + EnvVars: []string{envNames.TemplateBaseDir}, + }, }, Commands: []*cli.Command{ { @@ -137,12 +145,12 @@ func main() { func runAction(c *cli.Context, a action.GTSAction) error { // create a new *config.Config based on the config path provided... - conf, err := config.New(c.String(config.GetFlagNames().ConfigPath)) + conf, err := config.FromFile(c.String(config.GetFlagNames().ConfigPath)) if err != nil { return fmt.Errorf("error creating config: %s", err) } // ... and the flags set on the *cli.Context by urfave - conf.ParseFlags(c) + conf.ParseCLIFlags(c) // create a logger with the log level, formatting, and output splitter already set log, err := log.New(conf.LogLevel) diff --git a/example/config.yaml b/example/config.yaml index e4d05c634..b65149d9a 100644 --- a/example/config.yaml +++ b/example/config.yaml @@ -60,3 +60,10 @@ db: # Examples: ["mydb","postgres","gotosocial"] # Default: "postgres" database: "postgres" + +# Config pertaining to templating of web pages/email notifications and the like +template: + # String. Directory from which gotosocial will attempt to load html templates (.tmpl files). + # Examples: ["/some/absolute/path/", "./relative/path/", "../../some/weird/path/"] + # Default: "./web/template/" + baseDir: "./web/template/" diff --git a/go.mod b/go.mod index 6f1ede9ed..473ff3ea8 100644 --- a/go.mod +++ b/go.mod @@ -11,7 +11,7 @@ require ( github.com/go-session/session v3.1.2+incompatible github.com/golang/mock v1.4.4 // indirect github.com/google/uuid v1.2.0 // indirect - github.com/gotosocial/oauth2/v4 v4.2.1-0.20210316171520-7b12112bbb88 + github.com/gotosocial/oauth2/v4 v4.2.1-0.20210318133800-45d321d259b3 github.com/onsi/ginkgo v1.15.0 // indirect github.com/onsi/gomega v1.10.5 // indirect github.com/sirupsen/logrus v1.8.0 diff --git a/go.sum b/go.sum index f482187af..0b12241f0 100644 --- a/go.sum +++ b/go.sum @@ -107,6 +107,12 @@ github.com/gorilla/websocket v1.4.2 h1:+/TMaTYc4QFitKJxsQ7Yye35DkWvkdLcvGKqM+x0U github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= github.com/gotosocial/oauth2/v4 v4.2.1-0.20210316171520-7b12112bbb88 h1:YJ//HmHOYJ4srm/LA6VPNjNisneMbY6TTM1xttV/ZQU= github.com/gotosocial/oauth2/v4 v4.2.1-0.20210316171520-7b12112bbb88/go.mod h1:zl5kwHf/atRUrY5yOyDnk49Us1Ygs0BzdW4jKAgoiP8= +github.com/gotosocial/oauth2/v4 v4.2.1-0.20210318132047-b7df44000ea6 h1:mWWMTK2Boy6FSCi45WB6GVCcXW3IoTVJKJiHmmdjywU= +github.com/gotosocial/oauth2/v4 v4.2.1-0.20210318132047-b7df44000ea6/go.mod h1:zl5kwHf/atRUrY5yOyDnk49Us1Ygs0BzdW4jKAgoiP8= +github.com/gotosocial/oauth2/v4 v4.2.1-0.20210318132554-68b81fe90e62 h1:duqoA9NSY+BFY2IVveXx5lSvIQliVvPsaNMdspkTJPc= +github.com/gotosocial/oauth2/v4 v4.2.1-0.20210318132554-68b81fe90e62/go.mod h1:zl5kwHf/atRUrY5yOyDnk49Us1Ygs0BzdW4jKAgoiP8= +github.com/gotosocial/oauth2/v4 v4.2.1-0.20210318133800-45d321d259b3 h1:CKRz5d7mRum+UMR88Ue33tCYcej14WjUsB59C02DDqY= +github.com/gotosocial/oauth2/v4 v4.2.1-0.20210318133800-45d321d259b3/go.mod h1:zl5kwHf/atRUrY5yOyDnk49Us1Ygs0BzdW4jKAgoiP8= github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= github.com/imkira/go-interpol v1.1.0 h1:KIiKr0VSG2CUW1hl1jpiyuzuJeKUUpC8iM1AIE7N1Vk= github.com/imkira/go-interpol v1.1.0/go.mod h1:z0h2/2T3XF8kyEPpRgJ3kmNv+C43p+I/CoI+jC3w2iA= diff --git a/internal/api/server.go b/internal/api/server.go index 321c932cd..8e22742bb 100644 --- a/internal/api/server.go +++ b/internal/api/server.go @@ -19,6 +19,10 @@ package api import ( + "fmt" + "os" + "path/filepath" + "github.com/gin-contrib/sessions" "github.com/gin-contrib/sessions/memstore" "github.com/gin-gonic/gin" @@ -71,6 +75,10 @@ func New(config *config.Config, logger *logrus.Logger) Server { engine := gin.New() store := memstore.NewStore([]byte("authentication-key"), []byte("encryption-keyencryption-key----")) engine.Use(sessions.Sessions("gotosocial-session", store)) + cwd, _ := os.Getwd() + tmPath := filepath.Join(cwd, fmt.Sprintf("%s*", config.TemplateConfig.BaseDir)) + logger.Debugf("loading templates from %s", tmPath) + engine.LoadHTMLGlob(tmPath) return &server{ APIGroup: engine.Group("/api").Group("/v1"), logger: logger, diff --git a/internal/config/config.go b/internal/config/config.go index 5832ed53f..8e2656e3f 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -27,25 +27,38 @@ import ( // Config pulls together all the configuration needed to run gotosocial type Config struct { - LogLevel string `yaml:"logLevel"` - ApplicationName string `yaml:"applicationName"` - DBConfig *DBConfig `yaml:"db"` + LogLevel string `yaml:"logLevel"` + ApplicationName string `yaml:"applicationName"` + DBConfig *DBConfig `yaml:"db"` + TemplateConfig *TemplateConfig `yaml:"template"` } -// New returns a new config, or an error if something goes amiss. -// The path parameter is optional, for loading a configuration json from the given path. -func New(path string) (*Config, error) { - config := &Config{ - DBConfig: &DBConfig{}, +// FromFile returns a new config from a file, or an error if something goes amiss. +func FromFile(path string) (*Config, error) { + c, err := loadFromFile(path) + if err != nil { + return nil, fmt.Errorf("error creating config: %s", err) } - if path != "" { - var err error - if config, err = loadFromFile(path); err != nil { - return nil, fmt.Errorf("error creating config: %s", err) - } + return c, nil +} + +// Default returns a new config with default values. +// Not yet implemented. +func Default() *Config { + // TODO: find a way of doing this without code repetition, because having to + // repeat all values here and elsewhere is annoying and gonna be prone to mistakes. + return &Config{ + DBConfig: &DBConfig{}, + TemplateConfig: &TemplateConfig{}, } +} - return config, nil +// Empty just returns an empty config +func Empty() *Config { + return &Config{ + DBConfig: &DBConfig{}, + TemplateConfig: &TemplateConfig{}, + } } // loadFromFile takes a path to a yaml file and attempts to load a Config object from it @@ -63,8 +76,8 @@ func loadFromFile(path string) (*Config, error) { return config, nil } -// ParseFlags sets flags on the config using the provided Flags object -func (c *Config) ParseFlags(f KeyedFlags) { +// ParseCLIFlags sets flags on the config using the provided Flags object +func (c *Config) ParseCLIFlags(f KeyedFlags) { fn := GetFlagNames() // For all of these flags, we only want to set them on the config if: @@ -108,6 +121,11 @@ func (c *Config) ParseFlags(f KeyedFlags) { if c.DBConfig.Database == "" || f.IsSet(fn.DbDatabase) { c.DBConfig.Database = f.String(fn.DbDatabase) } + + // template flags + if c.TemplateConfig.BaseDir == "" || f.IsSet(fn.TemplateBaseDir) { + c.TemplateConfig.BaseDir = f.String(fn.TemplateBaseDir) + } } // KeyedFlags is a wrapper for any type that can store keyed flags and give them back. @@ -130,6 +148,7 @@ type Flags struct { DbUser string DbPassword string DbDatabase string + TemplateBaseDir string } // GetFlagNames returns a struct containing the names of the various flags used for @@ -145,6 +164,7 @@ func GetFlagNames() Flags { DbUser: "db-user", DbPassword: "db-password", DbDatabase: "db-database", + TemplateBaseDir: "template-basedir", } } @@ -161,5 +181,6 @@ func GetEnvNames() Flags { DbUser: "GTS_DB_USER", DbPassword: "GTS_DB_PASSWORD", DbDatabase: "GTS_DB_DATABASE", + TemplateBaseDir: "GTS_TEMPLATE_BASEDIR", } } diff --git a/internal/config/template.go b/internal/config/template.go new file mode 100644 index 000000000..eba86f8e6 --- /dev/null +++ b/internal/config/template.go @@ -0,0 +1,25 @@ +/* + GoToSocial + Copyright (C) 2021 GoToSocial Authors admin@gotosocial.org + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . +*/ + +package config + +// TemplateConfig pertains to templating of web pages/email notifications and the like +type TemplateConfig struct { + // Directory from which gotosocial will attempt to load html templates (.tmpl files). + BaseDir string `yaml:"baseDir"` +} diff --git a/internal/oauth/html.go b/internal/oauth/html.go index 06089aedd..a3ae4318a 100644 --- a/internal/oauth/html.go +++ b/internal/oauth/html.go @@ -2,67 +2,8 @@ package oauth const ( signInHTML = ` - - - - - Login - - - - - - -
-

Login

-
-
- - -
-
- - -
- -
-
- - -` +` authorizeHTML = ` - - - - - Auth - - - - - - -
-
-
-

Authorize

-

The client would like to perform actions on your behalf.

-

- -

-
-
-
- -` +` ) diff --git a/internal/oauth/oauth.go b/internal/oauth/oauth.go index 97913549a..c6d596761 100644 --- a/internal/oauth/oauth.go +++ b/internal/oauth/oauth.go @@ -27,6 +27,7 @@ import ( "github.com/go-pg/pg/v10" "github.com/gotosocial/gotosocial/internal/api" "github.com/gotosocial/gotosocial/internal/gtsmodel" + "github.com/gotosocial/gotosocial/pkg/mastotypes" "github.com/gotosocial/oauth2/v4" "github.com/gotosocial/oauth2/v4/errors" "github.com/gotosocial/oauth2/v4/manage" @@ -45,16 +46,12 @@ type API struct { } type login struct { - Email string `form:"username"` + Email string `form:"username"` Password string `form:"password"` } -type authorize struct { - ForceLogin string `form:"force_login,omitempty"` - ResponseType string `form:"response_type"` - ClientID string `form:"client_id"` - RedirectURI string `form:"redirect_uri"` - Scope string `form:"scope,omitempty"` +type code struct { + Code string `form:"code"` } func New(ts oauth2.TokenStore, cs oauth2.ClientStore, conn *pg.DB, log *logrus.Logger) *API { @@ -79,6 +76,9 @@ func New(ts oauth2.TokenStore, cs oauth2.ClientStore, conn *pg.DB, log *logrus.L oauth2.AuthorizationCode, oauth2.Refreshing, }, + AllowedCodeChallengeMethods: []oauth2.CodeChallengeMethod{ + oauth2.CodeChallengePlain, + }, } srv := server.NewServer(sc, manager) @@ -106,9 +106,13 @@ func New(ts oauth2.TokenStore, cs oauth2.ClientStore, conn *pg.DB, log *logrus.L func (a *API) AddRoutes(s api.Server) error { s.AttachHandler(http.MethodGet, "/auth/sign_in", a.SignInGETHandler) s.AttachHandler(http.MethodPost, "/auth/sign_in", a.SignInPOSTHandler) + s.AttachHandler(http.MethodPost, "/oauth/token", a.TokenHandler) + s.AttachHandler(http.MethodGet, "/oauth/authorize", a.AuthorizeGETHandler) - s.AttachHandler(methodAny, "/auth", a.AuthHandler) + s.AttachHandler(http.MethodPost, "/oauth/authorize", a.AuthorizePOSTHandler) + + // s.AttachHandler(http.MethodGet, "/auth", a.AuthGETHandler) return nil } @@ -125,7 +129,7 @@ func incorrectPassword() (string, error) { // The form will then POST to the sign in page, which will be handled by SignInPOSTHandler func (a *API) SignInGETHandler(c *gin.Context) { a.log.WithField("func", "SignInGETHandler").Trace("serving sign in html") - c.Data(http.StatusOK, "text/html; charset=utf-8", []byte(signInHTML)) + c.HTML(http.StatusOK, "sign-in.tmpl", gin.H{}) } // SignInPOSTHandler should be served at https://example.org/auth/sign_in. @@ -135,15 +139,16 @@ func (a *API) SignInPOSTHandler(c *gin.Context) { l := a.log.WithField("func", "SignInPOSTHandler") s := sessions.Default(c) form := &login{} - if err := c.ShouldBind(form); err != nil || form.Email == "" || form.Password == "" { + if err := c.ShouldBind(form); err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) return } l.Tracef("parsed form: %+v", form) - userid, err := a.ValidatePassword(form.Email, form.Password); + userid, err := a.ValidatePassword(form.Email, form.Password) if err != nil { c.String(http.StatusForbidden, err.Error()) + return } s.Set("username", userid) @@ -151,11 +156,12 @@ func (a *API) SignInPOSTHandler(c *gin.Context) { c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) return } + l.Trace("redirecting to auth page") - c.Redirect(http.StatusFound, "/auth") + c.Redirect(http.StatusFound, "/oauth/authorize") } -// TokenHandler should be served at https://example.org/oauth/token +// TokenHandler should be served as a POST at https://example.org/oauth/token // The idea here is to serve an oauth access token to a user, which can be used for authorizing against non-public APIs. // See https://docs.joinmastodon.org/methods/apps/oauth/#obtain-a-token func (a *API) TokenHandler(c *gin.Context) { @@ -166,50 +172,61 @@ func (a *API) TokenHandler(c *gin.Context) { } } -// AuthorizeHandler should be served as GET at https://example.org/oauth/authorize +// AuthorizeGETHandler should be served as GET at https://example.org/oauth/authorize // The idea here is to present an oauth authorize page to the user, with a button // that they have to click to accept. See here: https://docs.joinmastodon.org/methods/apps/oauth/#authorize-a-user func (a *API) AuthorizeGETHandler(c *gin.Context) { - l := a.log.WithField("func", "AuthorizeHandler") + l := a.log.WithField("func", "AuthorizeGETHandler") s := sessions.Default(c) - form := &authorize{} - - if err := c.ShouldBind(form); err != nil { - c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) - return - } - l.Tracef("parsed form: %+v", form) - - if form.ResponseType == "" || form.ClientID == "" || form.RedirectURI == "" { - c.JSON(http.StatusBadRequest, gin.H{"error": "missing one of: response_type, client_id or redirect_uri"}) - return - } - - s.Set("force_login", form.ForceLogin) - s.Set("response_type", form.ResponseType) - s.Set("client_id", form.ClientID) - s.Set("redirect_uri", form.RedirectURI) - s.Set("scope", form.Scope) - if err := s.Save(); err != nil { - c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) - } v := s.Get("username") if username, ok := v.(string); !ok || username == "" { - l.Trace("username was empty, redirecting to sign in page") + l.Trace("username was empty, parsing form then redirecting to sign in page") + + form := &mastotypes.OAuthAuthorize{} + + if err := c.ShouldBind(form); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + return + } + l.Tracef("parsed form: %+v", form) + + if form.ResponseType == "" || form.ClientID == "" || form.RedirectURI == "" { + c.JSON(http.StatusBadRequest, gin.H{"error": "missing one of: response_type, client_id or redirect_uri"}) + return + } + + // save these values from the form so we can use them elsewhere in the session + s.Set("force_login", form.ForceLogin) + s.Set("response_type", form.ResponseType) + s.Set("client_id", form.ClientID) + s.Set("redirect_uri", form.RedirectURI) + s.Set("scope", form.Scope) + if err := s.Save(); err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + c.Redirect(http.StatusFound, "/auth/sign_in") return } l.Trace("serving authorize html") - c.Data(http.StatusOK, "text/html; charset=utf-8", []byte(authorizeHTML)) + c.HTML(http.StatusOK, "authorize.tmpl", gin.H{}) } -// AuthHandler should be served at https://example.org/auth -func (a *API) AuthHandler(c *gin.Context) { - l := a.log.WithField("func", "AuthHandler") +// AuthorizePOSTHandler should be served as POST at https://example.org/oauth/authorize +// The idea here is to present an oauth authorize page to the user, with a button +// that they have to click to accept. See here: https://docs.joinmastodon.org/methods/apps/oauth/#authorize-a-user +func (a *API) AuthorizePOSTHandler(c *gin.Context) { + l := a.log.WithField("func", "AuthorizePOSTHandler") s := sessions.Default(c) + v := s.Get("username") + if username, ok := v.(string); !ok || username == "" { + c.JSON(http.StatusUnauthorized, gin.H{"error": "you are not signed in"}) + } + values := url.Values{} if v, ok := s.Get("force_login").(string); !ok { @@ -277,7 +294,13 @@ func (a *API) AuthHandler(c *gin.Context) { // so that it can be used in further Oauth flows to generate a token/retreieve an oauth client from the db. func (a *API) ValidatePassword(email string, password string) (userid string, err error) { l := a.log.WithField("func", "PasswordAuthorizationHandler") - l.Tracef("email %s password %s", email, password) + + // make sure an email/password was provided and bail if not + if email == "" || password == "" { + l.Debug("email or password was not provided") + return incorrectPassword() + } + // first we select the user from the database based on email address, bail if no user found for that email gtsUser := >smodel.User{} if err := a.conn.Model(gtsUser).Where("email = ?", email).Select(); err != nil { @@ -297,8 +320,7 @@ func (a *API) ValidatePassword(email string, password string) (userid string, er return incorrectPassword() } - // If we've made it this far the email/password is correct so we need the oauth client-id of the user - // This is, conveniently, the same as the user ID, so we can just return it. + // If we've made it this far the email/password is correct, so we can just return the id of the user. userid = gtsUser.ID l.Tracef("returning (%s, %s)", userid, err) return diff --git a/internal/oauth/oauth_test.go b/internal/oauth/oauth_test.go index 404ea5c20..901f99b64 100644 --- a/internal/oauth/oauth_test.go +++ b/internal/oauth/oauth_test.go @@ -40,17 +40,24 @@ func (suite *OauthTestSuite) SetupSuite() { suite.testUser = >smodel.User{ ID: userID, EncryptedPassword: string(encryptedPassword), - Email: "user@localhost", + Email: "user@example.org", CreatedAt: time.Now(), UpdatedAt: time.Now(), - AccountID: "some-account-id-it-doesn't-matter-really", + AccountID: "some-account-id-it-doesn't-matter-really-since-this-user-doesn't-actually-have-an-account!", } suite.testClient = &oauthClient{ ID: "a-known-client-id", Secret: "some-secret", - Domain: "http://localhost:8080", + Domain: "https://example.org", UserID: userID, } + + // because go tests are run within the test package directory, we need to fiddle with the templateconfig + // basedir in a way that we wouldn't normally have to do when running the binary, in order to make + // the templates actually load + c := config.Empty() + c.TemplateConfig.BaseDir = "../../web/template/" + suite.config = c } // SetupTest creates a postgres connection and creates the oauth_clients table before each test @@ -114,7 +121,7 @@ func (suite *OauthTestSuite) TestAPIInitialize() { api.AddRoutes(r) go r.Start() time.Sleep(30 * time.Second) - // http://localhost:8080/oauth/authorize?client_id=a-known-client-id&redirect_uri=''&response_type=code + // http://localhost:8080/oauth/authorize?client_id=a-known-client-id&response_type=code&redirect_uri=https://example.org } func TestOauthTestSuite(t *testing.T) { diff --git a/pkg/mastotypes/oauth.go b/pkg/mastotypes/oauth.go new file mode 100644 index 000000000..1b45b38e0 --- /dev/null +++ b/pkg/mastotypes/oauth.go @@ -0,0 +1,37 @@ +/* + GoToSocial + Copyright (C) 2021 GoToSocial Authors admin@gotosocial.org + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . +*/ + +package mastotypes + +// OAuthAuthorize represents a request sent to https://example.org/oauth/authorize +// See here: https://docs.joinmastodon.org/methods/apps/oauth/ +type OAuthAuthorize struct { + // Forces the user to re-login, which is necessary for authorizing with multiple accounts from the same instance. + ForceLogin string `form:"force_login,omitempty"` + // Should be set equal to `code`. + ResponseType string `form:"response_type"` + // Client ID, obtained during app registration. + ClientID string `form:"client_id"` + // Set a URI to redirect the user to. + // If this parameter is set to urn:ietf:wg:oauth:2.0:oob then the authorization code will be shown instead. + // Must match one of the redirect URIs declared during app registration. + RedirectURI string `form:"redirect_uri"` + // List of requested OAuth scopes, separated by spaces (or by pluses, if using query parameters). + // Must be a subset of scopes declared during app registration. If not provided, defaults to read. + Scope string `form:"scope,omitempty"` +} diff --git a/web/template/authorize.tmpl b/web/template/authorize.tmpl new file mode 100644 index 000000000..0043e21ba --- /dev/null +++ b/web/template/authorize.tmpl @@ -0,0 +1,33 @@ + + + + + Auth + + + + + + +
+
+
+

Authorize

+

The client would like to perform actions on your behalf.

+

+ +

+
+
+
+ + diff --git a/web/template/sign-in.tmpl b/web/template/sign-in.tmpl new file mode 100644 index 000000000..b7aa7c702 --- /dev/null +++ b/web/template/sign-in.tmpl @@ -0,0 +1,28 @@ + + + + + Login + + + + + + +
+

Login

+
+
+ + +
+
+ + +
+ +
+
+ + + -- cgit v1.2.3 From b915f427beca99d82ddf0014b7d4c7e849106a81 Mon Sep 17 00:00:00 2001 From: tsmethurst Date: Sat, 20 Mar 2021 00:18:44 +0100 Subject: allow showing just code --- internal/oauth/oauth.go | 22 +++++++++++++++------- internal/oauth/oauth_test.go | 5 +++-- 2 files changed, 18 insertions(+), 9 deletions(-) (limited to 'internal/oauth/oauth_test.go') diff --git a/internal/oauth/oauth.go b/internal/oauth/oauth.go index c6d596761..0caf2e84b 100644 --- a/internal/oauth/oauth.go +++ b/internal/oauth/oauth.go @@ -36,8 +36,6 @@ import ( "golang.org/x/crypto/bcrypt" ) -const methodAny = "ANY" - type API struct { manager *manage.Manager server *server.Server @@ -107,7 +105,7 @@ func (a *API) AddRoutes(s api.Server) error { s.AttachHandler(http.MethodGet, "/auth/sign_in", a.SignInGETHandler) s.AttachHandler(http.MethodPost, "/auth/sign_in", a.SignInPOSTHandler) - s.AttachHandler(http.MethodPost, "/oauth/token", a.TokenHandler) + s.AttachHandler(http.MethodPost, "/oauth/token", a.TokenPOSTHandler) s.AttachHandler(http.MethodGet, "/oauth/authorize", a.AuthorizeGETHandler) s.AttachHandler(http.MethodPost, "/oauth/authorize", a.AuthorizePOSTHandler) @@ -161,10 +159,10 @@ func (a *API) SignInPOSTHandler(c *gin.Context) { c.Redirect(http.StatusFound, "/oauth/authorize") } -// TokenHandler should be served as a POST at https://example.org/oauth/token +// TokenPOSTHandler should be served as a POST at https://example.org/oauth/token // The idea here is to serve an oauth access token to a user, which can be used for authorizing against non-public APIs. // See https://docs.joinmastodon.org/methods/apps/oauth/#obtain-a-token -func (a *API) TokenHandler(c *gin.Context) { +func (a *API) TokenPOSTHandler(c *gin.Context) { l := a.log.WithField("func", "TokenHandler") l.Trace("entered token handler, will now go to server.HandleTokenRequest") if err := a.server.HandleTokenRequest(c.Writer, c.Request); err != nil { @@ -211,8 +209,14 @@ func (a *API) AuthorizeGETHandler(c *gin.Context) { return } - l.Trace("serving authorize html") - c.HTML(http.StatusOK, "authorize.tmpl", gin.H{}) + code := &code{} + if err := c.Bind(code); err != nil || code.Code == "" { + // no code yet, serve auth html and let the user confirm + l.Trace("serving authorize html") + c.HTML(http.StatusOK, "authorize.tmpl", gin.H{}) + return + } + c.String(http.StatusOK, code.Code) } // AuthorizePOSTHandler should be served as POST at https://example.org/oauth/authorize @@ -254,6 +258,10 @@ func (a *API) AuthorizePOSTHandler(c *gin.Context) { c.JSON(http.StatusBadRequest, gin.H{"error": "session missing redirect_uri"}) return } else { + // todo: explain this little hack + if v == "urn:ietf:wg:oauth:2.0:oob" { + v = "http://localhost:8080/oauth/authorize" + } values.Add("redirect_uri", v) } diff --git a/internal/oauth/oauth_test.go b/internal/oauth/oauth_test.go index 901f99b64..0c786456a 100644 --- a/internal/oauth/oauth_test.go +++ b/internal/oauth/oauth_test.go @@ -40,7 +40,7 @@ func (suite *OauthTestSuite) SetupSuite() { suite.testUser = >smodel.User{ ID: userID, EncryptedPassword: string(encryptedPassword), - Email: "user@example.org", + Email: "user@localhost", CreatedAt: time.Now(), UpdatedAt: time.Now(), AccountID: "some-account-id-it-doesn't-matter-really-since-this-user-doesn't-actually-have-an-account!", @@ -48,7 +48,7 @@ func (suite *OauthTestSuite) SetupSuite() { suite.testClient = &oauthClient{ ID: "a-known-client-id", Secret: "some-secret", - Domain: "https://example.org", + Domain: "http://localhost:8080", UserID: userID, } @@ -122,6 +122,7 @@ func (suite *OauthTestSuite) TestAPIInitialize() { go r.Start() time.Sleep(30 * time.Second) // http://localhost:8080/oauth/authorize?client_id=a-known-client-id&response_type=code&redirect_uri=https://example.org + // http://localhost:8080/oauth/authorize?client_id=a-known-client-id&response_type=code&redirect_uri=urn:ietf:wg:oauth:2.0:oob } func TestOauthTestSuite(t *testing.T) { -- cgit v1.2.3 From d0e6625d6e2a1aac1f68ea0808abb3b1b711a8e5 Mon Sep 17 00:00:00 2001 From: tsmethurst Date: Sat, 20 Mar 2021 19:06:28 +0100 Subject: tidying up --- internal/oauth/oauth.go | 40 +++++++++++++++++++++++++++------------- internal/oauth/oauth_test.go | 14 ++++++++------ web/template/authorize.tmpl | 11 +++++++++++ 3 files changed, 46 insertions(+), 19 deletions(-) (limited to 'internal/oauth/oauth_test.go') diff --git a/internal/oauth/oauth.go b/internal/oauth/oauth.go index 39fe2ddce..49e04a905 100644 --- a/internal/oauth/oauth.go +++ b/internal/oauth/oauth.go @@ -19,12 +19,14 @@ package oauth import ( + "fmt" "net/http" "net/url" "github.com/gin-contrib/sessions" "github.com/gin-gonic/gin" "github.com/go-pg/pg/v10" + "github.com/google/uuid" "github.com/gotosocial/gotosocial/internal/api" "github.com/gotosocial/gotosocial/internal/gtsmodel" "github.com/gotosocial/gotosocial/pkg/mastotypes" @@ -102,6 +104,8 @@ func New(ts oauth2.TokenStore, cs oauth2.ClientStore, conn *pg.DB, log *logrus.L } func (a *API) AddRoutes(s api.Server) error { + s.AttachHandler(http.MethodPost, "/api/v1/apps", a.AppsPOSTHandler) + s.AttachHandler(http.MethodGet, "/auth/sign_in", a.SignInGETHandler) s.AttachHandler(http.MethodPost, "/auth/sign_in", a.SignInPOSTHandler) @@ -110,7 +114,6 @@ func (a *API) AddRoutes(s api.Server) error { s.AttachHandler(http.MethodGet, "/oauth/authorize", a.AuthorizeGETHandler) s.AttachHandler(http.MethodPost, "/oauth/authorize", a.AuthorizePOSTHandler) - // s.AttachHandler(http.MethodGet, "/auth", a.AuthGETHandler) return nil } @@ -260,18 +263,21 @@ func (a *API) AuthorizeGETHandler(c *gin.Context) { l := a.log.WithField("func", "AuthorizeGETHandler") s := sessions.Default(c) + // Username will be set in the session by AuthorizePOSTHandler if the caller has already gone through the authentication flow + // If it's not set, then we don't know yet who the user is, so we need to redirect them to the sign in page. v := s.Get("username") if username, ok := v.(string); !ok || username == "" { l.Trace("username was empty, parsing form then redirecting to sign in page") + // first make sure they've filled out the authorize form with the required values form := &mastotypes.OAuthAuthorize{} - if err := c.ShouldBind(form); err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) return } l.Tracef("parsed form: %+v", form) + // these fields are *required* so check 'em if form.ResponseType == "" || form.ClientID == "" || form.RedirectURI == "" { c.JSON(http.StatusBadRequest, gin.H{"error": "missing one of: response_type, client_id or redirect_uri"}) return @@ -288,18 +294,26 @@ func (a *API) AuthorizeGETHandler(c *gin.Context) { return } + // send them to the sign in page so we can tell who they are c.Redirect(http.StatusFound, "/auth/sign_in") return } + // Check if we have a code already. If we do, it means the user used urn:ietf:wg:oauth:2.0:oob as their redirect URI + // and were sent here, which means they just want the code displayed so they can use it out of band. code := &code{} - if err := c.Bind(code); err != nil || code.Code == "" { - // no code yet, serve auth html and let the user confirm - l.Trace("serving authorize html") - c.HTML(http.StatusOK, "authorize.tmpl", gin.H{}) + if err := c.Bind(code); err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) return } - c.String(http.StatusOK, code.Code) + + // the authorize template will either: + // 1. Display the code to the user if they're already authorized and were redirected here because they selected urn:ietf:wg:oauth:2.0:oob. + // 2. Display a form where they can get some information about the app that's trying to authorize, and approve it, which will then go to AuthorizePOSTHandler + l.Trace("serving authorize html") + c.HTML(http.StatusOK, "authorize.tmpl", gin.H{ + "code": code.Code, + }) } // AuthorizePOSTHandler should be served as POST at https://example.org/oauth/authorize @@ -417,16 +431,16 @@ func (a *API) ValidatePassword(email string, password string) (userid string, er return } -// UserAuthorizationHandler gets the user's email address from the form key 'username' +// UserAuthorizationHandler gets the user's ID from the 'username' field of the request form, // or redirects to the /auth/sign_in page, if this key is not present. -func (a *API) UserAuthorizationHandler(w http.ResponseWriter, r *http.Request) (username string, err error) { +func (a *API) UserAuthorizationHandler(w http.ResponseWriter, r *http.Request) (userID string, err error) { l := a.log.WithField("func", "UserAuthorizationHandler") - username = r.FormValue("username") - if username == "" { + userID = r.FormValue("username") + if userID == "" { l.Trace("username was empty, redirecting to sign in page") http.Redirect(w, r, "/auth/sign_in", http.StatusFound) return "", nil } - l.Tracef("returning (%s, %s)", username, err) - return username, err + l.Tracef("returning (%s, %s)", userID, err) + return userID, err } diff --git a/internal/oauth/oauth_test.go b/internal/oauth/oauth_test.go index 0c786456a..2e5be121b 100644 --- a/internal/oauth/oauth_test.go +++ b/internal/oauth/oauth_test.go @@ -7,7 +7,6 @@ import ( "github.com/go-pg/pg/v10" "github.com/go-pg/pg/v10/orm" - "github.com/google/uuid" "github.com/gotosocial/gotosocial/internal/api" "github.com/gotosocial/gotosocial/internal/config" "github.com/gotosocial/gotosocial/internal/gtsmodel" @@ -22,6 +21,7 @@ type OauthTestSuite struct { tokenStore oauth2.TokenStore clientStore oauth2.ClientStore conn *pg.DB + testAccount *gtsmodel.Account testUser *gtsmodel.User testClient *oauthClient config *config.Config @@ -36,20 +36,18 @@ func (suite *OauthTestSuite) SetupSuite() { logrus.Panicf("error encrypting user pass: %s", err) } - userID := uuid.NewString() + suite.testAccount = >smodel.Account{ + + } suite.testUser = >smodel.User{ - ID: userID, EncryptedPassword: string(encryptedPassword), Email: "user@localhost", - CreatedAt: time.Now(), - UpdatedAt: time.Now(), AccountID: "some-account-id-it-doesn't-matter-really-since-this-user-doesn't-actually-have-an-account!", } suite.testClient = &oauthClient{ ID: "a-known-client-id", Secret: "some-secret", Domain: "http://localhost:8080", - UserID: userID, } // because go tests are run within the test package directory, we need to fiddle with the templateconfig @@ -71,6 +69,8 @@ func (suite *OauthTestSuite) SetupTest() { &oauthClient{}, &oauthToken{}, >smodel.User{}, + >smodel.Account{}, + >smodel.Application{}, } for _, m := range models { @@ -100,6 +100,8 @@ func (suite *OauthTestSuite) TearDownTest() { &oauthClient{}, &oauthToken{}, >smodel.User{}, + >smodel.Account{}, + >smodel.Application{}, } for _, m := range models { if err := suite.conn.Model(m).DropTable(&orm.DropTableOptions{}); err != nil { diff --git a/web/template/authorize.tmpl b/web/template/authorize.tmpl index 0043e21ba..2b3b3ab07 100644 --- a/web/template/authorize.tmpl +++ b/web/template/authorize.tmpl @@ -11,6 +11,7 @@ +{{if len .code | eq 0 }}
@@ -30,4 +31,14 @@
+{{else}} + +
+
+ {{.code}} +
+
+ +{{end}} + -- cgit v1.2.3 From 044c0df42813697a0923e6de87ac8e2243d6025c Mon Sep 17 00:00:00 2001 From: tsmethurst Date: Sat, 20 Mar 2021 19:08:17 +0100 Subject: go fmt --- internal/gtsmodel/account.go | 2 +- internal/gtsmodel/user.go | 10 +++++----- internal/oauth/oauth_test.go | 4 +--- 3 files changed, 7 insertions(+), 9 deletions(-) (limited to 'internal/oauth/oauth_test.go') diff --git a/internal/gtsmodel/account.go b/internal/gtsmodel/account.go index 7bc8118a3..67860146e 100644 --- a/internal/gtsmodel/account.go +++ b/internal/gtsmodel/account.go @@ -121,7 +121,7 @@ type Account struct { // When was this account suspended (eg., don't allow it to log in/post, don't accept media/posts from this account) SuspendedAt time.Time `pg:"type:timestamp"` // How much do we trust this account 🤔 - TrustLevel int + TrustLevel int // Should we hide this account's collections? HideCollections bool // id of the user that suspended this account through an admin action diff --git a/internal/gtsmodel/user.go b/internal/gtsmodel/user.go index c105899b8..551cbe2a4 100644 --- a/internal/gtsmodel/user.go +++ b/internal/gtsmodel/user.go @@ -112,9 +112,9 @@ type User struct { EncryptedOTPSecretSalt string OTPRequiredForLogin bool OTPBackupCodes []string - ConsumedTimestamp int - RememberToken string - SignInToken string - SignInTokenSentAt time.Time `pg:"type:timestamp"` - WebauthnID string + ConsumedTimestamp int + RememberToken string + SignInToken string + SignInTokenSentAt time.Time `pg:"type:timestamp"` + WebauthnID string } diff --git a/internal/oauth/oauth_test.go b/internal/oauth/oauth_test.go index 2e5be121b..9ee5ac9a8 100644 --- a/internal/oauth/oauth_test.go +++ b/internal/oauth/oauth_test.go @@ -36,9 +36,7 @@ func (suite *OauthTestSuite) SetupSuite() { logrus.Panicf("error encrypting user pass: %s", err) } - suite.testAccount = >smodel.Account{ - - } + suite.testAccount = >smodel.Account{} suite.testUser = >smodel.User{ EncryptedPassword: string(encryptedPassword), Email: "user@localhost", -- cgit v1.2.3