diff options
Diffstat (limited to 'internal/apimodule')
39 files changed, 232 insertions, 187 deletions
diff --git a/internal/apimodule/account/account.go b/internal/apimodule/account/account.go index f4a47f6a2..a836afcdb 100644 --- a/internal/apimodule/account/account.go +++ b/internal/apimodule/account/account.go @@ -37,25 +37,31 @@ import ( ) const ( - idKey = "id" - basePath = "/api/v1/accounts" - basePathWithID = basePath + "/:" + idKey - verifyPath = basePath + "/verify_credentials" - updateCredentialsPath = basePath + "/update_credentials" + // IDKey is the key to use for retrieving account ID in requests + IDKey = "id" + // BasePath is the base API path for this module + BasePath = "/api/v1/accounts" + // BasePathWithID is the base path for this module with the ID key + BasePathWithID = BasePath + "/:" + IDKey + // VerifyPath is for verifying account credentials + VerifyPath = BasePath + "/verify_credentials" + // UpdateCredentialsPath is for updating account credentials + UpdateCredentialsPath = BasePath + "/update_credentials" ) -type accountModule struct { +// Module implements the ClientAPIModule interface for account-related actions +type Module struct { config *config.Config db db.DB oauthServer oauth.Server - mediaHandler media.MediaHandler + mediaHandler media.Handler mastoConverter mastotypes.Converter log *logrus.Logger } // New returns a new account module -func New(config *config.Config, db db.DB, oauthServer oauth.Server, mediaHandler media.MediaHandler, mastoConverter mastotypes.Converter, log *logrus.Logger) apimodule.ClientAPIModule { - return &accountModule{ +func New(config *config.Config, db db.DB, oauthServer oauth.Server, mediaHandler media.Handler, mastoConverter mastotypes.Converter, log *logrus.Logger) apimodule.ClientAPIModule { + return &Module{ config: config, db: db, oauthServer: oauthServer, @@ -66,14 +72,15 @@ func New(config *config.Config, db db.DB, oauthServer oauth.Server, mediaHandler } // Route attaches all routes from this module to the given router -func (m *accountModule) Route(r router.Router) error { - r.AttachHandler(http.MethodPost, basePath, m.accountCreatePOSTHandler) - r.AttachHandler(http.MethodGet, basePathWithID, m.muxHandler) - r.AttachHandler(http.MethodPatch, basePathWithID, m.muxHandler) +func (m *Module) Route(r router.Router) error { + r.AttachHandler(http.MethodPost, BasePath, m.AccountCreatePOSTHandler) + r.AttachHandler(http.MethodGet, BasePathWithID, m.muxHandler) + r.AttachHandler(http.MethodPatch, BasePathWithID, m.muxHandler) return nil } -func (m *accountModule) CreateTables(db db.DB) error { +// CreateTables creates the required tables for this module in the given database +func (m *Module) CreateTables(db db.DB) error { models := []interface{}{ >smodel.User{}, >smodel.Account{}, @@ -93,18 +100,18 @@ func (m *accountModule) CreateTables(db db.DB) error { return nil } -func (m *accountModule) muxHandler(c *gin.Context) { +func (m *Module) muxHandler(c *gin.Context) { ru := c.Request.RequestURI switch c.Request.Method { case http.MethodGet: - if strings.HasPrefix(ru, verifyPath) { - m.accountVerifyGETHandler(c) + if strings.HasPrefix(ru, VerifyPath) { + m.AccountVerifyGETHandler(c) } else { - m.accountGETHandler(c) + m.AccountGETHandler(c) } case http.MethodPatch: - if strings.HasPrefix(ru, updateCredentialsPath) { - m.accountUpdateCredentialsPATCHHandler(c) + if strings.HasPrefix(ru, UpdateCredentialsPath) { + m.AccountUpdateCredentialsPATCHHandler(c) } } } diff --git a/internal/apimodule/account/accountcreate.go b/internal/apimodule/account/accountcreate.go index 266d820af..fb21925b8 100644 --- a/internal/apimodule/account/accountcreate.go +++ b/internal/apimodule/account/accountcreate.go @@ -34,10 +34,10 @@ import ( "github.com/superseriousbusiness/oauth2/v4" ) -// accountCreatePOSTHandler handles create account requests, validates them, +// AccountCreatePOSTHandler handles create account requests, validates them, // and puts them in the database if they're valid. // It should be served as a POST at /api/v1/accounts -func (m *accountModule) accountCreatePOSTHandler(c *gin.Context) { +func (m *Module) AccountCreatePOSTHandler(c *gin.Context) { l := m.log.WithField("func", "accountCreatePOSTHandler") authed, err := oauth.MustAuth(c, true, true, false, false) if err != nil { @@ -83,7 +83,7 @@ func (m *accountModule) accountCreatePOSTHandler(c *gin.Context) { // accountCreate does the dirty work of making an account and user in the database. // It then returns a token to the caller, for use with the new account, as per the // spec here: https://docs.joinmastodon.org/methods/accounts/ -func (m *accountModule) accountCreate(form *mastotypes.AccountCreateRequest, signUpIP net.IP, token oauth2.TokenInfo, app *gtsmodel.Application) (*mastotypes.Token, error) { +func (m *Module) accountCreate(form *mastotypes.AccountCreateRequest, signUpIP net.IP, token oauth2.TokenInfo, app *gtsmodel.Application) (*mastotypes.Token, error) { l := m.log.WithField("func", "accountCreate") // don't store a reason if we don't require one diff --git a/internal/apimodule/account/accountget.go b/internal/apimodule/account/accountget.go index cd4aed22e..5003be139 100644 --- a/internal/apimodule/account/accountget.go +++ b/internal/apimodule/account/accountget.go @@ -26,12 +26,12 @@ import ( "github.com/superseriousbusiness/gotosocial/internal/db/gtsmodel" ) -// accountGetHandler serves the account information held by the server in response to a GET +// AccountGETHandler serves the account information held by the server in response to a GET // request. It should be served as a GET at /api/v1/accounts/:id. // // See: https://docs.joinmastodon.org/methods/accounts/ -func (m *accountModule) accountGETHandler(c *gin.Context) { - targetAcctID := c.Param(idKey) +func (m *Module) AccountGETHandler(c *gin.Context) { + targetAcctID := c.Param(IDKey) if targetAcctID == "" { c.JSON(http.StatusBadRequest, gin.H{"error": "no account id specified"}) return diff --git a/internal/apimodule/account/accountupdate.go b/internal/apimodule/account/accountupdate.go index 15e9cf0d1..7709697bf 100644 --- a/internal/apimodule/account/accountupdate.go +++ b/internal/apimodule/account/accountupdate.go @@ -34,7 +34,7 @@ import ( "github.com/superseriousbusiness/gotosocial/internal/util" ) -// accountUpdateCredentialsPATCHHandler allows a user to modify their account/profile settings. +// AccountUpdateCredentialsPATCHHandler allows a user to modify their account/profile settings. // It should be served as a PATCH at /api/v1/accounts/update_credentials // // TODO: this can be optimized massively by building up a picture of what we want the new account @@ -42,7 +42,7 @@ import ( // which is not gonna make the database very happy when lots of requests are going through. // This way it would also be safer because the update won't happen until *all* the fields are validated. // Otherwise we risk doing a partial update and that's gonna cause probllleeemmmsss. -func (m *accountModule) accountUpdateCredentialsPATCHHandler(c *gin.Context) { +func (m *Module) AccountUpdateCredentialsPATCHHandler(c *gin.Context) { l := m.log.WithField("func", "accountUpdateCredentialsPATCHHandler") authed, err := oauth.MustAuth(c, true, false, false, true) if err != nil { @@ -196,7 +196,7 @@ func (m *accountModule) accountUpdateCredentialsPATCHHandler(c *gin.Context) { // UpdateAccountAvatar does the dirty work of checking the avatar part of an account update form, // parsing and checking the image, and doing the necessary updates in the database for this to become // the account's new avatar image. -func (m *accountModule) UpdateAccountAvatar(avatar *multipart.FileHeader, accountID string) (*gtsmodel.MediaAttachment, error) { +func (m *Module) UpdateAccountAvatar(avatar *multipart.FileHeader, accountID string) (*gtsmodel.MediaAttachment, error) { var err error if int(avatar.Size) > m.config.MediaConfig.MaxImageSize { err = fmt.Errorf("avatar with size %d exceeded max image size of %d bytes", avatar.Size, m.config.MediaConfig.MaxImageSize) @@ -229,7 +229,7 @@ func (m *accountModule) UpdateAccountAvatar(avatar *multipart.FileHeader, accoun // UpdateAccountHeader does the dirty work of checking the header part of an account update form, // parsing and checking the image, and doing the necessary updates in the database for this to become // the account's new header image. -func (m *accountModule) UpdateAccountHeader(header *multipart.FileHeader, accountID string) (*gtsmodel.MediaAttachment, error) { +func (m *Module) UpdateAccountHeader(header *multipart.FileHeader, accountID string) (*gtsmodel.MediaAttachment, error) { var err error if int(header.Size) > m.config.MediaConfig.MaxImageSize { err = fmt.Errorf("header with size %d exceeded max image size of %d bytes", header.Size, m.config.MediaConfig.MaxImageSize) diff --git a/internal/apimodule/account/accountverify.go b/internal/apimodule/account/accountverify.go index 584ab6122..9edf1e73a 100644 --- a/internal/apimodule/account/accountverify.go +++ b/internal/apimodule/account/accountverify.go @@ -25,10 +25,10 @@ import ( "github.com/superseriousbusiness/gotosocial/internal/oauth" ) -// accountVerifyGETHandler serves a user's account details to them IF they reached this +// AccountVerifyGETHandler serves a user's account details to them IF they reached this // handler while in possession of a valid token, according to the oauth middleware. // It should be served as a GET at /api/v1/accounts/verify_credentials -func (m *accountModule) accountVerifyGETHandler(c *gin.Context) { +func (m *Module) AccountVerifyGETHandler(c *gin.Context) { l := m.log.WithField("func", "accountVerifyGETHandler") authed, err := oauth.MustAuth(c, true, false, false, true) if err != nil { diff --git a/internal/apimodule/account/accountcreate_test.go b/internal/apimodule/account/test/accountcreate_test.go index 8677e3573..81eab467a 100644 --- a/internal/apimodule/account/accountcreate_test.go +++ b/internal/apimodule/account/test/accountcreate_test.go @@ -39,6 +39,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/suite" + "github.com/superseriousbusiness/gotosocial/internal/apimodule/account" "github.com/superseriousbusiness/gotosocial/internal/config" "github.com/superseriousbusiness/gotosocial/internal/db" "github.com/superseriousbusiness/gotosocial/internal/db/gtsmodel" @@ -63,10 +64,10 @@ type AccountCreateTestSuite struct { testToken oauth2.TokenInfo mockOauthServer *oauth.MockServer mockStorage *storage.MockStorage - mediaHandler media.MediaHandler + mediaHandler media.Handler mastoConverter mastotypes.Converter db db.DB - accountModule *accountModule + accountModule *account.Module newUserFormHappyPath url.Values } @@ -164,7 +165,7 @@ func (suite *AccountCreateTestSuite) SetupSuite() { suite.mastoConverter = mastotypes.New(suite.config, suite.db) // and finally here's the thing we're actually testing! - suite.accountModule = New(suite.config, suite.db, suite.mockOauthServer, suite.mediaHandler, suite.mastoConverter, suite.log).(*accountModule) + suite.accountModule = account.New(suite.config, suite.db, suite.mockOauthServer, suite.mediaHandler, suite.mastoConverter, suite.log).(*account.Module) } func (suite *AccountCreateTestSuite) TearDownSuite() { @@ -250,9 +251,9 @@ func (suite *AccountCreateTestSuite) TestAccountCreatePOSTHandlerSuccessful() { ctx, _ := gin.CreateTestContext(recorder) ctx.Set(oauth.SessionAuthorizedApplication, suite.testApplication) ctx.Set(oauth.SessionAuthorizedToken, suite.testToken) - ctx.Request = httptest.NewRequest(http.MethodPost, fmt.Sprintf("http://localhost:8080/%s", basePath), nil) // the endpoint we're hitting + ctx.Request = httptest.NewRequest(http.MethodPost, fmt.Sprintf("http://localhost:8080/%s", account.BasePath), nil) // the endpoint we're hitting ctx.Request.Form = suite.newUserFormHappyPath - suite.accountModule.accountCreatePOSTHandler(ctx) + suite.accountModule.AccountCreatePOSTHandler(ctx) // check response @@ -324,9 +325,9 @@ func (suite *AccountCreateTestSuite) TestAccountCreatePOSTHandlerNoAuth() { // setup recorder := httptest.NewRecorder() ctx, _ := gin.CreateTestContext(recorder) - ctx.Request = httptest.NewRequest(http.MethodPost, fmt.Sprintf("http://localhost:8080/%s", basePath), nil) // the endpoint we're hitting + ctx.Request = httptest.NewRequest(http.MethodPost, fmt.Sprintf("http://localhost:8080/%s", account.BasePath), nil) // the endpoint we're hitting ctx.Request.Form = suite.newUserFormHappyPath - suite.accountModule.accountCreatePOSTHandler(ctx) + suite.accountModule.AccountCreatePOSTHandler(ctx) // check response @@ -349,8 +350,8 @@ func (suite *AccountCreateTestSuite) TestAccountCreatePOSTHandlerNoForm() { ctx, _ := gin.CreateTestContext(recorder) ctx.Set(oauth.SessionAuthorizedApplication, suite.testApplication) ctx.Set(oauth.SessionAuthorizedToken, suite.testToken) - ctx.Request = httptest.NewRequest(http.MethodPost, fmt.Sprintf("http://localhost:8080/%s", basePath), nil) // the endpoint we're hitting - suite.accountModule.accountCreatePOSTHandler(ctx) + ctx.Request = httptest.NewRequest(http.MethodPost, fmt.Sprintf("http://localhost:8080/%s", account.BasePath), nil) // the endpoint we're hitting + suite.accountModule.AccountCreatePOSTHandler(ctx) // check response suite.EqualValues(http.StatusBadRequest, recorder.Code) @@ -371,11 +372,11 @@ func (suite *AccountCreateTestSuite) TestAccountCreatePOSTHandlerWeakPassword() ctx, _ := gin.CreateTestContext(recorder) ctx.Set(oauth.SessionAuthorizedApplication, suite.testApplication) ctx.Set(oauth.SessionAuthorizedToken, suite.testToken) - ctx.Request = httptest.NewRequest(http.MethodPost, fmt.Sprintf("http://localhost:8080/%s", basePath), nil) // the endpoint we're hitting + ctx.Request = httptest.NewRequest(http.MethodPost, fmt.Sprintf("http://localhost:8080/%s", account.BasePath), nil) // the endpoint we're hitting ctx.Request.Form = suite.newUserFormHappyPath // set a weak password ctx.Request.Form.Set("password", "weak") - suite.accountModule.accountCreatePOSTHandler(ctx) + suite.accountModule.AccountCreatePOSTHandler(ctx) // check response suite.EqualValues(http.StatusBadRequest, recorder.Code) @@ -396,11 +397,11 @@ func (suite *AccountCreateTestSuite) TestAccountCreatePOSTHandlerWeirdLocale() { ctx, _ := gin.CreateTestContext(recorder) ctx.Set(oauth.SessionAuthorizedApplication, suite.testApplication) ctx.Set(oauth.SessionAuthorizedToken, suite.testToken) - ctx.Request = httptest.NewRequest(http.MethodPost, fmt.Sprintf("http://localhost:8080/%s", basePath), nil) // the endpoint we're hitting + ctx.Request = httptest.NewRequest(http.MethodPost, fmt.Sprintf("http://localhost:8080/%s", account.BasePath), nil) // the endpoint we're hitting ctx.Request.Form = suite.newUserFormHappyPath // set an invalid locale ctx.Request.Form.Set("locale", "neverneverland") - suite.accountModule.accountCreatePOSTHandler(ctx) + suite.accountModule.AccountCreatePOSTHandler(ctx) // check response suite.EqualValues(http.StatusBadRequest, recorder.Code) @@ -421,12 +422,12 @@ func (suite *AccountCreateTestSuite) TestAccountCreatePOSTHandlerRegistrationsCl ctx, _ := gin.CreateTestContext(recorder) ctx.Set(oauth.SessionAuthorizedApplication, suite.testApplication) ctx.Set(oauth.SessionAuthorizedToken, suite.testToken) - ctx.Request = httptest.NewRequest(http.MethodPost, fmt.Sprintf("http://localhost:8080/%s", basePath), nil) // the endpoint we're hitting + ctx.Request = httptest.NewRequest(http.MethodPost, fmt.Sprintf("http://localhost:8080/%s", account.BasePath), nil) // the endpoint we're hitting ctx.Request.Form = suite.newUserFormHappyPath // close registrations suite.config.AccountsConfig.OpenRegistration = false - suite.accountModule.accountCreatePOSTHandler(ctx) + suite.accountModule.AccountCreatePOSTHandler(ctx) // check response suite.EqualValues(http.StatusBadRequest, recorder.Code) @@ -447,13 +448,13 @@ func (suite *AccountCreateTestSuite) TestAccountCreatePOSTHandlerReasonNotProvid ctx, _ := gin.CreateTestContext(recorder) ctx.Set(oauth.SessionAuthorizedApplication, suite.testApplication) ctx.Set(oauth.SessionAuthorizedToken, suite.testToken) - ctx.Request = httptest.NewRequest(http.MethodPost, fmt.Sprintf("http://localhost:8080/%s", basePath), nil) // the endpoint we're hitting + ctx.Request = httptest.NewRequest(http.MethodPost, fmt.Sprintf("http://localhost:8080/%s", account.BasePath), nil) // the endpoint we're hitting ctx.Request.Form = suite.newUserFormHappyPath // remove reason ctx.Request.Form.Set("reason", "") - suite.accountModule.accountCreatePOSTHandler(ctx) + suite.accountModule.AccountCreatePOSTHandler(ctx) // check response suite.EqualValues(http.StatusBadRequest, recorder.Code) @@ -474,13 +475,13 @@ func (suite *AccountCreateTestSuite) TestAccountCreatePOSTHandlerInsufficientRea ctx, _ := gin.CreateTestContext(recorder) ctx.Set(oauth.SessionAuthorizedApplication, suite.testApplication) ctx.Set(oauth.SessionAuthorizedToken, suite.testToken) - ctx.Request = httptest.NewRequest(http.MethodPost, fmt.Sprintf("http://localhost:8080/%s", basePath), nil) // the endpoint we're hitting + ctx.Request = httptest.NewRequest(http.MethodPost, fmt.Sprintf("http://localhost:8080/%s", account.BasePath), nil) // the endpoint we're hitting ctx.Request.Form = suite.newUserFormHappyPath // remove reason ctx.Request.Form.Set("reason", "just cuz") - suite.accountModule.accountCreatePOSTHandler(ctx) + suite.accountModule.AccountCreatePOSTHandler(ctx) // check response suite.EqualValues(http.StatusBadRequest, recorder.Code) @@ -526,9 +527,9 @@ func (suite *AccountCreateTestSuite) TestAccountUpdateCredentialsPATCHHandler() ctx, _ := gin.CreateTestContext(recorder) ctx.Set(oauth.SessionAuthorizedAccount, suite.testAccountLocal) ctx.Set(oauth.SessionAuthorizedToken, suite.testToken) - ctx.Request = httptest.NewRequest(http.MethodPatch, fmt.Sprintf("http://localhost:8080/%s", updateCredentialsPath), body) // the endpoint we're hitting + ctx.Request = httptest.NewRequest(http.MethodPatch, fmt.Sprintf("http://localhost:8080/%s", account.UpdateCredentialsPath), body) // the endpoint we're hitting ctx.Request.Header.Set("Content-Type", writer.FormDataContentType()) - suite.accountModule.accountUpdateCredentialsPATCHHandler(ctx) + suite.accountModule.AccountUpdateCredentialsPATCHHandler(ctx) // check response diff --git a/internal/apimodule/account/accountupdate_test.go b/internal/apimodule/account/test/accountupdate_test.go index 7ca2190d8..1c6f528a1 100644 --- a/internal/apimodule/account/accountupdate_test.go +++ b/internal/apimodule/account/test/accountupdate_test.go @@ -37,6 +37,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/suite" + "github.com/superseriousbusiness/gotosocial/internal/apimodule/account" "github.com/superseriousbusiness/gotosocial/internal/config" "github.com/superseriousbusiness/gotosocial/internal/db" "github.com/superseriousbusiness/gotosocial/internal/db/gtsmodel" @@ -58,10 +59,10 @@ type AccountUpdateTestSuite struct { testToken oauth2.TokenInfo mockOauthServer *oauth.MockServer mockStorage *storage.MockStorage - mediaHandler media.MediaHandler + mediaHandler media.Handler mastoConverter mastotypes.Converter db db.DB - accountModule *accountModule + accountModule *account.Module newUserFormHappyPath url.Values } @@ -159,7 +160,7 @@ func (suite *AccountUpdateTestSuite) SetupSuite() { suite.mastoConverter = mastotypes.New(suite.config, suite.db) // and finally here's the thing we're actually testing! - suite.accountModule = New(suite.config, suite.db, suite.mockOauthServer, suite.mediaHandler, suite.mastoConverter, suite.log).(*accountModule) + suite.accountModule = account.New(suite.config, suite.db, suite.mockOauthServer, suite.mediaHandler, suite.mastoConverter, suite.log).(*account.Module) } func (suite *AccountUpdateTestSuite) TearDownSuite() { @@ -278,9 +279,9 @@ func (suite *AccountUpdateTestSuite) TestAccountUpdateCredentialsPATCHHandler() ctx, _ := gin.CreateTestContext(recorder) ctx.Set(oauth.SessionAuthorizedAccount, suite.testAccountLocal) ctx.Set(oauth.SessionAuthorizedToken, suite.testToken) - ctx.Request = httptest.NewRequest(http.MethodPatch, fmt.Sprintf("http://localhost:8080/%s", updateCredentialsPath), body) // the endpoint we're hitting + ctx.Request = httptest.NewRequest(http.MethodPatch, fmt.Sprintf("http://localhost:8080/%s", account.UpdateCredentialsPath), body) // the endpoint we're hitting ctx.Request.Header.Set("Content-Type", writer.FormDataContentType()) - suite.accountModule.accountUpdateCredentialsPATCHHandler(ctx) + suite.accountModule.AccountUpdateCredentialsPATCHHandler(ctx) // check response diff --git a/internal/apimodule/account/accountverify_test.go b/internal/apimodule/account/test/accountverify_test.go index 223a0c145..223a0c145 100644 --- a/internal/apimodule/account/accountverify_test.go +++ b/internal/apimodule/account/test/accountverify_test.go diff --git a/internal/apimodule/admin/admin.go b/internal/apimodule/admin/admin.go index 34a0aa2c8..2ebe9c7a7 100644 --- a/internal/apimodule/admin/admin.go +++ b/internal/apimodule/admin/admin.go @@ -33,21 +33,24 @@ import ( ) const ( - basePath = "/api/v1/admin" - emojiPath = basePath + "/custom_emojis" + // BasePath is the base API path for this module + BasePath = "/api/v1/admin" + // EmojiPath is used for posting/deleting custom emojis + EmojiPath = BasePath + "/custom_emojis" ) -type adminModule struct { +// Module implements the ClientAPIModule interface for admin-related actions (reports, emojis, etc) +type Module struct { config *config.Config db db.DB - mediaHandler media.MediaHandler + mediaHandler media.Handler mastoConverter mastotypes.Converter log *logrus.Logger } -// New returns a new account module -func New(config *config.Config, db db.DB, mediaHandler media.MediaHandler, mastoConverter mastotypes.Converter, log *logrus.Logger) apimodule.ClientAPIModule { - return &adminModule{ +// New returns a new admin module +func New(config *config.Config, db db.DB, mediaHandler media.Handler, mastoConverter mastotypes.Converter, log *logrus.Logger) apimodule.ClientAPIModule { + return &Module{ config: config, db: db, mediaHandler: mediaHandler, @@ -57,12 +60,13 @@ func New(config *config.Config, db db.DB, mediaHandler media.MediaHandler, masto } // Route attaches all routes from this module to the given router -func (m *adminModule) Route(r router.Router) error { - r.AttachHandler(http.MethodPost, emojiPath, m.emojiCreatePOSTHandler) +func (m *Module) Route(r router.Router) error { + r.AttachHandler(http.MethodPost, EmojiPath, m.emojiCreatePOSTHandler) return nil } -func (m *adminModule) CreateTables(db db.DB) error { +// CreateTables creates the necessary tables for this module in the given database +func (m *Module) CreateTables(db db.DB) error { models := []interface{}{ >smodel.User{}, >smodel.Account{}, diff --git a/internal/apimodule/admin/emojicreate.go b/internal/apimodule/admin/emojicreate.go index 91457c07c..49e5492dd 100644 --- a/internal/apimodule/admin/emojicreate.go +++ b/internal/apimodule/admin/emojicreate.go @@ -33,7 +33,7 @@ import ( "github.com/superseriousbusiness/gotosocial/internal/util" ) -func (m *adminModule) emojiCreatePOSTHandler(c *gin.Context) { +func (m *Module) emojiCreatePOSTHandler(c *gin.Context) { l := m.log.WithFields(logrus.Fields{ "func": "emojiCreatePOSTHandler", "request_uri": c.Request.RequestURI, diff --git a/internal/apimodule/app/app.go b/internal/apimodule/app/app.go index 08292acd1..518192758 100644 --- a/internal/apimodule/app/app.go +++ b/internal/apimodule/app/app.go @@ -31,9 +31,11 @@ import ( "github.com/superseriousbusiness/gotosocial/internal/router" ) -const appsPath = "/api/v1/apps" +// BasePath is the base path for this api module +const BasePath = "/api/v1/apps" -type appModule struct { +// Module implements the ClientAPIModule interface for requests relating to registering/removing applications +type Module struct { server oauth.Server db db.DB mastoConverter mastotypes.Converter @@ -42,7 +44,7 @@ type appModule struct { // New returns a new auth module func New(srv oauth.Server, db db.DB, mastoConverter mastotypes.Converter, log *logrus.Logger) apimodule.ClientAPIModule { - return &appModule{ + return &Module{ server: srv, db: db, mastoConverter: mastoConverter, @@ -51,12 +53,13 @@ func New(srv oauth.Server, db db.DB, mastoConverter mastotypes.Converter, log *l } // Route satisfies the RESTAPIModule interface -func (m *appModule) Route(s router.Router) error { - s.AttachHandler(http.MethodPost, appsPath, m.appsPOSTHandler) +func (m *Module) Route(s router.Router) error { + s.AttachHandler(http.MethodPost, BasePath, m.AppsPOSTHandler) return nil } -func (m *appModule) CreateTables(db db.DB) error { +// CreateTables creates the necessary tables for this module in the given database +func (m *Module) CreateTables(db db.DB) error { models := []interface{}{ &oauth.Client{}, &oauth.Token{}, diff --git a/internal/apimodule/app/appcreate.go b/internal/apimodule/app/appcreate.go index ec52a9d37..99b79d470 100644 --- a/internal/apimodule/app/appcreate.go +++ b/internal/apimodule/app/appcreate.go @@ -29,9 +29,9 @@ import ( "github.com/superseriousbusiness/gotosocial/internal/oauth" ) -// appsPOSTHandler should be served at https://example.org/api/v1/apps +// AppsPOSTHandler should be served at https://example.org/api/v1/apps // It is equivalent to: https://docs.joinmastodon.org/methods/apps/ -func (m *appModule) appsPOSTHandler(c *gin.Context) { +func (m *Module) AppsPOSTHandler(c *gin.Context) { l := m.log.WithField("func", "AppsPOSTHandler") l.Trace("entering AppsPOSTHandler") diff --git a/internal/apimodule/app/app_test.go b/internal/apimodule/app/test/app_test.go index d45b04e74..d45b04e74 100644 --- a/internal/apimodule/app/app_test.go +++ b/internal/apimodule/app/test/app_test.go diff --git a/internal/apimodule/auth/README.md b/internal/apimodule/auth/README.md deleted file mode 100644 index 96b2443c1..000000000 --- a/internal/apimodule/auth/README.md +++ /dev/null @@ -1,5 +0,0 @@ -# auth - -This package provides uses the [GoToSocial oauth2](https://github.com/gotosocial/oauth2) module (forked from [go-oauth2](https://github.com/go-oauth2/oauth2)) to provide [oauth2](https://www.oauth.com/) functionality to the GoToSocial client API. - -It also provides a handler/middleware for attaching to the Gin engine for validating authenticated users. diff --git a/internal/apimodule/auth/auth.go b/internal/apimodule/auth/auth.go index b70adeb43..341805b40 100644 --- a/internal/apimodule/auth/auth.go +++ b/internal/apimodule/auth/auth.go @@ -16,12 +16,6 @@ along with this program. If not, see <http://www.gnu.org/licenses/>. */ -// Package auth is a module that provides oauth functionality to a router. -// It adds the following paths: -// /auth/sign_in -// /oauth/token -// /oauth/authorize -// It also includes the oauthTokenMiddleware, which can be attached to a router to authenticate every request by Bearer token. package auth import ( @@ -37,12 +31,16 @@ import ( ) const ( - authSignInPath = "/auth/sign_in" - oauthTokenPath = "/oauth/token" - oauthAuthorizePath = "/oauth/authorize" + // AuthSignInPath is the API path for users to sign in through + AuthSignInPath = "/auth/sign_in" + // OauthTokenPath is the API path to use for granting token requests to users with valid credentials + OauthTokenPath = "/oauth/token" + // OauthAuthorizePath is the API path for authorization requests (eg., authorize this app to act on my behalf as a user) + OauthAuthorizePath = "/oauth/authorize" ) -type authModule struct { +// Module implements the ClientAPIModule interface for +type Module struct { server oauth.Server db db.DB log *logrus.Logger @@ -50,7 +48,7 @@ type authModule struct { // New returns a new auth module func New(srv oauth.Server, db db.DB, log *logrus.Logger) apimodule.ClientAPIModule { - return &authModule{ + return &Module{ server: srv, db: db, log: log, @@ -58,20 +56,21 @@ func New(srv oauth.Server, db db.DB, log *logrus.Logger) apimodule.ClientAPIModu } // Route satisfies the RESTAPIModule interface -func (m *authModule) Route(s router.Router) error { - s.AttachHandler(http.MethodGet, authSignInPath, m.signInGETHandler) - s.AttachHandler(http.MethodPost, authSignInPath, m.signInPOSTHandler) +func (m *Module) Route(s router.Router) error { + s.AttachHandler(http.MethodGet, AuthSignInPath, m.SignInGETHandler) + s.AttachHandler(http.MethodPost, AuthSignInPath, m.SignInPOSTHandler) - s.AttachHandler(http.MethodPost, oauthTokenPath, m.tokenPOSTHandler) + s.AttachHandler(http.MethodPost, OauthTokenPath, m.TokenPOSTHandler) - s.AttachHandler(http.MethodGet, oauthAuthorizePath, m.authorizeGETHandler) - s.AttachHandler(http.MethodPost, oauthAuthorizePath, m.authorizePOSTHandler) + s.AttachHandler(http.MethodGet, OauthAuthorizePath, m.AuthorizeGETHandler) + s.AttachHandler(http.MethodPost, OauthAuthorizePath, m.AuthorizePOSTHandler) - s.AttachMiddleware(m.oauthTokenMiddleware) + s.AttachMiddleware(m.OauthTokenMiddleware) return nil } -func (m *authModule) CreateTables(db db.DB) error { +// CreateTables creates the necessary tables for this module in the given database +func (m *Module) CreateTables(db db.DB) error { models := []interface{}{ &oauth.Client{}, &oauth.Token{}, diff --git a/internal/apimodule/auth/authorize.go b/internal/apimodule/auth/authorize.go index bf525e09e..4bc1991ac 100644 --- a/internal/apimodule/auth/authorize.go +++ b/internal/apimodule/auth/authorize.go @@ -31,10 +31,10 @@ import ( "github.com/superseriousbusiness/gotosocial/internal/mastotypes/mastomodel" ) -// authorizeGETHandler 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 (m *authModule) authorizeGETHandler(c *gin.Context) { +func (m *Module) AuthorizeGETHandler(c *gin.Context) { l := m.log.WithField("func", "AuthorizeGETHandler") s := sessions.Default(c) @@ -46,7 +46,7 @@ func (m *authModule) authorizeGETHandler(c *gin.Context) { if err := parseAuthForm(c, l); err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) } else { - c.Redirect(http.StatusFound, authSignInPath) + c.Redirect(http.StatusFound, AuthSignInPath) } return } @@ -108,11 +108,11 @@ func (m *authModule) authorizeGETHandler(c *gin.Context) { }) } -// authorizePOSTHandler should be served as POST at https://example.org/oauth/authorize +// AuthorizePOSTHandler should be served as POST at https://example.org/oauth/authorize // At this point we assume that the user has A) logged in and B) accepted that the app should act for them, // so we should proceed with the authentication flow and generate an oauth token for them if we can. // See here: https://docs.joinmastodon.org/methods/apps/oauth/#authorize-a-user -func (m *authModule) authorizePOSTHandler(c *gin.Context) { +func (m *Module) AuthorizePOSTHandler(c *gin.Context) { l := m.log.WithField("func", "AuthorizePOSTHandler") s := sessions.Default(c) diff --git a/internal/apimodule/auth/middleware.go b/internal/apimodule/auth/middleware.go index 4ca1f47a2..1d9a85993 100644 --- a/internal/apimodule/auth/middleware.go +++ b/internal/apimodule/auth/middleware.go @@ -24,12 +24,12 @@ import ( "github.com/superseriousbusiness/gotosocial/internal/oauth" ) -// oauthTokenMiddleware checks if the client has presented a valid oauth Bearer token. +// OauthTokenMiddleware checks if the client has presented a valid oauth Bearer token. // If so, it will check the User that the token belongs to, and set that in the context of // the request. Then, it will look up the account for that user, and set that in the request too. // If user or account can't be found, then the handler won't *fail*, in case the server wants to allow // public requests that don't have a Bearer token set (eg., for public instance information and so on). -func (m *authModule) oauthTokenMiddleware(c *gin.Context) { +func (m *Module) OauthTokenMiddleware(c *gin.Context) { l := m.log.WithField("func", "ValidatePassword") l.Trace("entering OauthTokenMiddleware") diff --git a/internal/apimodule/auth/signin.go b/internal/apimodule/auth/signin.go index a6994c90e..44de0891c 100644 --- a/internal/apimodule/auth/signin.go +++ b/internal/apimodule/auth/signin.go @@ -28,23 +28,24 @@ import ( "golang.org/x/crypto/bcrypt" ) +// login just wraps a form-submitted username (we want an email) and password type login struct { Email string `form:"username"` Password string `form:"password"` } -// signInGETHandler 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 (m *authModule) signInGETHandler(c *gin.Context) { +func (m *Module) SignInGETHandler(c *gin.Context) { m.log.WithField("func", "SignInGETHandler").Trace("serving sign in html") c.HTML(http.StatusOK, "sign-in.tmpl", gin.H{}) } -// signInPOSTHandler should be served at https://example.org/auth/sign_in. +// 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 (m *authModule) signInPOSTHandler(c *gin.Context) { +func (m *Module) SignInPOSTHandler(c *gin.Context) { l := m.log.WithField("func", "SignInPOSTHandler") s := sessions.Default(c) form := &login{} @@ -54,7 +55,7 @@ func (m *authModule) signInPOSTHandler(c *gin.Context) { } l.Tracef("parsed form: %+v", form) - userid, err := m.validatePassword(form.Email, form.Password) + userid, err := m.ValidatePassword(form.Email, form.Password) if err != nil { c.String(http.StatusForbidden, err.Error()) return @@ -67,14 +68,14 @@ func (m *authModule) signInPOSTHandler(c *gin.Context) { } l.Trace("redirecting to auth page") - c.Redirect(http.StatusFound, oauthAuthorizePath) + c.Redirect(http.StatusFound, OauthAuthorizePath) } -// validatePassword takes an email address and a password. +// ValidatePassword takes an email address 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 (m *authModule) validatePassword(email string, password string) (userid string, err error) { +func (m *Module) ValidatePassword(email string, password string) (userid string, err error) { l := m.log.WithField("func", "ValidatePassword") // make sure an email/password was provided and bail if not diff --git a/internal/apimodule/auth/auth_test.go b/internal/apimodule/auth/test/auth_test.go index 2c272e985..2c272e985 100644 --- a/internal/apimodule/auth/auth_test.go +++ b/internal/apimodule/auth/test/auth_test.go diff --git a/internal/apimodule/auth/token.go b/internal/apimodule/auth/token.go index 1e54b6ab3..c531a3009 100644 --- a/internal/apimodule/auth/token.go +++ b/internal/apimodule/auth/token.go @@ -24,10 +24,10 @@ import ( "github.com/gin-gonic/gin" ) -// tokenPOSTHandler 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 (m *authModule) tokenPOSTHandler(c *gin.Context) { +func (m *Module) TokenPOSTHandler(c *gin.Context) { l := m.log.WithField("func", "TokenPOSTHandler") l.Trace("entered TokenPOSTHandler") if err := m.server.HandleTokenRequest(c.Writer, c.Request); err != nil { diff --git a/internal/apimodule/fileserver/fileserver.go b/internal/apimodule/fileserver/fileserver.go index 25f3be864..7651c8cc1 100644 --- a/internal/apimodule/fileserver/fileserver.go +++ b/internal/apimodule/fileserver/fileserver.go @@ -32,12 +32,14 @@ import ( ) const ( + // AccountIDKey is the url key for account id (an account uuid) AccountIDKey = "account_id" + // MediaTypeKey is the url key for media type (usually something like attachment or header etc) MediaTypeKey = "media_type" + // MediaSizeKey is the url key for the desired media size--original/small/static MediaSizeKey = "media_size" + // FileNameKey is the actual filename being sought. Will usually be a UUID then something like .jpeg FileNameKey = "file_name" - - FilesPath = "files" ) // FileServer implements the RESTAPIModule interface. @@ -67,6 +69,7 @@ func (m *FileServer) Route(s router.Router) error { return nil } +// CreateTables populates necessary tables in the given DB func (m *FileServer) CreateTables(db db.DB) error { models := []interface{}{ >smodel.MediaAttachment{}, diff --git a/internal/apimodule/fileserver/test/servefile_test.go b/internal/apimodule/fileserver/test/servefile_test.go index 8af2b40b3..516e3528c 100644 --- a/internal/apimodule/fileserver/test/servefile_test.go +++ b/internal/apimodule/fileserver/test/servefile_test.go @@ -49,7 +49,7 @@ type ServeFileTestSuite struct { log *logrus.Logger storage storage.Storage mastoConverter mastotypes.Converter - mediaHandler media.MediaHandler + mediaHandler media.Handler oauthServer oauth.Server // standard suite models diff --git a/internal/apimodule/media/media.go b/internal/apimodule/media/media.go index c8d3d7425..8fb9f16ec 100644 --- a/internal/apimodule/media/media.go +++ b/internal/apimodule/media/media.go @@ -32,10 +32,12 @@ import ( "github.com/superseriousbusiness/gotosocial/internal/router" ) +// BasePath is the base API path for making media requests const BasePath = "/api/v1/media" -type MediaModule struct { - mediaHandler media.MediaHandler +// Module implements the ClientAPIModule interface for media +type Module struct { + mediaHandler media.Handler config *config.Config db db.DB mastoConverter mastotypes.Converter @@ -43,8 +45,8 @@ type MediaModule struct { } // New returns a new auth module -func New(db db.DB, mediaHandler media.MediaHandler, mastoConverter mastotypes.Converter, config *config.Config, log *logrus.Logger) apimodule.ClientAPIModule { - return &MediaModule{ +func New(db db.DB, mediaHandler media.Handler, mastoConverter mastotypes.Converter, config *config.Config, log *logrus.Logger) apimodule.ClientAPIModule { + return &Module{ mediaHandler: mediaHandler, config: config, db: db, @@ -54,12 +56,13 @@ func New(db db.DB, mediaHandler media.MediaHandler, mastoConverter mastotypes.Co } // Route satisfies the RESTAPIModule interface -func (m *MediaModule) Route(s router.Router) error { +func (m *Module) Route(s router.Router) error { s.AttachHandler(http.MethodPost, BasePath, m.MediaCreatePOSTHandler) return nil } -func (m *MediaModule) CreateTables(db db.DB) error { +// CreateTables populates necessary tables in the given DB +func (m *Module) CreateTables(db db.DB) error { models := []interface{}{ >smodel.MediaAttachment{}, } diff --git a/internal/apimodule/media/mediacreate.go b/internal/apimodule/media/mediacreate.go index 06b6d5be6..ee713a471 100644 --- a/internal/apimodule/media/mediacreate.go +++ b/internal/apimodule/media/mediacreate.go @@ -33,7 +33,8 @@ import ( "github.com/superseriousbusiness/gotosocial/internal/oauth" ) -func (m *MediaModule) MediaCreatePOSTHandler(c *gin.Context) { +// MediaCreatePOSTHandler handles requests to create/upload media attachments +func (m *Module) MediaCreatePOSTHandler(c *gin.Context) { l := m.log.WithField("func", "statusCreatePOSTHandler") authed, err := oauth.MustAuth(c, true, true, true, true) // posting new media is serious business so we want *everything* if err != nil { diff --git a/internal/apimodule/media/test/mediacreate_test.go b/internal/apimodule/media/test/mediacreate_test.go index 01a0a6a31..30bbb117a 100644 --- a/internal/apimodule/media/test/mediacreate_test.go +++ b/internal/apimodule/media/test/mediacreate_test.go @@ -52,7 +52,7 @@ type MediaCreateTestSuite struct { log *logrus.Logger storage storage.Storage mastoConverter mastotypes.Converter - mediaHandler media.MediaHandler + mediaHandler media.Handler oauthServer oauth.Server // standard suite models @@ -64,7 +64,7 @@ type MediaCreateTestSuite struct { testAttachments map[string]*gtsmodel.MediaAttachment // item being tested - mediaModule *mediamodule.MediaModule + mediaModule *mediamodule.Module } /* @@ -82,7 +82,7 @@ func (suite *MediaCreateTestSuite) SetupSuite() { suite.oauthServer = testrig.NewTestOauthServer(suite.db) // setup module being tested - suite.mediaModule = mediamodule.New(suite.db, suite.mediaHandler, suite.mastoConverter, suite.config, suite.log).(*mediamodule.MediaModule) + suite.mediaModule = mediamodule.New(suite.db, suite.mediaHandler, suite.mastoConverter, suite.config, suite.log).(*mediamodule.Module) } func (suite *MediaCreateTestSuite) TearDownSuite() { @@ -115,7 +115,7 @@ func (suite *MediaCreateTestSuite) TestStatusCreatePOSTImageHandlerSuccessful() // set up the context for the request t := suite.testTokens["local_account_1"] - oauthToken := oauth.PGTokenToOauthToken(t) + oauthToken := oauth.TokenToOauthToken(t) recorder := httptest.NewRecorder() ctx, _ := gin.CreateTestContext(recorder) ctx.Set(oauth.SessionAuthorizedApplication, suite.testApplications["application_1"]) diff --git a/internal/apimodule/security/flocblock.go b/internal/apimodule/security/flocblock.go index 4bb011d4d..7cedcde6b 100644 --- a/internal/apimodule/security/flocblock.go +++ b/internal/apimodule/security/flocblock.go @@ -20,8 +20,9 @@ package security import "github.com/gin-gonic/gin" -// flocBlock prevents google chrome cohort tracking by writing the Permissions-Policy header after all other parts of the request have been completed. +// FlocBlock is a middleware that prevents google chrome cohort tracking by +// writing the Permissions-Policy header after all other parts of the request have been completed. // See: https://plausible.io/blog/google-floc -func (m *module) flocBlock(c *gin.Context) { +func (m *Module) FlocBlock(c *gin.Context) { c.Header("Permissions-Policy", "interest-cohort=()") } diff --git a/internal/apimodule/security/security.go b/internal/apimodule/security/security.go index cfac2ce1e..8f805bc93 100644 --- a/internal/apimodule/security/security.go +++ b/internal/apimodule/security/security.go @@ -26,25 +26,27 @@ import ( "github.com/superseriousbusiness/gotosocial/internal/router" ) -// module implements the apiclient interface -type module struct { +// Module implements the ClientAPIModule interface for security middleware +type Module struct { config *config.Config log *logrus.Logger } // New returns a new security module func New(config *config.Config, log *logrus.Logger) apimodule.ClientAPIModule { - return &module{ + return &Module{ config: config, log: log, } } -func (m *module) Route(s router.Router) error { - s.AttachMiddleware(m.flocBlock) +// Route attaches security middleware to the given router +func (m *Module) Route(s router.Router) error { + s.AttachMiddleware(m.FlocBlock) return nil } -func (m *module) CreateTables(db db.DB) error { +// CreateTables doesn't do diddly squat at the moment, it's just for fulfilling the interface +func (m *Module) CreateTables(db db.DB) error { return nil } diff --git a/internal/apimodule/status/status.go b/internal/apimodule/status/status.go index e65293b62..73a1b5847 100644 --- a/internal/apimodule/status/status.go +++ b/internal/apimodule/status/status.go @@ -36,42 +36,60 @@ import ( ) const ( + // IDKey is for status UUIDs IDKey = "id" + // BasePath is the base path for serving the status API BasePath = "/api/v1/statuses" + // BasePathWithID is just the base path with the ID key in it. + // Use this anywhere you need to know the ID of the status being queried. BasePathWithID = BasePath + "/:" + IDKey + // ContextPath is used for fetching context of posts ContextPath = BasePathWithID + "/context" + // FavouritedPath is for seeing who's faved a given status FavouritedPath = BasePathWithID + "/favourited_by" + // FavouritePath is for posting a fave on a status FavouritePath = BasePathWithID + "/favourite" + // UnfavouritePath is for removing a fave from a status UnfavouritePath = BasePathWithID + "/unfavourite" + // RebloggedPath is for seeing who's boosted a given status RebloggedPath = BasePathWithID + "/reblogged_by" + // ReblogPath is for boosting/reblogging a given status ReblogPath = BasePathWithID + "/reblog" + // UnreblogPath is for undoing a boost/reblog of a given status UnreblogPath = BasePathWithID + "/unreblog" + // BookmarkPath is for creating a bookmark on a given status BookmarkPath = BasePathWithID + "/bookmark" + // UnbookmarkPath is for removing a bookmark from a given status UnbookmarkPath = BasePathWithID + "/unbookmark" + // MutePath is for muting a given status so that notifications will no longer be received about it. MutePath = BasePathWithID + "/mute" + // UnmutePath is for undoing an existing mute UnmutePath = BasePathWithID + "/unmute" + // PinPath is for pinning a status to an account profile so that it's the first thing people see PinPath = BasePathWithID + "/pin" + // UnpinPath is for undoing a pin and returning a status to the ever-swirling drain of time and entropy UnpinPath = BasePathWithID + "/unpin" ) -type StatusModule struct { +// Module implements the ClientAPIModule interface for every related to posting/deleting/interacting with statuses +type Module struct { config *config.Config db db.DB - mediaHandler media.MediaHandler + mediaHandler media.Handler mastoConverter mastotypes.Converter distributor distributor.Distributor log *logrus.Logger } // New returns a new account module -func New(config *config.Config, db db.DB, mediaHandler media.MediaHandler, mastoConverter mastotypes.Converter, distributor distributor.Distributor, log *logrus.Logger) apimodule.ClientAPIModule { - return &StatusModule{ +func New(config *config.Config, db db.DB, mediaHandler media.Handler, mastoConverter mastotypes.Converter, distributor distributor.Distributor, log *logrus.Logger) apimodule.ClientAPIModule { + return &Module{ config: config, db: db, mediaHandler: mediaHandler, @@ -82,7 +100,7 @@ func New(config *config.Config, db db.DB, mediaHandler media.MediaHandler, masto } // Route attaches all routes from this module to the given router -func (m *StatusModule) Route(r router.Router) error { +func (m *Module) Route(r router.Router) error { r.AttachHandler(http.MethodPost, BasePath, m.StatusCreatePOSTHandler) r.AttachHandler(http.MethodDelete, BasePathWithID, m.StatusDELETEHandler) @@ -93,7 +111,8 @@ func (m *StatusModule) Route(r router.Router) error { return nil } -func (m *StatusModule) CreateTables(db db.DB) error { +// CreateTables populates necessary tables in the given DB +func (m *Module) CreateTables(db db.DB) error { models := []interface{}{ >smodel.User{}, >smodel.Account{}, @@ -121,7 +140,8 @@ func (m *StatusModule) CreateTables(db db.DB) error { return nil } -func (m *StatusModule) muxHandler(c *gin.Context) { +// muxHandler is a little workaround to overcome the limitations of Gin +func (m *Module) muxHandler(c *gin.Context) { m.log.Debug("entering mux handler") ru := c.Request.RequestURI diff --git a/internal/apimodule/status/statuscreate.go b/internal/apimodule/status/statuscreate.go index ce1cc6da7..97354e767 100644 --- a/internal/apimodule/status/statuscreate.go +++ b/internal/apimodule/status/statuscreate.go @@ -53,7 +53,8 @@ type advancedVisibilityFlagsForm struct { Likeable *bool `form:"likeable"` } -func (m *StatusModule) StatusCreatePOSTHandler(c *gin.Context) { +// StatusCreatePOSTHandler deals with the creation of new statuses +func (m *Module) StatusCreatePOSTHandler(c *gin.Context) { l := m.log.WithField("func", "statusCreatePOSTHandler") authed, err := oauth.MustAuth(c, true, true, true, true) // posting a status is serious business so we want *everything* if err != nil { @@ -318,7 +319,7 @@ func parseVisibility(form *advancedStatusCreateForm, accountDefaultVis gtsmodel. return nil } -func (m *StatusModule) parseReplyToID(form *advancedStatusCreateForm, thisAccountID string, status *gtsmodel.Status) error { +func (m *Module) parseReplyToID(form *advancedStatusCreateForm, thisAccountID string, status *gtsmodel.Status) error { if form.InReplyToID == "" { return nil } @@ -336,9 +337,8 @@ func (m *StatusModule) parseReplyToID(form *advancedStatusCreateForm, thisAccoun if err := m.db.GetByID(form.InReplyToID, repliedStatus); err != nil { if _, ok := err.(db.ErrNoEntries); ok { return fmt.Errorf("status with id %s not replyable because it doesn't exist", form.InReplyToID) - } else { - return fmt.Errorf("status with id %s not replyable: %s", form.InReplyToID, err) } + return fmt.Errorf("status with id %s not replyable: %s", form.InReplyToID, err) } if !repliedStatus.VisibilityAdvanced.Replyable { @@ -349,9 +349,8 @@ func (m *StatusModule) parseReplyToID(form *advancedStatusCreateForm, thisAccoun if err := m.db.GetByID(repliedStatus.AccountID, repliedAccount); err != nil { if _, ok := err.(db.ErrNoEntries); ok { return fmt.Errorf("status with id %s not replyable because account id %s is not known", form.InReplyToID, repliedStatus.AccountID) - } else { - return fmt.Errorf("status with id %s not replyable: %s", form.InReplyToID, err) } + return fmt.Errorf("status with id %s not replyable: %s", form.InReplyToID, err) } // check if a block exists if blocked, err := m.db.Blocked(thisAccountID, repliedAccount.ID); err != nil { @@ -367,7 +366,7 @@ func (m *StatusModule) parseReplyToID(form *advancedStatusCreateForm, thisAccoun return nil } -func (m *StatusModule) parseMediaIDs(form *advancedStatusCreateForm, thisAccountID string, status *gtsmodel.Status) error { +func (m *Module) parseMediaIDs(form *advancedStatusCreateForm, thisAccountID string, status *gtsmodel.Status) error { if form.MediaIDs == nil { return nil } @@ -408,7 +407,7 @@ func parseLanguage(form *advancedStatusCreateForm, accountDefaultLanguage string return nil } -func (m *StatusModule) parseMentions(form *advancedStatusCreateForm, accountID string, status *gtsmodel.Status) error { +func (m *Module) parseMentions(form *advancedStatusCreateForm, accountID string, status *gtsmodel.Status) error { menchies := []string{} gtsMenchies, err := m.db.MentionStringsToMentions(util.DeriveMentions(form.Status), accountID, status.ID) if err != nil { @@ -427,7 +426,7 @@ func (m *StatusModule) parseMentions(form *advancedStatusCreateForm, accountID s return nil } -func (m *StatusModule) parseTags(form *advancedStatusCreateForm, accountID string, status *gtsmodel.Status) error { +func (m *Module) parseTags(form *advancedStatusCreateForm, accountID string, status *gtsmodel.Status) error { tags := []string{} gtsTags, err := m.db.TagStringsToTags(util.DeriveHashtags(form.Status), accountID, status.ID) if err != nil { @@ -446,7 +445,7 @@ func (m *StatusModule) parseTags(form *advancedStatusCreateForm, accountID strin return nil } -func (m *StatusModule) parseEmojis(form *advancedStatusCreateForm, accountID string, status *gtsmodel.Status) error { +func (m *Module) parseEmojis(form *advancedStatusCreateForm, accountID string, status *gtsmodel.Status) error { emojis := []string{} gtsEmojis, err := m.db.EmojiStringsToEmojis(util.DeriveEmojis(form.Status), accountID, status.ID) if err != nil { diff --git a/internal/apimodule/status/statusdelete.go b/internal/apimodule/status/statusdelete.go index f67d035d8..01dfe81df 100644 --- a/internal/apimodule/status/statusdelete.go +++ b/internal/apimodule/status/statusdelete.go @@ -29,7 +29,8 @@ import ( "github.com/superseriousbusiness/gotosocial/internal/oauth" ) -func (m *StatusModule) StatusDELETEHandler(c *gin.Context) { +// StatusDELETEHandler verifies and handles deletion of a status +func (m *Module) StatusDELETEHandler(c *gin.Context) { l := m.log.WithFields(logrus.Fields{ "func": "StatusDELETEHandler", "request_uri": c.Request.RequestURI, diff --git a/internal/apimodule/status/statusfave.go b/internal/apimodule/status/statusfave.go index de475b905..9ce68af09 100644 --- a/internal/apimodule/status/statusfave.go +++ b/internal/apimodule/status/statusfave.go @@ -29,7 +29,8 @@ import ( "github.com/superseriousbusiness/gotosocial/internal/oauth" ) -func (m *StatusModule) StatusFavePOSTHandler(c *gin.Context) { +// StatusFavePOSTHandler handles fave requests against a given status ID +func (m *Module) StatusFavePOSTHandler(c *gin.Context) { l := m.log.WithFields(logrus.Fields{ "func": "StatusFavePOSTHandler", "request_uri": c.Request.RequestURI, diff --git a/internal/apimodule/status/statusfavedby.go b/internal/apimodule/status/statusfavedby.go index 76a50b2ca..58236edc2 100644 --- a/internal/apimodule/status/statusfavedby.go +++ b/internal/apimodule/status/statusfavedby.go @@ -29,7 +29,8 @@ import ( "github.com/superseriousbusiness/gotosocial/internal/oauth" ) -func (m *StatusModule) StatusFavedByGETHandler(c *gin.Context) { +// StatusFavedByGETHandler is for serving a list of accounts that have faved a given status +func (m *Module) StatusFavedByGETHandler(c *gin.Context) { l := m.log.WithFields(logrus.Fields{ "func": "statusGETHandler", "request_uri": c.Request.RequestURI, diff --git a/internal/apimodule/status/statusget.go b/internal/apimodule/status/statusget.go index ed2e89159..76918c782 100644 --- a/internal/apimodule/status/statusget.go +++ b/internal/apimodule/status/statusget.go @@ -28,7 +28,8 @@ import ( "github.com/superseriousbusiness/gotosocial/internal/oauth" ) -func (m *StatusModule) StatusGETHandler(c *gin.Context) { +// StatusGETHandler is for handling requests to just get one status based on its ID +func (m *Module) StatusGETHandler(c *gin.Context) { l := m.log.WithFields(logrus.Fields{ "func": "statusGETHandler", "request_uri": c.Request.RequestURI, diff --git a/internal/apimodule/status/statusunfave.go b/internal/apimodule/status/statusunfave.go index 61ffd8e4c..9c06eaf92 100644 --- a/internal/apimodule/status/statusunfave.go +++ b/internal/apimodule/status/statusunfave.go @@ -29,7 +29,8 @@ import ( "github.com/superseriousbusiness/gotosocial/internal/oauth" ) -func (m *StatusModule) StatusUnfavePOSTHandler(c *gin.Context) { +// StatusUnfavePOSTHandler is for undoing a fave on a status with a given ID +func (m *Module) StatusUnfavePOSTHandler(c *gin.Context) { l := m.log.WithFields(logrus.Fields{ "func": "StatusUnfavePOSTHandler", "request_uri": c.Request.RequestURI, diff --git a/internal/apimodule/status/test/statuscreate_test.go b/internal/apimodule/status/test/statuscreate_test.go index 6c5aa6b7d..d143ac9a7 100644 --- a/internal/apimodule/status/test/statuscreate_test.go +++ b/internal/apimodule/status/test/statuscreate_test.go @@ -52,7 +52,7 @@ type StatusCreateTestSuite struct { log *logrus.Logger storage storage.Storage mastoConverter mastotypes.Converter - mediaHandler media.MediaHandler + mediaHandler media.Handler oauthServer oauth.Server distributor distributor.Distributor @@ -65,7 +65,7 @@ type StatusCreateTestSuite struct { testAttachments map[string]*gtsmodel.MediaAttachment // module being tested - statusModule *status.StatusModule + statusModule *status.Module } /* @@ -85,7 +85,7 @@ func (suite *StatusCreateTestSuite) SetupSuite() { suite.distributor = testrig.NewTestDistributor() // setup module being tested - suite.statusModule = status.New(suite.config, suite.db, suite.mediaHandler, suite.mastoConverter, suite.distributor, suite.log).(*status.StatusModule) + suite.statusModule = status.New(suite.config, suite.db, suite.mediaHandler, suite.mastoConverter, suite.distributor, suite.log).(*status.Module) } func (suite *StatusCreateTestSuite) TearDownSuite() { @@ -121,7 +121,7 @@ func (suite *StatusCreateTestSuite) TearDownTest() { func (suite *StatusCreateTestSuite) TestPostNewStatus() { t := suite.testTokens["local_account_1"] - oauthToken := oauth.PGTokenToOauthToken(t) + oauthToken := oauth.TokenToOauthToken(t) // setup recorder := httptest.NewRecorder() @@ -175,7 +175,7 @@ func (suite *StatusCreateTestSuite) TestPostNewStatus() { func (suite *StatusCreateTestSuite) TestPostNewStatusWithEmoji() { t := suite.testTokens["local_account_1"] - oauthToken := oauth.PGTokenToOauthToken(t) + oauthToken := oauth.TokenToOauthToken(t) // setup recorder := httptest.NewRecorder() @@ -216,7 +216,7 @@ func (suite *StatusCreateTestSuite) TestPostNewStatusWithEmoji() { // Try to reply to a status that doesn't exist func (suite *StatusCreateTestSuite) TestReplyToNonexistentStatus() { t := suite.testTokens["local_account_1"] - oauthToken := oauth.PGTokenToOauthToken(t) + oauthToken := oauth.TokenToOauthToken(t) // setup recorder := httptest.NewRecorder() @@ -247,7 +247,7 @@ func (suite *StatusCreateTestSuite) TestReplyToNonexistentStatus() { // Post a reply to the status of a local user that allows replies. func (suite *StatusCreateTestSuite) TestReplyToLocalStatus() { t := suite.testTokens["local_account_1"] - oauthToken := oauth.PGTokenToOauthToken(t) + oauthToken := oauth.TokenToOauthToken(t) // setup recorder := httptest.NewRecorder() @@ -287,7 +287,7 @@ func (suite *StatusCreateTestSuite) TestReplyToLocalStatus() { // Take a media file which is currently not associated with a status, and attach it to a new status. func (suite *StatusCreateTestSuite) TestAttachNewMediaSuccess() { t := suite.testTokens["local_account_1"] - oauthToken := oauth.PGTokenToOauthToken(t) + oauthToken := oauth.TokenToOauthToken(t) // setup recorder := httptest.NewRecorder() diff --git a/internal/apimodule/status/test/statusfave_test.go b/internal/apimodule/status/test/statusfave_test.go index b15e57e77..9ccf58948 100644 --- a/internal/apimodule/status/test/statusfave_test.go +++ b/internal/apimodule/status/test/statusfave_test.go @@ -52,7 +52,7 @@ type StatusFaveTestSuite struct { log *logrus.Logger storage storage.Storage mastoConverter mastotypes.Converter - mediaHandler media.MediaHandler + mediaHandler media.Handler oauthServer oauth.Server distributor distributor.Distributor @@ -66,7 +66,7 @@ type StatusFaveTestSuite struct { testStatuses map[string]*gtsmodel.Status // module being tested - statusModule *status.StatusModule + statusModule *status.Module } /* @@ -86,7 +86,7 @@ func (suite *StatusFaveTestSuite) SetupSuite() { suite.distributor = testrig.NewTestDistributor() // setup module being tested - suite.statusModule = status.New(suite.config, suite.db, suite.mediaHandler, suite.mastoConverter, suite.distributor, suite.log).(*status.StatusModule) + suite.statusModule = status.New(suite.config, suite.db, suite.mediaHandler, suite.mastoConverter, suite.distributor, suite.log).(*status.Module) } func (suite *StatusFaveTestSuite) TearDownSuite() { @@ -120,7 +120,7 @@ func (suite *StatusFaveTestSuite) TearDownTest() { func (suite *StatusFaveTestSuite) TestPostFave() { t := suite.testTokens["local_account_1"] - oauthToken := oauth.PGTokenToOauthToken(t) + oauthToken := oauth.TokenToOauthToken(t) targetStatus := suite.testStatuses["admin_account_status_2"] @@ -168,7 +168,7 @@ func (suite *StatusFaveTestSuite) TestPostFave() { func (suite *StatusFaveTestSuite) TestPostUnfaveable() { t := suite.testTokens["local_account_1"] - oauthToken := oauth.PGTokenToOauthToken(t) + oauthToken := oauth.TokenToOauthToken(t) targetStatus := suite.testStatuses["local_account_2_status_3"] // this one is unlikeable and unreplyable diff --git a/internal/apimodule/status/test/statusfavedby_test.go b/internal/apimodule/status/test/statusfavedby_test.go index 83f66562b..169543a81 100644 --- a/internal/apimodule/status/test/statusfavedby_test.go +++ b/internal/apimodule/status/test/statusfavedby_test.go @@ -52,7 +52,7 @@ type StatusFavedByTestSuite struct { log *logrus.Logger storage storage.Storage mastoConverter mastotypes.Converter - mediaHandler media.MediaHandler + mediaHandler media.Handler oauthServer oauth.Server distributor distributor.Distributor @@ -66,7 +66,7 @@ type StatusFavedByTestSuite struct { testStatuses map[string]*gtsmodel.Status // module being tested - statusModule *status.StatusModule + statusModule *status.Module } // SetupSuite sets some variables on the suite that we can use as consts (more or less) throughout @@ -82,7 +82,7 @@ func (suite *StatusFavedByTestSuite) SetupSuite() { suite.distributor = testrig.NewTestDistributor() // setup module being tested - suite.statusModule = status.New(suite.config, suite.db, suite.mediaHandler, suite.mastoConverter, suite.distributor, suite.log).(*status.StatusModule) + suite.statusModule = status.New(suite.config, suite.db, suite.mediaHandler, suite.mastoConverter, suite.distributor, suite.log).(*status.Module) } func (suite *StatusFavedByTestSuite) TearDownSuite() { @@ -114,7 +114,7 @@ func (suite *StatusFavedByTestSuite) TearDownTest() { func (suite *StatusFavedByTestSuite) TestGetFavedBy() { t := suite.testTokens["local_account_2"] - oauthToken := oauth.PGTokenToOauthToken(t) + oauthToken := oauth.TokenToOauthToken(t) targetStatus := suite.testStatuses["admin_account_status_1"] // this status is faved by local_account_1 diff --git a/internal/apimodule/status/test/statusget_test.go b/internal/apimodule/status/test/statusget_test.go index 2c2e98acd..ce817d247 100644 --- a/internal/apimodule/status/test/statusget_test.go +++ b/internal/apimodule/status/test/statusget_test.go @@ -43,7 +43,7 @@ type StatusGetTestSuite struct { log *logrus.Logger storage storage.Storage mastoConverter mastotypes.Converter - mediaHandler media.MediaHandler + mediaHandler media.Handler oauthServer oauth.Server distributor distributor.Distributor @@ -56,7 +56,7 @@ type StatusGetTestSuite struct { testAttachments map[string]*gtsmodel.MediaAttachment // module being tested - statusModule *status.StatusModule + statusModule *status.Module } /* @@ -76,7 +76,7 @@ func (suite *StatusGetTestSuite) SetupSuite() { suite.distributor = testrig.NewTestDistributor() // setup module being tested - suite.statusModule = status.New(suite.config, suite.db, suite.mediaHandler, suite.mastoConverter, suite.distributor, suite.log).(*status.StatusModule) + suite.statusModule = status.New(suite.config, suite.db, suite.mediaHandler, suite.mastoConverter, suite.distributor, suite.log).(*status.Module) } func (suite *StatusGetTestSuite) TearDownSuite() { diff --git a/internal/apimodule/status/test/statusunfave_test.go b/internal/apimodule/status/test/statusunfave_test.go index 81276a1ed..5f5277921 100644 --- a/internal/apimodule/status/test/statusunfave_test.go +++ b/internal/apimodule/status/test/statusunfave_test.go @@ -52,7 +52,7 @@ type StatusUnfaveTestSuite struct { log *logrus.Logger storage storage.Storage mastoConverter mastotypes.Converter - mediaHandler media.MediaHandler + mediaHandler media.Handler oauthServer oauth.Server distributor distributor.Distributor @@ -66,7 +66,7 @@ type StatusUnfaveTestSuite struct { testStatuses map[string]*gtsmodel.Status // module being tested - statusModule *status.StatusModule + statusModule *status.Module } /* @@ -86,7 +86,7 @@ func (suite *StatusUnfaveTestSuite) SetupSuite() { suite.distributor = testrig.NewTestDistributor() // setup module being tested - suite.statusModule = status.New(suite.config, suite.db, suite.mediaHandler, suite.mastoConverter, suite.distributor, suite.log).(*status.StatusModule) + suite.statusModule = status.New(suite.config, suite.db, suite.mediaHandler, suite.mastoConverter, suite.distributor, suite.log).(*status.Module) } func (suite *StatusUnfaveTestSuite) TearDownSuite() { @@ -120,7 +120,7 @@ func (suite *StatusUnfaveTestSuite) TearDownTest() { func (suite *StatusUnfaveTestSuite) TestPostUnfave() { t := suite.testTokens["local_account_1"] - oauthToken := oauth.PGTokenToOauthToken(t) + oauthToken := oauth.TokenToOauthToken(t) // this is the status we wanna unfave: in the testrig it's already faved by this account targetStatus := suite.testStatuses["admin_account_status_1"] @@ -169,7 +169,7 @@ func (suite *StatusUnfaveTestSuite) TestPostUnfave() { func (suite *StatusUnfaveTestSuite) TestPostAlreadyNotFaved() { t := suite.testTokens["local_account_1"] - oauthToken := oauth.PGTokenToOauthToken(t) + oauthToken := oauth.TokenToOauthToken(t) // this is the status we wanna unfave: in the testrig it's not faved by this account targetStatus := suite.testStatuses["admin_account_status_2"] |