diff --git a/api4/api.go b/api4/api.go index 24dd41a389..225e2b8c42 100644 --- a/api4/api.go +++ b/api4/api.go @@ -16,7 +16,7 @@ import ( type Routes struct { Root *mux.Router // '' - ApiRoot *mux.Router // 'api/v4' + APIRoot *mux.Router // 'api/v4' Users *mux.Router // 'api/v4/users' User *mux.Router // 'api/v4/users/{user_id:[A-Za-z0-9]+}' @@ -146,17 +146,17 @@ func Init(a app.AppIface, root *mux.Router) *API { } api.BaseRoutes.Root = root - api.BaseRoutes.ApiRoot = root.PathPrefix(model.ApiUrlSuffix).Subrouter() + api.BaseRoutes.APIRoot = root.PathPrefix(model.APIURLSuffix).Subrouter() - api.BaseRoutes.Users = api.BaseRoutes.ApiRoot.PathPrefix("/users").Subrouter() - api.BaseRoutes.User = api.BaseRoutes.ApiRoot.PathPrefix("/users/{user_id:[A-Za-z0-9]+}").Subrouter() + api.BaseRoutes.Users = api.BaseRoutes.APIRoot.PathPrefix("/users").Subrouter() + api.BaseRoutes.User = api.BaseRoutes.APIRoot.PathPrefix("/users/{user_id:[A-Za-z0-9]+}").Subrouter() api.BaseRoutes.UserByUsername = api.BaseRoutes.Users.PathPrefix("/username/{username:[A-Za-z0-9\\_\\-\\.]+}").Subrouter() api.BaseRoutes.UserByEmail = api.BaseRoutes.Users.PathPrefix("/email/{email:.+}").Subrouter() - api.BaseRoutes.Bots = api.BaseRoutes.ApiRoot.PathPrefix("/bots").Subrouter() - api.BaseRoutes.Bot = api.BaseRoutes.ApiRoot.PathPrefix("/bots/{bot_user_id:[A-Za-z0-9]+}").Subrouter() + api.BaseRoutes.Bots = api.BaseRoutes.APIRoot.PathPrefix("/bots").Subrouter() + api.BaseRoutes.Bot = api.BaseRoutes.APIRoot.PathPrefix("/bots/{bot_user_id:[A-Za-z0-9]+}").Subrouter() - api.BaseRoutes.Teams = api.BaseRoutes.ApiRoot.PathPrefix("/teams").Subrouter() + api.BaseRoutes.Teams = api.BaseRoutes.APIRoot.PathPrefix("/teams").Subrouter() api.BaseRoutes.TeamsForUser = api.BaseRoutes.User.PathPrefix("/teams").Subrouter() api.BaseRoutes.Team = api.BaseRoutes.Teams.PathPrefix("/{team_id:[A-Za-z0-9]+}").Subrouter() api.BaseRoutes.TeamForUser = api.BaseRoutes.TeamsForUser.PathPrefix("/{team_id:[A-Za-z0-9]+}").Subrouter() @@ -167,7 +167,7 @@ func Init(a app.AppIface, root *mux.Router) *API { api.BaseRoutes.TeamMember = api.BaseRoutes.TeamMembers.PathPrefix("/{user_id:[A-Za-z0-9]+}").Subrouter() api.BaseRoutes.TeamMembersForUser = api.BaseRoutes.User.PathPrefix("/teams/members").Subrouter() - api.BaseRoutes.Channels = api.BaseRoutes.ApiRoot.PathPrefix("/channels").Subrouter() + api.BaseRoutes.Channels = api.BaseRoutes.APIRoot.PathPrefix("/channels").Subrouter() api.BaseRoutes.Channel = api.BaseRoutes.Channels.PathPrefix("/{channel_id:[A-Za-z0-9]+}").Subrouter() api.BaseRoutes.ChannelForUser = api.BaseRoutes.User.PathPrefix("/channels/{channel_id:[A-Za-z0-9]+}").Subrouter() api.BaseRoutes.ChannelByName = api.BaseRoutes.Team.PathPrefix("/channels/name/{channel_name:[A-Za-z0-9_-]+}").Subrouter() @@ -179,77 +179,77 @@ func Init(a app.AppIface, root *mux.Router) *API { api.BaseRoutes.ChannelModerations = api.BaseRoutes.Channel.PathPrefix("/moderations").Subrouter() api.BaseRoutes.ChannelCategories = api.BaseRoutes.User.PathPrefix("/teams/{team_id:[A-Za-z0-9]+}/channels/categories").Subrouter() - api.BaseRoutes.Posts = api.BaseRoutes.ApiRoot.PathPrefix("/posts").Subrouter() + api.BaseRoutes.Posts = api.BaseRoutes.APIRoot.PathPrefix("/posts").Subrouter() api.BaseRoutes.Post = api.BaseRoutes.Posts.PathPrefix("/{post_id:[A-Za-z0-9]+}").Subrouter() api.BaseRoutes.PostsForChannel = api.BaseRoutes.Channel.PathPrefix("/posts").Subrouter() api.BaseRoutes.PostsForUser = api.BaseRoutes.User.PathPrefix("/posts").Subrouter() api.BaseRoutes.PostForUser = api.BaseRoutes.PostsForUser.PathPrefix("/{post_id:[A-Za-z0-9]+}").Subrouter() - api.BaseRoutes.Files = api.BaseRoutes.ApiRoot.PathPrefix("/files").Subrouter() + api.BaseRoutes.Files = api.BaseRoutes.APIRoot.PathPrefix("/files").Subrouter() api.BaseRoutes.File = api.BaseRoutes.Files.PathPrefix("/{file_id:[A-Za-z0-9]+}").Subrouter() api.BaseRoutes.PublicFile = api.BaseRoutes.Root.PathPrefix("/files/{file_id:[A-Za-z0-9]+}/public").Subrouter() - api.BaseRoutes.Uploads = api.BaseRoutes.ApiRoot.PathPrefix("/uploads").Subrouter() + api.BaseRoutes.Uploads = api.BaseRoutes.APIRoot.PathPrefix("/uploads").Subrouter() api.BaseRoutes.Upload = api.BaseRoutes.Uploads.PathPrefix("/{upload_id:[A-Za-z0-9]+}").Subrouter() - api.BaseRoutes.Plugins = api.BaseRoutes.ApiRoot.PathPrefix("/plugins").Subrouter() + api.BaseRoutes.Plugins = api.BaseRoutes.APIRoot.PathPrefix("/plugins").Subrouter() api.BaseRoutes.Plugin = api.BaseRoutes.Plugins.PathPrefix("/{plugin_id:[A-Za-z0-9\\_\\-\\.]+}").Subrouter() - api.BaseRoutes.Commands = api.BaseRoutes.ApiRoot.PathPrefix("/commands").Subrouter() + api.BaseRoutes.Commands = api.BaseRoutes.APIRoot.PathPrefix("/commands").Subrouter() api.BaseRoutes.Command = api.BaseRoutes.Commands.PathPrefix("/{command_id:[A-Za-z0-9]+}").Subrouter() - api.BaseRoutes.Hooks = api.BaseRoutes.ApiRoot.PathPrefix("/hooks").Subrouter() + api.BaseRoutes.Hooks = api.BaseRoutes.APIRoot.PathPrefix("/hooks").Subrouter() api.BaseRoutes.IncomingHooks = api.BaseRoutes.Hooks.PathPrefix("/incoming").Subrouter() api.BaseRoutes.IncomingHook = api.BaseRoutes.IncomingHooks.PathPrefix("/{hook_id:[A-Za-z0-9]+}").Subrouter() api.BaseRoutes.OutgoingHooks = api.BaseRoutes.Hooks.PathPrefix("/outgoing").Subrouter() api.BaseRoutes.OutgoingHook = api.BaseRoutes.OutgoingHooks.PathPrefix("/{hook_id:[A-Za-z0-9]+}").Subrouter() - api.BaseRoutes.SAML = api.BaseRoutes.ApiRoot.PathPrefix("/saml").Subrouter() + api.BaseRoutes.SAML = api.BaseRoutes.APIRoot.PathPrefix("/saml").Subrouter() - api.BaseRoutes.OAuth = api.BaseRoutes.ApiRoot.PathPrefix("/oauth").Subrouter() + api.BaseRoutes.OAuth = api.BaseRoutes.APIRoot.PathPrefix("/oauth").Subrouter() api.BaseRoutes.OAuthApps = api.BaseRoutes.OAuth.PathPrefix("/apps").Subrouter() api.BaseRoutes.OAuthApp = api.BaseRoutes.OAuthApps.PathPrefix("/{app_id:[A-Za-z0-9]+}").Subrouter() - api.BaseRoutes.Compliance = api.BaseRoutes.ApiRoot.PathPrefix("/compliance").Subrouter() - api.BaseRoutes.Cluster = api.BaseRoutes.ApiRoot.PathPrefix("/cluster").Subrouter() - api.BaseRoutes.LDAP = api.BaseRoutes.ApiRoot.PathPrefix("/ldap").Subrouter() - api.BaseRoutes.Brand = api.BaseRoutes.ApiRoot.PathPrefix("/brand").Subrouter() - api.BaseRoutes.System = api.BaseRoutes.ApiRoot.PathPrefix("/system").Subrouter() + api.BaseRoutes.Compliance = api.BaseRoutes.APIRoot.PathPrefix("/compliance").Subrouter() + api.BaseRoutes.Cluster = api.BaseRoutes.APIRoot.PathPrefix("/cluster").Subrouter() + api.BaseRoutes.LDAP = api.BaseRoutes.APIRoot.PathPrefix("/ldap").Subrouter() + api.BaseRoutes.Brand = api.BaseRoutes.APIRoot.PathPrefix("/brand").Subrouter() + api.BaseRoutes.System = api.BaseRoutes.APIRoot.PathPrefix("/system").Subrouter() api.BaseRoutes.Preferences = api.BaseRoutes.User.PathPrefix("/preferences").Subrouter() - api.BaseRoutes.License = api.BaseRoutes.ApiRoot.PathPrefix("/license").Subrouter() - api.BaseRoutes.Public = api.BaseRoutes.ApiRoot.PathPrefix("/public").Subrouter() - api.BaseRoutes.Reactions = api.BaseRoutes.ApiRoot.PathPrefix("/reactions").Subrouter() - api.BaseRoutes.Jobs = api.BaseRoutes.ApiRoot.PathPrefix("/jobs").Subrouter() - api.BaseRoutes.Elasticsearch = api.BaseRoutes.ApiRoot.PathPrefix("/elasticsearch").Subrouter() - api.BaseRoutes.Bleve = api.BaseRoutes.ApiRoot.PathPrefix("/bleve").Subrouter() - api.BaseRoutes.DataRetention = api.BaseRoutes.ApiRoot.PathPrefix("/data_retention").Subrouter() + api.BaseRoutes.License = api.BaseRoutes.APIRoot.PathPrefix("/license").Subrouter() + api.BaseRoutes.Public = api.BaseRoutes.APIRoot.PathPrefix("/public").Subrouter() + api.BaseRoutes.Reactions = api.BaseRoutes.APIRoot.PathPrefix("/reactions").Subrouter() + api.BaseRoutes.Jobs = api.BaseRoutes.APIRoot.PathPrefix("/jobs").Subrouter() + api.BaseRoutes.Elasticsearch = api.BaseRoutes.APIRoot.PathPrefix("/elasticsearch").Subrouter() + api.BaseRoutes.Bleve = api.BaseRoutes.APIRoot.PathPrefix("/bleve").Subrouter() + api.BaseRoutes.DataRetention = api.BaseRoutes.APIRoot.PathPrefix("/data_retention").Subrouter() - api.BaseRoutes.Emojis = api.BaseRoutes.ApiRoot.PathPrefix("/emoji").Subrouter() - api.BaseRoutes.Emoji = api.BaseRoutes.ApiRoot.PathPrefix("/emoji/{emoji_id:[A-Za-z0-9]+}").Subrouter() + api.BaseRoutes.Emojis = api.BaseRoutes.APIRoot.PathPrefix("/emoji").Subrouter() + api.BaseRoutes.Emoji = api.BaseRoutes.APIRoot.PathPrefix("/emoji/{emoji_id:[A-Za-z0-9]+}").Subrouter() api.BaseRoutes.EmojiByName = api.BaseRoutes.Emojis.PathPrefix("/name/{emoji_name:[A-Za-z0-9\\_\\-\\+]+}").Subrouter() api.BaseRoutes.ReactionByNameForPostForUser = api.BaseRoutes.PostForUser.PathPrefix("/reactions/{emoji_name:[A-Za-z0-9\\_\\-\\+]+}").Subrouter() - api.BaseRoutes.OpenGraph = api.BaseRoutes.ApiRoot.PathPrefix("/opengraph").Subrouter() + api.BaseRoutes.OpenGraph = api.BaseRoutes.APIRoot.PathPrefix("/opengraph").Subrouter() - api.BaseRoutes.Roles = api.BaseRoutes.ApiRoot.PathPrefix("/roles").Subrouter() - api.BaseRoutes.Schemes = api.BaseRoutes.ApiRoot.PathPrefix("/schemes").Subrouter() + api.BaseRoutes.Roles = api.BaseRoutes.APIRoot.PathPrefix("/roles").Subrouter() + api.BaseRoutes.Schemes = api.BaseRoutes.APIRoot.PathPrefix("/schemes").Subrouter() - api.BaseRoutes.Image = api.BaseRoutes.ApiRoot.PathPrefix("/image").Subrouter() + api.BaseRoutes.Image = api.BaseRoutes.APIRoot.PathPrefix("/image").Subrouter() - api.BaseRoutes.TermsOfService = api.BaseRoutes.ApiRoot.PathPrefix("/terms_of_service").Subrouter() - api.BaseRoutes.Groups = api.BaseRoutes.ApiRoot.PathPrefix("/groups").Subrouter() + api.BaseRoutes.TermsOfService = api.BaseRoutes.APIRoot.PathPrefix("/terms_of_service").Subrouter() + api.BaseRoutes.Groups = api.BaseRoutes.APIRoot.PathPrefix("/groups").Subrouter() - api.BaseRoutes.Cloud = api.BaseRoutes.ApiRoot.PathPrefix("/cloud").Subrouter() + api.BaseRoutes.Cloud = api.BaseRoutes.APIRoot.PathPrefix("/cloud").Subrouter() - api.BaseRoutes.Imports = api.BaseRoutes.ApiRoot.PathPrefix("/imports").Subrouter() - api.BaseRoutes.Exports = api.BaseRoutes.ApiRoot.PathPrefix("/exports").Subrouter() + api.BaseRoutes.Imports = api.BaseRoutes.APIRoot.PathPrefix("/imports").Subrouter() + api.BaseRoutes.Exports = api.BaseRoutes.APIRoot.PathPrefix("/exports").Subrouter() api.BaseRoutes.Export = api.BaseRoutes.Exports.PathPrefix("/{export_name:.+\\.zip}").Subrouter() - api.BaseRoutes.RemoteCluster = api.BaseRoutes.ApiRoot.PathPrefix("/remotecluster").Subrouter() - api.BaseRoutes.SharedChannels = api.BaseRoutes.ApiRoot.PathPrefix("/sharedchannels").Subrouter() + api.BaseRoutes.RemoteCluster = api.BaseRoutes.APIRoot.PathPrefix("/remotecluster").Subrouter() + api.BaseRoutes.SharedChannels = api.BaseRoutes.APIRoot.PathPrefix("/sharedchannels").Subrouter() - api.BaseRoutes.Permissions = api.BaseRoutes.ApiRoot.PathPrefix("/permissions").Subrouter() + api.BaseRoutes.Permissions = api.BaseRoutes.APIRoot.PathPrefix("/permissions").Subrouter() api.InitUser() api.InitBot() @@ -305,23 +305,23 @@ func InitLocal(a app.AppIface, root *mux.Router) *API { } api.BaseRoutes.Root = root - api.BaseRoutes.ApiRoot = root.PathPrefix(model.ApiUrlSuffix).Subrouter() + api.BaseRoutes.APIRoot = root.PathPrefix(model.APIURLSuffix).Subrouter() - api.BaseRoutes.Users = api.BaseRoutes.ApiRoot.PathPrefix("/users").Subrouter() + api.BaseRoutes.Users = api.BaseRoutes.APIRoot.PathPrefix("/users").Subrouter() api.BaseRoutes.User = api.BaseRoutes.Users.PathPrefix("/{user_id:[A-Za-z0-9]+}").Subrouter() api.BaseRoutes.UserByUsername = api.BaseRoutes.Users.PathPrefix("/username/{username:[A-Za-z0-9\\_\\-\\.]+}").Subrouter() api.BaseRoutes.UserByEmail = api.BaseRoutes.Users.PathPrefix("/email/{email:.+}").Subrouter() - api.BaseRoutes.Bots = api.BaseRoutes.ApiRoot.PathPrefix("/bots").Subrouter() - api.BaseRoutes.Bot = api.BaseRoutes.ApiRoot.PathPrefix("/bots/{bot_user_id:[A-Za-z0-9]+}").Subrouter() + api.BaseRoutes.Bots = api.BaseRoutes.APIRoot.PathPrefix("/bots").Subrouter() + api.BaseRoutes.Bot = api.BaseRoutes.APIRoot.PathPrefix("/bots/{bot_user_id:[A-Za-z0-9]+}").Subrouter() - api.BaseRoutes.Teams = api.BaseRoutes.ApiRoot.PathPrefix("/teams").Subrouter() + api.BaseRoutes.Teams = api.BaseRoutes.APIRoot.PathPrefix("/teams").Subrouter() api.BaseRoutes.Team = api.BaseRoutes.Teams.PathPrefix("/{team_id:[A-Za-z0-9]+}").Subrouter() api.BaseRoutes.TeamByName = api.BaseRoutes.Teams.PathPrefix("/name/{team_name:[A-Za-z0-9_-]+}").Subrouter() api.BaseRoutes.TeamMembers = api.BaseRoutes.Team.PathPrefix("/members").Subrouter() api.BaseRoutes.TeamMember = api.BaseRoutes.TeamMembers.PathPrefix("/{user_id:[A-Za-z0-9]+}").Subrouter() - api.BaseRoutes.Channels = api.BaseRoutes.ApiRoot.PathPrefix("/channels").Subrouter() + api.BaseRoutes.Channels = api.BaseRoutes.APIRoot.PathPrefix("/channels").Subrouter() api.BaseRoutes.Channel = api.BaseRoutes.Channels.PathPrefix("/{channel_id:[A-Za-z0-9]+}").Subrouter() api.BaseRoutes.ChannelByName = api.BaseRoutes.Team.PathPrefix("/channels/name/{channel_name:[A-Za-z0-9_-]+}").Subrouter() @@ -331,40 +331,40 @@ func InitLocal(a app.AppIface, root *mux.Router) *API { api.BaseRoutes.ChannelMember = api.BaseRoutes.ChannelMembers.PathPrefix("/{user_id:[A-Za-z0-9]+}").Subrouter() api.BaseRoutes.ChannelMembersForUser = api.BaseRoutes.User.PathPrefix("/teams/{team_id:[A-Za-z0-9]+}/channels/members").Subrouter() - api.BaseRoutes.Plugins = api.BaseRoutes.ApiRoot.PathPrefix("/plugins").Subrouter() + api.BaseRoutes.Plugins = api.BaseRoutes.APIRoot.PathPrefix("/plugins").Subrouter() api.BaseRoutes.Plugin = api.BaseRoutes.Plugins.PathPrefix("/{plugin_id:[A-Za-z0-9\\_\\-\\.]+}").Subrouter() - api.BaseRoutes.Commands = api.BaseRoutes.ApiRoot.PathPrefix("/commands").Subrouter() + api.BaseRoutes.Commands = api.BaseRoutes.APIRoot.PathPrefix("/commands").Subrouter() api.BaseRoutes.Command = api.BaseRoutes.Commands.PathPrefix("/{command_id:[A-Za-z0-9]+}").Subrouter() - api.BaseRoutes.Hooks = api.BaseRoutes.ApiRoot.PathPrefix("/hooks").Subrouter() + api.BaseRoutes.Hooks = api.BaseRoutes.APIRoot.PathPrefix("/hooks").Subrouter() api.BaseRoutes.IncomingHooks = api.BaseRoutes.Hooks.PathPrefix("/incoming").Subrouter() api.BaseRoutes.IncomingHook = api.BaseRoutes.IncomingHooks.PathPrefix("/{hook_id:[A-Za-z0-9]+}").Subrouter() api.BaseRoutes.OutgoingHooks = api.BaseRoutes.Hooks.PathPrefix("/outgoing").Subrouter() api.BaseRoutes.OutgoingHook = api.BaseRoutes.OutgoingHooks.PathPrefix("/{hook_id:[A-Za-z0-9]+}").Subrouter() - api.BaseRoutes.License = api.BaseRoutes.ApiRoot.PathPrefix("/license").Subrouter() + api.BaseRoutes.License = api.BaseRoutes.APIRoot.PathPrefix("/license").Subrouter() - api.BaseRoutes.Groups = api.BaseRoutes.ApiRoot.PathPrefix("/groups").Subrouter() + api.BaseRoutes.Groups = api.BaseRoutes.APIRoot.PathPrefix("/groups").Subrouter() - api.BaseRoutes.LDAP = api.BaseRoutes.ApiRoot.PathPrefix("/ldap").Subrouter() - api.BaseRoutes.System = api.BaseRoutes.ApiRoot.PathPrefix("/system").Subrouter() - api.BaseRoutes.Posts = api.BaseRoutes.ApiRoot.PathPrefix("/posts").Subrouter() + api.BaseRoutes.LDAP = api.BaseRoutes.APIRoot.PathPrefix("/ldap").Subrouter() + api.BaseRoutes.System = api.BaseRoutes.APIRoot.PathPrefix("/system").Subrouter() + api.BaseRoutes.Posts = api.BaseRoutes.APIRoot.PathPrefix("/posts").Subrouter() api.BaseRoutes.Post = api.BaseRoutes.Posts.PathPrefix("/{post_id:[A-Za-z0-9]+}").Subrouter() api.BaseRoutes.PostsForChannel = api.BaseRoutes.Channel.PathPrefix("/posts").Subrouter() - api.BaseRoutes.Roles = api.BaseRoutes.ApiRoot.PathPrefix("/roles").Subrouter() + api.BaseRoutes.Roles = api.BaseRoutes.APIRoot.PathPrefix("/roles").Subrouter() - api.BaseRoutes.Uploads = api.BaseRoutes.ApiRoot.PathPrefix("/uploads").Subrouter() + api.BaseRoutes.Uploads = api.BaseRoutes.APIRoot.PathPrefix("/uploads").Subrouter() api.BaseRoutes.Upload = api.BaseRoutes.Uploads.PathPrefix("/{upload_id:[A-Za-z0-9]+}").Subrouter() - api.BaseRoutes.Imports = api.BaseRoutes.ApiRoot.PathPrefix("/imports").Subrouter() - api.BaseRoutes.Exports = api.BaseRoutes.ApiRoot.PathPrefix("/exports").Subrouter() + api.BaseRoutes.Imports = api.BaseRoutes.APIRoot.PathPrefix("/imports").Subrouter() + api.BaseRoutes.Exports = api.BaseRoutes.APIRoot.PathPrefix("/exports").Subrouter() api.BaseRoutes.Export = api.BaseRoutes.Exports.PathPrefix("/{export_name:.+\\.zip}").Subrouter() - api.BaseRoutes.Jobs = api.BaseRoutes.ApiRoot.PathPrefix("/jobs").Subrouter() + api.BaseRoutes.Jobs = api.BaseRoutes.APIRoot.PathPrefix("/jobs").Subrouter() - api.BaseRoutes.SAML = api.BaseRoutes.ApiRoot.PathPrefix("/saml").Subrouter() + api.BaseRoutes.SAML = api.BaseRoutes.APIRoot.PathPrefix("/saml").Subrouter() api.InitUserLocal() api.InitTeamLocal() diff --git a/api4/apitestlib.go b/api4/apitestlib.go index ec63193677..9d259b7365 100644 --- a/api4/apitestlib.go +++ b/api4/apitestlib.go @@ -469,7 +469,7 @@ func (th *TestHelper) CreateLocalClient(socketPath string) *model.Client4 { } return &model.Client4{ - ApiUrl: "http://_" + model.ApiUrlSuffix, + APIURL: "http://_" + model.APIURLSuffix, HTTPClient: httpClient, } } @@ -609,8 +609,8 @@ func (th *TestHelper) SetupSamlConfig() { *cfg.SamlSettings.Enable = true *cfg.SamlSettings.Verify = false *cfg.SamlSettings.Encrypt = false - *cfg.SamlSettings.IdpUrl = "https://does.notmatter.com" - *cfg.SamlSettings.IdpDescriptorUrl = "https://localhost/adfs/services/trust" + *cfg.SamlSettings.IdpURL = "https://does.notmatter.com" + *cfg.SamlSettings.IdpDescriptorURL = "https://localhost/adfs/services/trust" *cfg.SamlSettings.AssertionConsumerServiceURL = "https://localhost/login/sso/saml" *cfg.SamlSettings.ServiceProviderIdentifier = "https://localhost/login/sso/saml" *cfg.SamlSettings.IdpCertificateFile = app.SamlIdpCertificateName diff --git a/api4/bleve.go b/api4/bleve.go index 7f560a70e6..e6b43480d2 100644 --- a/api4/bleve.go +++ b/api4/bleve.go @@ -11,7 +11,7 @@ import ( ) func (api *API) InitBleve() { - api.BaseRoutes.Bleve.Handle("/purge_indexes", api.ApiSessionRequired(purgeBleveIndexes)).Methods("POST") + api.BaseRoutes.Bleve.Handle("/purge_indexes", api.APISessionRequired(purgeBleveIndexes)).Methods("POST") } func purgeBleveIndexes(c *Context, w http.ResponseWriter, r *http.Request) { diff --git a/api4/bot.go b/api4/bot.go index 2f71373007..98f410e0e4 100644 --- a/api4/bot.go +++ b/api4/bot.go @@ -14,14 +14,14 @@ import ( ) func (api *API) InitBot() { - api.BaseRoutes.Bots.Handle("", api.ApiSessionRequired(createBot)).Methods("POST") - api.BaseRoutes.Bot.Handle("", api.ApiSessionRequired(patchBot)).Methods("PUT") - api.BaseRoutes.Bot.Handle("", api.ApiSessionRequired(getBot)).Methods("GET") - api.BaseRoutes.Bots.Handle("", api.ApiSessionRequired(getBots)).Methods("GET") - api.BaseRoutes.Bot.Handle("/disable", api.ApiSessionRequired(disableBot)).Methods("POST") - api.BaseRoutes.Bot.Handle("/enable", api.ApiSessionRequired(enableBot)).Methods("POST") - api.BaseRoutes.Bot.Handle("/convert_to_user", api.ApiSessionRequired(convertBotToUser)).Methods("POST") - api.BaseRoutes.Bot.Handle("/assign/{user_id:[A-Za-z0-9]+}", api.ApiSessionRequired(assignBot)).Methods("POST") + api.BaseRoutes.Bots.Handle("", api.APISessionRequired(createBot)).Methods("POST") + api.BaseRoutes.Bot.Handle("", api.APISessionRequired(patchBot)).Methods("PUT") + api.BaseRoutes.Bot.Handle("", api.APISessionRequired(getBot)).Methods("GET") + api.BaseRoutes.Bots.Handle("", api.APISessionRequired(getBots)).Methods("GET") + api.BaseRoutes.Bot.Handle("/disable", api.APISessionRequired(disableBot)).Methods("POST") + api.BaseRoutes.Bot.Handle("/enable", api.APISessionRequired(enableBot)).Methods("POST") + api.BaseRoutes.Bot.Handle("/convert_to_user", api.APISessionRequired(convertBotToUser)).Methods("POST") + api.BaseRoutes.Bot.Handle("/assign/{user_id:[A-Za-z0-9]+}", api.APISessionRequired(assignBot)).Methods("POST") } func createBot(c *Context, w http.ResponseWriter, r *http.Request) { diff --git a/api4/bot_local.go b/api4/bot_local.go index 369ba62a75..0b988dd5a3 100644 --- a/api4/bot_local.go +++ b/api4/bot_local.go @@ -4,12 +4,12 @@ package api4 func (api *API) InitBotLocal() { - api.BaseRoutes.Bot.Handle("", api.ApiLocal(getBot)).Methods("GET") - api.BaseRoutes.Bot.Handle("", api.ApiLocal(patchBot)).Methods("PUT") - api.BaseRoutes.Bot.Handle("/disable", api.ApiLocal(disableBot)).Methods("POST") - api.BaseRoutes.Bot.Handle("/enable", api.ApiLocal(enableBot)).Methods("POST") - api.BaseRoutes.Bot.Handle("/convert_to_user", api.ApiLocal(convertBotToUser)).Methods("POST") - api.BaseRoutes.Bot.Handle("/assign/{user_id:[A-Za-z0-9]+}", api.ApiLocal(assignBot)).Methods("POST") + api.BaseRoutes.Bot.Handle("", api.APILocal(getBot)).Methods("GET") + api.BaseRoutes.Bot.Handle("", api.APILocal(patchBot)).Methods("PUT") + api.BaseRoutes.Bot.Handle("/disable", api.APILocal(disableBot)).Methods("POST") + api.BaseRoutes.Bot.Handle("/enable", api.APILocal(enableBot)).Methods("POST") + api.BaseRoutes.Bot.Handle("/convert_to_user", api.APILocal(convertBotToUser)).Methods("POST") + api.BaseRoutes.Bot.Handle("/assign/{user_id:[A-Za-z0-9]+}", api.APILocal(assignBot)).Methods("POST") - api.BaseRoutes.Bots.Handle("", api.ApiLocal(getBots)).Methods("GET") + api.BaseRoutes.Bots.Handle("", api.APILocal(getBots)).Methods("GET") } diff --git a/api4/bot_test.go b/api4/bot_test.go index 6826bb7665..00d2960b3e 100644 --- a/api4/bot_test.go +++ b/api4/bot_test.go @@ -458,7 +458,7 @@ func TestPatchBot(t *testing.T) { CheckCreatedStatus(t, resp) defer th.App.PermanentDeleteBot(createdBot.UserId) - r, err := th.Client.DoApiPut("/bots/"+createdBot.UserId, `{"creator_id":"`+th.BasicUser2.Id+`"}`) + r, err := th.Client.DoAPIPut("/bots/"+createdBot.UserId, `{"creator_id":"`+th.BasicUser2.Id+`"}`) require.NoError(t, err) defer func() { _, _ = ioutil.ReadAll(r.Body) diff --git a/api4/brand.go b/api4/brand.go index 744170f1e6..2903b5e289 100644 --- a/api4/brand.go +++ b/api4/brand.go @@ -13,9 +13,9 @@ import ( ) func (api *API) InitBrand() { - api.BaseRoutes.Brand.Handle("/image", api.ApiHandlerTrustRequester(getBrandImage)).Methods("GET") - api.BaseRoutes.Brand.Handle("/image", api.ApiSessionRequired(uploadBrandImage)).Methods("POST") - api.BaseRoutes.Brand.Handle("/image", api.ApiSessionRequired(deleteBrandImage)).Methods("DELETE") + api.BaseRoutes.Brand.Handle("/image", api.APIHandlerTrustRequester(getBrandImage)).Methods("GET") + api.BaseRoutes.Brand.Handle("/image", api.APISessionRequired(uploadBrandImage)).Methods("POST") + api.BaseRoutes.Brand.Handle("/image", api.APISessionRequired(deleteBrandImage)).Methods("DELETE") } func getBrandImage(c *Context, w http.ResponseWriter, r *http.Request) { diff --git a/api4/channel.go b/api4/channel.go index 286ee5ad9f..5aa72633ea 100644 --- a/api4/channel.go +++ b/api4/channel.go @@ -17,64 +17,64 @@ import ( ) func (api *API) InitChannel() { - api.BaseRoutes.Channels.Handle("", api.ApiSessionRequired(getAllChannels)).Methods("GET") - api.BaseRoutes.Channels.Handle("", api.ApiSessionRequired(createChannel)).Methods("POST") - api.BaseRoutes.Channels.Handle("/direct", api.ApiSessionRequired(createDirectChannel)).Methods("POST") - api.BaseRoutes.Channels.Handle("/search", api.ApiSessionRequiredDisableWhenBusy(searchAllChannels)).Methods("POST") - api.BaseRoutes.Channels.Handle("/group/search", api.ApiSessionRequiredDisableWhenBusy(searchGroupChannels)).Methods("POST") - api.BaseRoutes.Channels.Handle("/group", api.ApiSessionRequired(createGroupChannel)).Methods("POST") - api.BaseRoutes.Channels.Handle("/members/{user_id:[A-Za-z0-9]+}/view", api.ApiSessionRequired(viewChannel)).Methods("POST") - api.BaseRoutes.Channels.Handle("/{channel_id:[A-Za-z0-9]+}/scheme", api.ApiSessionRequired(updateChannelScheme)).Methods("PUT") + api.BaseRoutes.Channels.Handle("", api.APISessionRequired(getAllChannels)).Methods("GET") + api.BaseRoutes.Channels.Handle("", api.APISessionRequired(createChannel)).Methods("POST") + api.BaseRoutes.Channels.Handle("/direct", api.APISessionRequired(createDirectChannel)).Methods("POST") + api.BaseRoutes.Channels.Handle("/search", api.APISessionRequiredDisableWhenBusy(searchAllChannels)).Methods("POST") + api.BaseRoutes.Channels.Handle("/group/search", api.APISessionRequiredDisableWhenBusy(searchGroupChannels)).Methods("POST") + api.BaseRoutes.Channels.Handle("/group", api.APISessionRequired(createGroupChannel)).Methods("POST") + api.BaseRoutes.Channels.Handle("/members/{user_id:[A-Za-z0-9]+}/view", api.APISessionRequired(viewChannel)).Methods("POST") + api.BaseRoutes.Channels.Handle("/{channel_id:[A-Za-z0-9]+}/scheme", api.APISessionRequired(updateChannelScheme)).Methods("PUT") - api.BaseRoutes.ChannelsForTeam.Handle("", api.ApiSessionRequired(getPublicChannelsForTeam)).Methods("GET") - api.BaseRoutes.ChannelsForTeam.Handle("/deleted", api.ApiSessionRequired(getDeletedChannelsForTeam)).Methods("GET") - api.BaseRoutes.ChannelsForTeam.Handle("/private", api.ApiSessionRequired(getPrivateChannelsForTeam)).Methods("GET") - api.BaseRoutes.ChannelsForTeam.Handle("/ids", api.ApiSessionRequired(getPublicChannelsByIdsForTeam)).Methods("POST") - api.BaseRoutes.ChannelsForTeam.Handle("/search", api.ApiSessionRequiredDisableWhenBusy(searchChannelsForTeam)).Methods("POST") - api.BaseRoutes.ChannelsForTeam.Handle("/search_archived", api.ApiSessionRequiredDisableWhenBusy(searchArchivedChannelsForTeam)).Methods("POST") - api.BaseRoutes.ChannelsForTeam.Handle("/autocomplete", api.ApiSessionRequired(autocompleteChannelsForTeam)).Methods("GET") - api.BaseRoutes.ChannelsForTeam.Handle("/search_autocomplete", api.ApiSessionRequired(autocompleteChannelsForTeamForSearch)).Methods("GET") - api.BaseRoutes.User.Handle("/teams/{team_id:[A-Za-z0-9]+}/channels", api.ApiSessionRequired(getChannelsForTeamForUser)).Methods("GET") + api.BaseRoutes.ChannelsForTeam.Handle("", api.APISessionRequired(getPublicChannelsForTeam)).Methods("GET") + api.BaseRoutes.ChannelsForTeam.Handle("/deleted", api.APISessionRequired(getDeletedChannelsForTeam)).Methods("GET") + api.BaseRoutes.ChannelsForTeam.Handle("/private", api.APISessionRequired(getPrivateChannelsForTeam)).Methods("GET") + api.BaseRoutes.ChannelsForTeam.Handle("/ids", api.APISessionRequired(getPublicChannelsByIdsForTeam)).Methods("POST") + api.BaseRoutes.ChannelsForTeam.Handle("/search", api.APISessionRequiredDisableWhenBusy(searchChannelsForTeam)).Methods("POST") + api.BaseRoutes.ChannelsForTeam.Handle("/search_archived", api.APISessionRequiredDisableWhenBusy(searchArchivedChannelsForTeam)).Methods("POST") + api.BaseRoutes.ChannelsForTeam.Handle("/autocomplete", api.APISessionRequired(autocompleteChannelsForTeam)).Methods("GET") + api.BaseRoutes.ChannelsForTeam.Handle("/search_autocomplete", api.APISessionRequired(autocompleteChannelsForTeamForSearch)).Methods("GET") + api.BaseRoutes.User.Handle("/teams/{team_id:[A-Za-z0-9]+}/channels", api.APISessionRequired(getChannelsForTeamForUser)).Methods("GET") - api.BaseRoutes.ChannelCategories.Handle("", api.ApiSessionRequired(getCategoriesForTeamForUser)).Methods("GET") - api.BaseRoutes.ChannelCategories.Handle("", api.ApiSessionRequired(createCategoryForTeamForUser)).Methods("POST") - api.BaseRoutes.ChannelCategories.Handle("", api.ApiSessionRequired(updateCategoriesForTeamForUser)).Methods("PUT") - api.BaseRoutes.ChannelCategories.Handle("/order", api.ApiSessionRequired(getCategoryOrderForTeamForUser)).Methods("GET") - api.BaseRoutes.ChannelCategories.Handle("/order", api.ApiSessionRequired(updateCategoryOrderForTeamForUser)).Methods("PUT") - api.BaseRoutes.ChannelCategories.Handle("/{category_id:[A-Za-z0-9_-]+}", api.ApiSessionRequired(getCategoryForTeamForUser)).Methods("GET") - api.BaseRoutes.ChannelCategories.Handle("/{category_id:[A-Za-z0-9_-]+}", api.ApiSessionRequired(updateCategoryForTeamForUser)).Methods("PUT") - api.BaseRoutes.ChannelCategories.Handle("/{category_id:[A-Za-z0-9_-]+}", api.ApiSessionRequired(deleteCategoryForTeamForUser)).Methods("DELETE") + api.BaseRoutes.ChannelCategories.Handle("", api.APISessionRequired(getCategoriesForTeamForUser)).Methods("GET") + api.BaseRoutes.ChannelCategories.Handle("", api.APISessionRequired(createCategoryForTeamForUser)).Methods("POST") + api.BaseRoutes.ChannelCategories.Handle("", api.APISessionRequired(updateCategoriesForTeamForUser)).Methods("PUT") + api.BaseRoutes.ChannelCategories.Handle("/order", api.APISessionRequired(getCategoryOrderForTeamForUser)).Methods("GET") + api.BaseRoutes.ChannelCategories.Handle("/order", api.APISessionRequired(updateCategoryOrderForTeamForUser)).Methods("PUT") + api.BaseRoutes.ChannelCategories.Handle("/{category_id:[A-Za-z0-9_-]+}", api.APISessionRequired(getCategoryForTeamForUser)).Methods("GET") + api.BaseRoutes.ChannelCategories.Handle("/{category_id:[A-Za-z0-9_-]+}", api.APISessionRequired(updateCategoryForTeamForUser)).Methods("PUT") + api.BaseRoutes.ChannelCategories.Handle("/{category_id:[A-Za-z0-9_-]+}", api.APISessionRequired(deleteCategoryForTeamForUser)).Methods("DELETE") - api.BaseRoutes.Channel.Handle("", api.ApiSessionRequired(getChannel)).Methods("GET") - api.BaseRoutes.Channel.Handle("", api.ApiSessionRequired(updateChannel)).Methods("PUT") - api.BaseRoutes.Channel.Handle("/patch", api.ApiSessionRequired(patchChannel)).Methods("PUT") - api.BaseRoutes.Channel.Handle("/privacy", api.ApiSessionRequired(updateChannelPrivacy)).Methods("PUT") - api.BaseRoutes.Channel.Handle("/restore", api.ApiSessionRequired(restoreChannel)).Methods("POST") - api.BaseRoutes.Channel.Handle("", api.ApiSessionRequired(deleteChannel)).Methods("DELETE") - api.BaseRoutes.Channel.Handle("/stats", api.ApiSessionRequired(getChannelStats)).Methods("GET") - api.BaseRoutes.Channel.Handle("/pinned", api.ApiSessionRequired(getPinnedPosts)).Methods("GET") - api.BaseRoutes.Channel.Handle("/timezones", api.ApiSessionRequired(getChannelMembersTimezones)).Methods("GET") - api.BaseRoutes.Channel.Handle("/members_minus_group_members", api.ApiSessionRequired(channelMembersMinusGroupMembers)).Methods("GET") - api.BaseRoutes.Channel.Handle("/move", api.ApiSessionRequired(moveChannel)).Methods("POST") - api.BaseRoutes.Channel.Handle("/member_counts_by_group", api.ApiSessionRequired(channelMemberCountsByGroup)).Methods("GET") + api.BaseRoutes.Channel.Handle("", api.APISessionRequired(getChannel)).Methods("GET") + api.BaseRoutes.Channel.Handle("", api.APISessionRequired(updateChannel)).Methods("PUT") + api.BaseRoutes.Channel.Handle("/patch", api.APISessionRequired(patchChannel)).Methods("PUT") + api.BaseRoutes.Channel.Handle("/privacy", api.APISessionRequired(updateChannelPrivacy)).Methods("PUT") + api.BaseRoutes.Channel.Handle("/restore", api.APISessionRequired(restoreChannel)).Methods("POST") + api.BaseRoutes.Channel.Handle("", api.APISessionRequired(deleteChannel)).Methods("DELETE") + api.BaseRoutes.Channel.Handle("/stats", api.APISessionRequired(getChannelStats)).Methods("GET") + api.BaseRoutes.Channel.Handle("/pinned", api.APISessionRequired(getPinnedPosts)).Methods("GET") + api.BaseRoutes.Channel.Handle("/timezones", api.APISessionRequired(getChannelMembersTimezones)).Methods("GET") + api.BaseRoutes.Channel.Handle("/members_minus_group_members", api.APISessionRequired(channelMembersMinusGroupMembers)).Methods("GET") + api.BaseRoutes.Channel.Handle("/move", api.APISessionRequired(moveChannel)).Methods("POST") + api.BaseRoutes.Channel.Handle("/member_counts_by_group", api.APISessionRequired(channelMemberCountsByGroup)).Methods("GET") - api.BaseRoutes.ChannelForUser.Handle("/unread", api.ApiSessionRequired(getChannelUnread)).Methods("GET") + api.BaseRoutes.ChannelForUser.Handle("/unread", api.APISessionRequired(getChannelUnread)).Methods("GET") - api.BaseRoutes.ChannelByName.Handle("", api.ApiSessionRequired(getChannelByName)).Methods("GET") - api.BaseRoutes.ChannelByNameForTeamName.Handle("", api.ApiSessionRequired(getChannelByNameForTeamName)).Methods("GET") + api.BaseRoutes.ChannelByName.Handle("", api.APISessionRequired(getChannelByName)).Methods("GET") + api.BaseRoutes.ChannelByNameForTeamName.Handle("", api.APISessionRequired(getChannelByNameForTeamName)).Methods("GET") - api.BaseRoutes.ChannelMembers.Handle("", api.ApiSessionRequired(getChannelMembers)).Methods("GET") - api.BaseRoutes.ChannelMembers.Handle("/ids", api.ApiSessionRequired(getChannelMembersByIds)).Methods("POST") - api.BaseRoutes.ChannelMembers.Handle("", api.ApiSessionRequired(addChannelMember)).Methods("POST") - api.BaseRoutes.ChannelMembersForUser.Handle("", api.ApiSessionRequired(getChannelMembersForUser)).Methods("GET") - api.BaseRoutes.ChannelMember.Handle("", api.ApiSessionRequired(getChannelMember)).Methods("GET") - api.BaseRoutes.ChannelMember.Handle("", api.ApiSessionRequired(removeChannelMember)).Methods("DELETE") - api.BaseRoutes.ChannelMember.Handle("/roles", api.ApiSessionRequired(updateChannelMemberRoles)).Methods("PUT") - api.BaseRoutes.ChannelMember.Handle("/schemeRoles", api.ApiSessionRequired(updateChannelMemberSchemeRoles)).Methods("PUT") - api.BaseRoutes.ChannelMember.Handle("/notify_props", api.ApiSessionRequired(updateChannelMemberNotifyProps)).Methods("PUT") + api.BaseRoutes.ChannelMembers.Handle("", api.APISessionRequired(getChannelMembers)).Methods("GET") + api.BaseRoutes.ChannelMembers.Handle("/ids", api.APISessionRequired(getChannelMembersByIds)).Methods("POST") + api.BaseRoutes.ChannelMembers.Handle("", api.APISessionRequired(addChannelMember)).Methods("POST") + api.BaseRoutes.ChannelMembersForUser.Handle("", api.APISessionRequired(getChannelMembersForUser)).Methods("GET") + api.BaseRoutes.ChannelMember.Handle("", api.APISessionRequired(getChannelMember)).Methods("GET") + api.BaseRoutes.ChannelMember.Handle("", api.APISessionRequired(removeChannelMember)).Methods("DELETE") + api.BaseRoutes.ChannelMember.Handle("/roles", api.APISessionRequired(updateChannelMemberRoles)).Methods("PUT") + api.BaseRoutes.ChannelMember.Handle("/schemeRoles", api.APISessionRequired(updateChannelMemberSchemeRoles)).Methods("PUT") + api.BaseRoutes.ChannelMember.Handle("/notify_props", api.APISessionRequired(updateChannelMemberNotifyProps)).Methods("PUT") - api.BaseRoutes.ChannelModerations.Handle("", api.ApiSessionRequired(getChannelModerations)).Methods("GET") - api.BaseRoutes.ChannelModerations.Handle("/patch", api.ApiSessionRequired(patchChannelModerations)).Methods("PUT") + api.BaseRoutes.ChannelModerations.Handle("", api.APISessionRequired(getChannelModerations)).Methods("GET") + api.BaseRoutes.ChannelModerations.Handle("/patch", api.APISessionRequired(patchChannelModerations)).Methods("PUT") } func createChannel(c *Context, w http.ResponseWriter, r *http.Request) { @@ -873,7 +873,7 @@ func getChannelsForTeamForUser(c *Context, w http.ResponseWriter, r *http.Reques lastDeleteAt = 0 } if lastDeleteAt < 0 { - c.SetInvalidUrlParam("last_delete_at") + c.SetInvalidURLParam("last_delete_at") return } diff --git a/api4/channel_local.go b/api4/channel_local.go index 4430070f7b..82b98bb9fa 100644 --- a/api4/channel_local.go +++ b/api4/channel_local.go @@ -14,27 +14,27 @@ import ( ) func (api *API) InitChannelLocal() { - api.BaseRoutes.Channels.Handle("", api.ApiLocal(getAllChannels)).Methods("GET") - api.BaseRoutes.Channels.Handle("", api.ApiLocal(localCreateChannel)).Methods("POST") - api.BaseRoutes.Channel.Handle("", api.ApiLocal(getChannel)).Methods("GET") - api.BaseRoutes.ChannelByName.Handle("", api.ApiLocal(getChannelByName)).Methods("GET") - api.BaseRoutes.Channel.Handle("", api.ApiLocal(localDeleteChannel)).Methods("DELETE") - api.BaseRoutes.Channel.Handle("/patch", api.ApiLocal(localPatchChannel)).Methods("PUT") - api.BaseRoutes.Channel.Handle("/move", api.ApiLocal(localMoveChannel)).Methods("POST") - api.BaseRoutes.Channel.Handle("/privacy", api.ApiLocal(localUpdateChannelPrivacy)).Methods("PUT") - api.BaseRoutes.Channel.Handle("/restore", api.ApiLocal(localRestoreChannel)).Methods("POST") + api.BaseRoutes.Channels.Handle("", api.APILocal(getAllChannels)).Methods("GET") + api.BaseRoutes.Channels.Handle("", api.APILocal(localCreateChannel)).Methods("POST") + api.BaseRoutes.Channel.Handle("", api.APILocal(getChannel)).Methods("GET") + api.BaseRoutes.ChannelByName.Handle("", api.APILocal(getChannelByName)).Methods("GET") + api.BaseRoutes.Channel.Handle("", api.APILocal(localDeleteChannel)).Methods("DELETE") + api.BaseRoutes.Channel.Handle("/patch", api.APILocal(localPatchChannel)).Methods("PUT") + api.BaseRoutes.Channel.Handle("/move", api.APILocal(localMoveChannel)).Methods("POST") + api.BaseRoutes.Channel.Handle("/privacy", api.APILocal(localUpdateChannelPrivacy)).Methods("PUT") + api.BaseRoutes.Channel.Handle("/restore", api.APILocal(localRestoreChannel)).Methods("POST") - api.BaseRoutes.ChannelMember.Handle("", api.ApiLocal(localRemoveChannelMember)).Methods("DELETE") - api.BaseRoutes.ChannelMember.Handle("", api.ApiLocal(getChannelMember)).Methods("GET") - api.BaseRoutes.ChannelMembers.Handle("", api.ApiLocal(localAddChannelMember)).Methods("POST") - api.BaseRoutes.ChannelMembers.Handle("", api.ApiLocal(getChannelMembers)).Methods("GET") + api.BaseRoutes.ChannelMember.Handle("", api.APILocal(localRemoveChannelMember)).Methods("DELETE") + api.BaseRoutes.ChannelMember.Handle("", api.APILocal(getChannelMember)).Methods("GET") + api.BaseRoutes.ChannelMembers.Handle("", api.APILocal(localAddChannelMember)).Methods("POST") + api.BaseRoutes.ChannelMembers.Handle("", api.APILocal(getChannelMembers)).Methods("GET") - api.BaseRoutes.ChannelsForTeam.Handle("", api.ApiLocal(getPublicChannelsForTeam)).Methods("GET") - api.BaseRoutes.ChannelsForTeam.Handle("/deleted", api.ApiLocal(getDeletedChannelsForTeam)).Methods("GET") - api.BaseRoutes.ChannelsForTeam.Handle("/private", api.ApiLocal(getPrivateChannelsForTeam)).Methods("GET") + api.BaseRoutes.ChannelsForTeam.Handle("", api.APILocal(getPublicChannelsForTeam)).Methods("GET") + api.BaseRoutes.ChannelsForTeam.Handle("/deleted", api.APILocal(getDeletedChannelsForTeam)).Methods("GET") + api.BaseRoutes.ChannelsForTeam.Handle("/private", api.APILocal(getPrivateChannelsForTeam)).Methods("GET") - api.BaseRoutes.ChannelByName.Handle("", api.ApiLocal(getChannelByName)).Methods("GET") - api.BaseRoutes.ChannelByNameForTeamName.Handle("", api.ApiLocal(getChannelByNameForTeamName)).Methods("GET") + api.BaseRoutes.ChannelByName.Handle("", api.APILocal(getChannelByName)).Methods("GET") + api.BaseRoutes.ChannelByNameForTeamName.Handle("", api.APILocal(getChannelByNameForTeamName)).Methods("GET") } func localCreateChannel(c *Context, w http.ResponseWriter, r *http.Request) { diff --git a/api4/channel_test.go b/api4/channel_test.go index e9de38336d..dcea6af7e0 100644 --- a/api4/channel_test.go +++ b/api4/channel_test.go @@ -126,7 +126,7 @@ func TestCreateChannel(t *testing.T) { }) // Test posting Garbage - r, err := client.DoApiPost("/channels", "garbage") + r, err := client.DoAPIPost("/channels", "garbage") require.Error(t, err, "expected error") require.Equal(t, http.StatusBadRequest, r.StatusCode, "Expected 400 Bad Request") @@ -435,7 +435,7 @@ func TestCreateDirectChannel(t *testing.T) { require.Error(t, err) CheckForbiddenStatus(t, resp) - r, err := client.DoApiPost("/channels/direct", "garbage") + r, err := client.DoAPIPost("/channels/direct", "garbage") require.Error(t, err) require.Equal(t, http.StatusBadRequest, r.StatusCode) @@ -2346,7 +2346,7 @@ func TestViewChannel(t *testing.T) { require.Error(t, err) CheckForbiddenStatus(t, resp) - r, err := client.DoApiPost(fmt.Sprintf("/channels/members/%v/view", th.BasicUser.Id), "garbage") + r, err := client.DoAPIPost(fmt.Sprintf("/channels/members/%v/view", th.BasicUser.Id), "garbage") require.Error(t, err) require.Equal(t, http.StatusBadRequest, r.StatusCode) diff --git a/api4/cloud.go b/api4/cloud.go index 0ea3c20d8a..0930059354 100644 --- a/api4/cloud.go +++ b/api4/cloud.go @@ -18,31 +18,31 @@ import ( func (api *API) InitCloud() { // GET /api/v4/cloud/products - api.BaseRoutes.Cloud.Handle("/products", api.ApiSessionRequired(getCloudProducts)).Methods("GET") + api.BaseRoutes.Cloud.Handle("/products", api.APISessionRequired(getCloudProducts)).Methods("GET") // POST /api/v4/cloud/payment // POST /api/v4/cloud/payment/confirm - api.BaseRoutes.Cloud.Handle("/payment", api.ApiSessionRequired(createCustomerPayment)).Methods("POST") - api.BaseRoutes.Cloud.Handle("/payment/confirm", api.ApiSessionRequired(confirmCustomerPayment)).Methods("POST") + api.BaseRoutes.Cloud.Handle("/payment", api.APISessionRequired(createCustomerPayment)).Methods("POST") + api.BaseRoutes.Cloud.Handle("/payment/confirm", api.APISessionRequired(confirmCustomerPayment)).Methods("POST") // GET /api/v4/cloud/customer // PUT /api/v4/cloud/customer // PUT /api/v4/cloud/customer/address - api.BaseRoutes.Cloud.Handle("/customer", api.ApiSessionRequired(getCloudCustomer)).Methods("GET") - api.BaseRoutes.Cloud.Handle("/customer", api.ApiSessionRequired(updateCloudCustomer)).Methods("PUT") - api.BaseRoutes.Cloud.Handle("/customer/address", api.ApiSessionRequired(updateCloudCustomerAddress)).Methods("PUT") + api.BaseRoutes.Cloud.Handle("/customer", api.APISessionRequired(getCloudCustomer)).Methods("GET") + api.BaseRoutes.Cloud.Handle("/customer", api.APISessionRequired(updateCloudCustomer)).Methods("PUT") + api.BaseRoutes.Cloud.Handle("/customer/address", api.APISessionRequired(updateCloudCustomerAddress)).Methods("PUT") // GET /api/v4/cloud/subscription - api.BaseRoutes.Cloud.Handle("/subscription", api.ApiSessionRequired(getSubscription)).Methods("GET") - api.BaseRoutes.Cloud.Handle("/subscription/invoices", api.ApiSessionRequired(getInvoicesForSubscription)).Methods("GET") - api.BaseRoutes.Cloud.Handle("/subscription/invoices/{invoice_id:in_[A-Za-z0-9]+}/pdf", api.ApiSessionRequired(getSubscriptionInvoicePDF)).Methods("GET") - api.BaseRoutes.Cloud.Handle("/subscription/limitreached/invite", api.ApiSessionRequired(sendAdminUpgradeRequestEmail)).Methods("POST") - api.BaseRoutes.Cloud.Handle("/subscription/limitreached/join", api.ApiHandler(sendAdminUpgradeRequestEmailOnJoin)).Methods("POST") - api.BaseRoutes.Cloud.Handle("/subscription/stats", api.ApiHandler(getSubscriptionStats)).Methods("GET") - api.BaseRoutes.Cloud.Handle("/subscription", api.ApiSessionRequired(changeSubscription)).Methods("PUT") + api.BaseRoutes.Cloud.Handle("/subscription", api.APISessionRequired(getSubscription)).Methods("GET") + api.BaseRoutes.Cloud.Handle("/subscription/invoices", api.APISessionRequired(getInvoicesForSubscription)).Methods("GET") + api.BaseRoutes.Cloud.Handle("/subscription/invoices/{invoice_id:in_[A-Za-z0-9]+}/pdf", api.APISessionRequired(getSubscriptionInvoicePDF)).Methods("GET") + api.BaseRoutes.Cloud.Handle("/subscription/limitreached/invite", api.APISessionRequired(sendAdminUpgradeRequestEmail)).Methods("POST") + api.BaseRoutes.Cloud.Handle("/subscription/limitreached/join", api.APIHandler(sendAdminUpgradeRequestEmailOnJoin)).Methods("POST") + api.BaseRoutes.Cloud.Handle("/subscription/stats", api.APIHandler(getSubscriptionStats)).Methods("GET") + api.BaseRoutes.Cloud.Handle("/subscription", api.APISessionRequired(changeSubscription)).Methods("PUT") // POST /api/v4/cloud/webhook - api.BaseRoutes.Cloud.Handle("/webhook", api.CloudApiKeyRequired(handleCWSWebhook)).Methods("POST") + api.BaseRoutes.Cloud.Handle("/webhook", api.CloudAPIKeyRequired(handleCWSWebhook)).Methods("POST") } func getSubscription(c *Context, w http.ResponseWriter, r *http.Request) { diff --git a/api4/cluster.go b/api4/cluster.go index 44b7788acb..1ee33a46f0 100644 --- a/api4/cluster.go +++ b/api4/cluster.go @@ -10,7 +10,7 @@ import ( ) func (api *API) InitCluster() { - api.BaseRoutes.Cluster.Handle("/status", api.ApiSessionRequired(getClusterStatus)).Methods("GET") + api.BaseRoutes.Cluster.Handle("/status", api.APISessionRequired(getClusterStatus)).Methods("GET") } func getClusterStatus(c *Context, w http.ResponseWriter, r *http.Request) { diff --git a/api4/command.go b/api4/command.go index fd8aff51c3..350caa5018 100644 --- a/api4/command.go +++ b/api4/command.go @@ -15,18 +15,18 @@ import ( ) func (api *API) InitCommand() { - api.BaseRoutes.Commands.Handle("", api.ApiSessionRequired(createCommand)).Methods("POST") - api.BaseRoutes.Commands.Handle("", api.ApiSessionRequired(listCommands)).Methods("GET") - api.BaseRoutes.Commands.Handle("/execute", api.ApiSessionRequired(executeCommand)).Methods("POST") + api.BaseRoutes.Commands.Handle("", api.APISessionRequired(createCommand)).Methods("POST") + api.BaseRoutes.Commands.Handle("", api.APISessionRequired(listCommands)).Methods("GET") + api.BaseRoutes.Commands.Handle("/execute", api.APISessionRequired(executeCommand)).Methods("POST") - api.BaseRoutes.Command.Handle("", api.ApiSessionRequired(getCommand)).Methods("GET") - api.BaseRoutes.Command.Handle("", api.ApiSessionRequired(updateCommand)).Methods("PUT") - api.BaseRoutes.Command.Handle("/move", api.ApiSessionRequired(moveCommand)).Methods("PUT") - api.BaseRoutes.Command.Handle("", api.ApiSessionRequired(deleteCommand)).Methods("DELETE") + api.BaseRoutes.Command.Handle("", api.APISessionRequired(getCommand)).Methods("GET") + api.BaseRoutes.Command.Handle("", api.APISessionRequired(updateCommand)).Methods("PUT") + api.BaseRoutes.Command.Handle("/move", api.APISessionRequired(moveCommand)).Methods("PUT") + api.BaseRoutes.Command.Handle("", api.APISessionRequired(deleteCommand)).Methods("DELETE") - api.BaseRoutes.Team.Handle("/commands/autocomplete", api.ApiSessionRequired(listAutocompleteCommands)).Methods("GET") - api.BaseRoutes.Team.Handle("/commands/autocomplete_suggestions", api.ApiSessionRequired(listCommandAutocompleteSuggestions)).Methods("GET") - api.BaseRoutes.Command.Handle("/regen_token", api.ApiSessionRequired(regenCommandToken)).Methods("PUT") + api.BaseRoutes.Team.Handle("/commands/autocomplete", api.APISessionRequired(listAutocompleteCommands)).Methods("GET") + api.BaseRoutes.Team.Handle("/commands/autocomplete_suggestions", api.APISessionRequired(listCommandAutocompleteSuggestions)).Methods("GET") + api.BaseRoutes.Command.Handle("/regen_token", api.APISessionRequired(regenCommandToken)).Methods("PUT") } func createCommand(c *Context, w http.ResponseWriter, r *http.Request) { diff --git a/api4/command_local.go b/api4/command_local.go index f3b991aad1..fa59673aa2 100644 --- a/api4/command_local.go +++ b/api4/command_local.go @@ -13,13 +13,13 @@ import ( ) func (api *API) InitCommandLocal() { - api.BaseRoutes.Commands.Handle("", api.ApiLocal(localCreateCommand)).Methods("POST") - api.BaseRoutes.Commands.Handle("", api.ApiLocal(listCommands)).Methods("GET") + api.BaseRoutes.Commands.Handle("", api.APILocal(localCreateCommand)).Methods("POST") + api.BaseRoutes.Commands.Handle("", api.APILocal(listCommands)).Methods("GET") - api.BaseRoutes.Command.Handle("", api.ApiLocal(getCommand)).Methods("GET") - api.BaseRoutes.Command.Handle("", api.ApiLocal(updateCommand)).Methods("PUT") - api.BaseRoutes.Command.Handle("/move", api.ApiLocal(moveCommand)).Methods("PUT") - api.BaseRoutes.Command.Handle("", api.ApiLocal(deleteCommand)).Methods("DELETE") + api.BaseRoutes.Command.Handle("", api.APILocal(getCommand)).Methods("GET") + api.BaseRoutes.Command.Handle("", api.APILocal(updateCommand)).Methods("PUT") + api.BaseRoutes.Command.Handle("/move", api.APILocal(moveCommand)).Methods("PUT") + api.BaseRoutes.Command.Handle("", api.APILocal(deleteCommand)).Methods("DELETE") } func localCreateCommand(c *Context, w http.ResponseWriter, r *http.Request) { diff --git a/api4/compliance.go b/api4/compliance.go index 2ca8bac8b0..f45b3de7b5 100644 --- a/api4/compliance.go +++ b/api4/compliance.go @@ -16,10 +16,10 @@ import ( ) func (api *API) InitCompliance() { - api.BaseRoutes.Compliance.Handle("/reports", api.ApiSessionRequired(createComplianceReport)).Methods("POST") - api.BaseRoutes.Compliance.Handle("/reports", api.ApiSessionRequired(getComplianceReports)).Methods("GET") - api.BaseRoutes.Compliance.Handle("/reports/{report_id:[A-Za-z0-9]+}", api.ApiSessionRequired(getComplianceReport)).Methods("GET") - api.BaseRoutes.Compliance.Handle("/reports/{report_id:[A-Za-z0-9]+}/download", api.ApiSessionRequiredTrustRequester(downloadComplianceReport)).Methods("GET") + api.BaseRoutes.Compliance.Handle("/reports", api.APISessionRequired(createComplianceReport)).Methods("POST") + api.BaseRoutes.Compliance.Handle("/reports", api.APISessionRequired(getComplianceReports)).Methods("GET") + api.BaseRoutes.Compliance.Handle("/reports/{report_id:[A-Za-z0-9]+}", api.APISessionRequired(getComplianceReport)).Methods("GET") + api.BaseRoutes.Compliance.Handle("/reports/{report_id:[A-Za-z0-9]+}/download", api.APISessionRequiredTrustRequester(downloadComplianceReport)).Methods("GET") } func createComplianceReport(c *Context, w http.ResponseWriter, r *http.Request) { diff --git a/api4/config.go b/api4/config.go index 6e97b23dd6..cfa66ad61f 100644 --- a/api4/config.go +++ b/api4/config.go @@ -29,13 +29,13 @@ const ( ) func (api *API) InitConfig() { - api.BaseRoutes.ApiRoot.Handle("/config", api.ApiSessionRequired(getConfig)).Methods("GET") - api.BaseRoutes.ApiRoot.Handle("/config", api.ApiSessionRequired(updateConfig)).Methods("PUT") - api.BaseRoutes.ApiRoot.Handle("/config/patch", api.ApiSessionRequired(patchConfig)).Methods("PUT") - api.BaseRoutes.ApiRoot.Handle("/config/reload", api.ApiSessionRequired(configReload)).Methods("POST") - api.BaseRoutes.ApiRoot.Handle("/config/client", api.ApiHandler(getClientConfig)).Methods("GET") - api.BaseRoutes.ApiRoot.Handle("/config/environment", api.ApiSessionRequired(getEnvironmentConfig)).Methods("GET") - api.BaseRoutes.ApiRoot.Handle("/config/migrate", api.ApiSessionRequired(migrateConfig)).Methods("POST") + api.BaseRoutes.APIRoot.Handle("/config", api.APISessionRequired(getConfig)).Methods("GET") + api.BaseRoutes.APIRoot.Handle("/config", api.APISessionRequired(updateConfig)).Methods("PUT") + api.BaseRoutes.APIRoot.Handle("/config/patch", api.APISessionRequired(patchConfig)).Methods("PUT") + api.BaseRoutes.APIRoot.Handle("/config/reload", api.APISessionRequired(configReload)).Methods("POST") + api.BaseRoutes.APIRoot.Handle("/config/client", api.APIHandler(getClientConfig)).Methods("GET") + api.BaseRoutes.APIRoot.Handle("/config/environment", api.APISessionRequired(getEnvironmentConfig)).Methods("GET") + api.BaseRoutes.APIRoot.Handle("/config/migrate", api.APISessionRequired(migrateConfig)).Methods("POST") } func init() { diff --git a/api4/config_local.go b/api4/config_local.go index c807a1f315..ffb539b710 100644 --- a/api4/config_local.go +++ b/api4/config_local.go @@ -16,10 +16,10 @@ import ( ) func (api *API) InitConfigLocal() { - api.BaseRoutes.ApiRoot.Handle("/config", api.ApiLocal(localGetConfig)).Methods("GET") - api.BaseRoutes.ApiRoot.Handle("/config", api.ApiLocal(localUpdateConfig)).Methods("PUT") - api.BaseRoutes.ApiRoot.Handle("/config/patch", api.ApiLocal(localPatchConfig)).Methods("PUT") - api.BaseRoutes.ApiRoot.Handle("/config/migrate", api.ApiLocal(migrateConfig)).Methods("POST") + api.BaseRoutes.APIRoot.Handle("/config", api.APILocal(localGetConfig)).Methods("GET") + api.BaseRoutes.APIRoot.Handle("/config", api.APILocal(localUpdateConfig)).Methods("PUT") + api.BaseRoutes.APIRoot.Handle("/config/patch", api.APILocal(localPatchConfig)).Methods("PUT") + api.BaseRoutes.APIRoot.Handle("/config/migrate", api.APILocal(migrateConfig)).Methods("POST") } func localGetConfig(c *Context, w http.ResponseWriter, r *http.Request) { diff --git a/api4/config_test.go b/api4/config_test.go index 9af91b34cf..53e9cf3405 100644 --- a/api4/config_test.go +++ b/api4/config_test.go @@ -170,7 +170,7 @@ func TestUpdateConfig(t *testing.T) { require.Equal(t, SiteName, cfg.TeamSettings.SiteName, "It should update the SiteName") t.Run("Should set defaults for missing fields", func(t *testing.T) { - _, err = th.SystemAdminClient.DoApiPut("/config", "{}") + _, err = th.SystemAdminClient.DoAPIPut("/config", "{}") require.NoError(t, err) }) @@ -584,7 +584,7 @@ func TestGetOldClientConfig(t *testing.T) { t.Run("missing format", func(t *testing.T) { client := th.Client - resp, err := client.DoApiGet("/config/client", "") + resp, err := client.DoAPIGet("/config/client", "") require.Error(t, err) require.Equal(t, http.StatusNotImplemented, resp.StatusCode) }) @@ -592,7 +592,7 @@ func TestGetOldClientConfig(t *testing.T) { t.Run("invalid format", func(t *testing.T) { client := th.Client - resp, err := client.DoApiGet("/config/client?format=junk", "") + resp, err := client.DoAPIGet("/config/client?format=junk", "") require.Error(t, err) require.Equal(t, http.StatusBadRequest, resp.StatusCode) }) diff --git a/api4/data_retention.go b/api4/data_retention.go index cae7786a92..b11f89f3fe 100644 --- a/api4/data_retention.go +++ b/api4/data_retention.go @@ -12,23 +12,23 @@ import ( ) func (api *API) InitDataRetention() { - api.BaseRoutes.DataRetention.Handle("/policy", api.ApiSessionRequired(getGlobalPolicy)).Methods("GET") - api.BaseRoutes.DataRetention.Handle("/policies", api.ApiSessionRequired(getPolicies)).Methods("GET") - api.BaseRoutes.DataRetention.Handle("/policies_count", api.ApiSessionRequired(getPoliciesCount)).Methods("GET") - api.BaseRoutes.DataRetention.Handle("/policies", api.ApiSessionRequired(createPolicy)).Methods("POST") - api.BaseRoutes.DataRetention.Handle("/policies/{policy_id:[A-Za-z0-9]+}", api.ApiSessionRequired(getPolicy)).Methods("GET") - api.BaseRoutes.DataRetention.Handle("/policies/{policy_id:[A-Za-z0-9]+}", api.ApiSessionRequired(patchPolicy)).Methods("PATCH") - api.BaseRoutes.DataRetention.Handle("/policies/{policy_id:[A-Za-z0-9]+}", api.ApiSessionRequired(deletePolicy)).Methods("DELETE") - api.BaseRoutes.DataRetention.Handle("/policies/{policy_id:[A-Za-z0-9]+}/teams", api.ApiSessionRequired(getTeamsForPolicy)).Methods("GET") - api.BaseRoutes.DataRetention.Handle("/policies/{policy_id:[A-Za-z0-9]+}/teams", api.ApiSessionRequired(addTeamsToPolicy)).Methods("POST") - api.BaseRoutes.DataRetention.Handle("/policies/{policy_id:[A-Za-z0-9]+}/teams", api.ApiSessionRequired(removeTeamsFromPolicy)).Methods("DELETE") - api.BaseRoutes.DataRetention.Handle("/policies/{policy_id:[A-Za-z0-9]+}/teams/search", api.ApiSessionRequired(searchTeamsInPolicy)).Methods("POST") - api.BaseRoutes.DataRetention.Handle("/policies/{policy_id:[A-Za-z0-9]+}/channels", api.ApiSessionRequired(getChannelsForPolicy)).Methods("GET") - api.BaseRoutes.DataRetention.Handle("/policies/{policy_id:[A-Za-z0-9]+}/channels", api.ApiSessionRequired(addChannelsToPolicy)).Methods("POST") - api.BaseRoutes.DataRetention.Handle("/policies/{policy_id:[A-Za-z0-9]+}/channels", api.ApiSessionRequired(removeChannelsFromPolicy)).Methods("DELETE") - api.BaseRoutes.DataRetention.Handle("/policies/{policy_id:[A-Za-z0-9]+}/channels/search", api.ApiSessionRequired(searchChannelsInPolicy)).Methods("POST") - api.BaseRoutes.User.Handle("/data_retention/team_policies", api.ApiSessionRequired(getTeamPoliciesForUser)).Methods("GET") - api.BaseRoutes.User.Handle("/data_retention/channel_policies", api.ApiSessionRequired(getChannelPoliciesForUser)).Methods("GET") + api.BaseRoutes.DataRetention.Handle("/policy", api.APISessionRequired(getGlobalPolicy)).Methods("GET") + api.BaseRoutes.DataRetention.Handle("/policies", api.APISessionRequired(getPolicies)).Methods("GET") + api.BaseRoutes.DataRetention.Handle("/policies_count", api.APISessionRequired(getPoliciesCount)).Methods("GET") + api.BaseRoutes.DataRetention.Handle("/policies", api.APISessionRequired(createPolicy)).Methods("POST") + api.BaseRoutes.DataRetention.Handle("/policies/{policy_id:[A-Za-z0-9]+}", api.APISessionRequired(getPolicy)).Methods("GET") + api.BaseRoutes.DataRetention.Handle("/policies/{policy_id:[A-Za-z0-9]+}", api.APISessionRequired(patchPolicy)).Methods("PATCH") + api.BaseRoutes.DataRetention.Handle("/policies/{policy_id:[A-Za-z0-9]+}", api.APISessionRequired(deletePolicy)).Methods("DELETE") + api.BaseRoutes.DataRetention.Handle("/policies/{policy_id:[A-Za-z0-9]+}/teams", api.APISessionRequired(getTeamsForPolicy)).Methods("GET") + api.BaseRoutes.DataRetention.Handle("/policies/{policy_id:[A-Za-z0-9]+}/teams", api.APISessionRequired(addTeamsToPolicy)).Methods("POST") + api.BaseRoutes.DataRetention.Handle("/policies/{policy_id:[A-Za-z0-9]+}/teams", api.APISessionRequired(removeTeamsFromPolicy)).Methods("DELETE") + api.BaseRoutes.DataRetention.Handle("/policies/{policy_id:[A-Za-z0-9]+}/teams/search", api.APISessionRequired(searchTeamsInPolicy)).Methods("POST") + api.BaseRoutes.DataRetention.Handle("/policies/{policy_id:[A-Za-z0-9]+}/channels", api.APISessionRequired(getChannelsForPolicy)).Methods("GET") + api.BaseRoutes.DataRetention.Handle("/policies/{policy_id:[A-Za-z0-9]+}/channels", api.APISessionRequired(addChannelsToPolicy)).Methods("POST") + api.BaseRoutes.DataRetention.Handle("/policies/{policy_id:[A-Za-z0-9]+}/channels", api.APISessionRequired(removeChannelsFromPolicy)).Methods("DELETE") + api.BaseRoutes.DataRetention.Handle("/policies/{policy_id:[A-Za-z0-9]+}/channels/search", api.APISessionRequired(searchChannelsInPolicy)).Methods("POST") + api.BaseRoutes.User.Handle("/data_retention/team_policies", api.APISessionRequired(getTeamPoliciesForUser)).Methods("GET") + api.BaseRoutes.User.Handle("/data_retention/channel_policies", api.APISessionRequired(getChannelPoliciesForUser)).Methods("GET") } func getGlobalPolicy(c *Context, w http.ResponseWriter, r *http.Request) { diff --git a/api4/elasticsearch.go b/api4/elasticsearch.go index c77e2ed4e2..9e940cdf80 100644 --- a/api4/elasticsearch.go +++ b/api4/elasticsearch.go @@ -11,8 +11,8 @@ import ( ) func (api *API) InitElasticsearch() { - api.BaseRoutes.Elasticsearch.Handle("/test", api.ApiSessionRequired(testElasticsearch)).Methods("POST") - api.BaseRoutes.Elasticsearch.Handle("/purge_indexes", api.ApiSessionRequired(purgeElasticsearchIndexes)).Methods("POST") + api.BaseRoutes.Elasticsearch.Handle("/test", api.APISessionRequired(testElasticsearch)).Methods("POST") + api.BaseRoutes.Elasticsearch.Handle("/purge_indexes", api.APISessionRequired(purgeElasticsearchIndexes)).Methods("POST") } func testElasticsearch(c *Context, w http.ResponseWriter, r *http.Request) { diff --git a/api4/emoji.go b/api4/emoji.go index b8a7b4a396..fba90b3c0d 100644 --- a/api4/emoji.go +++ b/api4/emoji.go @@ -22,14 +22,14 @@ const ( ) func (api *API) InitEmoji() { - api.BaseRoutes.Emojis.Handle("", api.ApiSessionRequired(createEmoji)).Methods("POST") - api.BaseRoutes.Emojis.Handle("", api.ApiSessionRequired(getEmojiList)).Methods("GET") - api.BaseRoutes.Emojis.Handle("/search", api.ApiSessionRequired(searchEmojis)).Methods("POST") - api.BaseRoutes.Emojis.Handle("/autocomplete", api.ApiSessionRequired(autocompleteEmojis)).Methods("GET") - api.BaseRoutes.Emoji.Handle("", api.ApiSessionRequired(deleteEmoji)).Methods("DELETE") - api.BaseRoutes.Emoji.Handle("", api.ApiSessionRequired(getEmoji)).Methods("GET") - api.BaseRoutes.EmojiByName.Handle("", api.ApiSessionRequired(getEmojiByName)).Methods("GET") - api.BaseRoutes.Emoji.Handle("/image", api.ApiSessionRequiredTrustRequester(getEmojiImage)).Methods("GET") + api.BaseRoutes.Emojis.Handle("", api.APISessionRequired(createEmoji)).Methods("POST") + api.BaseRoutes.Emojis.Handle("", api.APISessionRequired(getEmojiList)).Methods("GET") + api.BaseRoutes.Emojis.Handle("/search", api.APISessionRequired(searchEmojis)).Methods("POST") + api.BaseRoutes.Emojis.Handle("/autocomplete", api.APISessionRequired(autocompleteEmojis)).Methods("GET") + api.BaseRoutes.Emoji.Handle("", api.APISessionRequired(deleteEmoji)).Methods("DELETE") + api.BaseRoutes.Emoji.Handle("", api.APISessionRequired(getEmoji)).Methods("GET") + api.BaseRoutes.EmojiByName.Handle("", api.APISessionRequired(getEmojiByName)).Methods("GET") + api.BaseRoutes.Emoji.Handle("/image", api.APISessionRequiredTrustRequester(getEmojiImage)).Methods("GET") } func createEmoji(c *Context, w http.ResponseWriter, r *http.Request) { @@ -111,7 +111,7 @@ func getEmojiList(c *Context, w http.ResponseWriter, r *http.Request) { sort := r.URL.Query().Get("sort") if sort != "" && sort != model.EmojiSortByName { - c.SetInvalidUrlParam("sort") + c.SetInvalidURLParam("sort") return } @@ -281,7 +281,7 @@ func autocompleteEmojis(c *Context, w http.ResponseWriter, r *http.Request) { name := r.URL.Query().Get("name") if name == "" { - c.SetInvalidUrlParam("name") + c.SetInvalidURLParam("name") return } diff --git a/api4/export.go b/api4/export.go index 3b1e6f212c..823a8f4b27 100644 --- a/api4/export.go +++ b/api4/export.go @@ -14,9 +14,9 @@ import ( ) func (api *API) InitExport() { - api.BaseRoutes.Exports.Handle("", api.ApiSessionRequired(listExports)).Methods("GET") - api.BaseRoutes.Export.Handle("", api.ApiSessionRequired(deleteExport)).Methods("DELETE") - api.BaseRoutes.Export.Handle("", api.ApiSessionRequired(downloadExport)).Methods("GET") + api.BaseRoutes.Exports.Handle("", api.APISessionRequired(listExports)).Methods("GET") + api.BaseRoutes.Export.Handle("", api.APISessionRequired(deleteExport)).Methods("DELETE") + api.BaseRoutes.Export.Handle("", api.APISessionRequired(downloadExport)).Methods("GET") } func listExports(c *Context, w http.ResponseWriter, r *http.Request) { diff --git a/api4/export_local.go b/api4/export_local.go index b3a243abbc..0f1008dbc1 100644 --- a/api4/export_local.go +++ b/api4/export_local.go @@ -4,7 +4,7 @@ package api4 func (api *API) InitExportLocal() { - api.BaseRoutes.Exports.Handle("", api.ApiLocal(listExports)).Methods("GET") - api.BaseRoutes.Export.Handle("", api.ApiLocal(deleteExport)).Methods("DELETE") - api.BaseRoutes.Export.Handle("", api.ApiLocal(downloadExport)).Methods("GET") + api.BaseRoutes.Exports.Handle("", api.APILocal(listExports)).Methods("GET") + api.BaseRoutes.Export.Handle("", api.APILocal(deleteExport)).Methods("DELETE") + api.BaseRoutes.Export.Handle("", api.APILocal(downloadExport)).Methods("GET") } diff --git a/api4/file.go b/api4/file.go index 98140d168e..dcbd71e2ca 100644 --- a/api4/file.go +++ b/api4/file.go @@ -55,16 +55,16 @@ var MediaContentTypes = [...]string{ const maxMultipartFormDataBytes = 10 * 1024 // 10Kb func (api *API) InitFile() { - api.BaseRoutes.Files.Handle("", api.ApiSessionRequired(uploadFileStream)).Methods("POST") - api.BaseRoutes.File.Handle("", api.ApiSessionRequiredTrustRequester(getFile)).Methods("GET") - api.BaseRoutes.File.Handle("/thumbnail", api.ApiSessionRequiredTrustRequester(getFileThumbnail)).Methods("GET") - api.BaseRoutes.File.Handle("/link", api.ApiSessionRequired(getFileLink)).Methods("GET") - api.BaseRoutes.File.Handle("/preview", api.ApiSessionRequiredTrustRequester(getFilePreview)).Methods("GET") - api.BaseRoutes.File.Handle("/info", api.ApiSessionRequired(getFileInfo)).Methods("GET") + api.BaseRoutes.Files.Handle("", api.APISessionRequired(uploadFileStream)).Methods("POST") + api.BaseRoutes.File.Handle("", api.APISessionRequiredTrustRequester(getFile)).Methods("GET") + api.BaseRoutes.File.Handle("/thumbnail", api.APISessionRequiredTrustRequester(getFileThumbnail)).Methods("GET") + api.BaseRoutes.File.Handle("/link", api.APISessionRequired(getFileLink)).Methods("GET") + api.BaseRoutes.File.Handle("/preview", api.APISessionRequiredTrustRequester(getFilePreview)).Methods("GET") + api.BaseRoutes.File.Handle("/info", api.APISessionRequired(getFileInfo)).Methods("GET") - api.BaseRoutes.Team.Handle("/files/search", api.ApiSessionRequiredDisableWhenBusy(searchFiles)).Methods("POST") + api.BaseRoutes.Team.Handle("/files/search", api.APISessionRequiredDisableWhenBusy(searchFiles)).Methods("POST") - api.BaseRoutes.PublicFile.Handle("", api.ApiHandler(getPublicFile)).Methods("GET") + api.BaseRoutes.PublicFile.Handle("", api.APIHandler(getPublicFile)).Methods("GET") } diff --git a/api4/file_test.go b/api4/file_test.go index 94719d0d19..19dc24faab 100644 --- a/api4/file_test.go +++ b/api4/file_test.go @@ -60,7 +60,7 @@ func fileBytes(t *testing.T, path string) []byte { func testDoUploadFileRequest(t testing.TB, c *model.Client4, url string, blob []byte, contentType string, contentLength int64) (*model.FileUploadResponse, *model.Response, error) { - req, err := http.NewRequest("POST", c.ApiUrl+"/files"+url, bytes.NewReader(blob)) + req, err := http.NewRequest("POST", c.APIURL+"/files"+url, bytes.NewReader(blob)) require.NoError(t, err) if contentLength != 0 { @@ -1049,7 +1049,7 @@ func TestGetPublicFile(t *testing.T) { info, err := th.App.Srv().Store.FileInfo().Get(fileId) require.NoError(t, err) - link := th.App.GeneratePublicLink(client.Url, info) + link := th.App.GeneratePublicLink(client.URL, info) resp, err := http.Get(link) require.NoError(t, err) @@ -1082,7 +1082,7 @@ func TestGetPublicFile(t *testing.T) { require.NoError(t, th.cleanupTestFile(fileInfo)) th.cleanupTestFile(info) - link = th.App.GeneratePublicLink(client.Url, info) + link = th.App.GeneratePublicLink(client.URL, info) resp, err = http.Get(link) require.NoError(t, err) require.Equal(t, http.StatusNotFound, resp.StatusCode, "should've failed to get file after it is deleted") diff --git a/api4/group.go b/api4/group.go index a8773bf689..6dd83ebe33 100644 --- a/api4/group.go +++ b/api4/group.go @@ -17,64 +17,64 @@ import ( func (api *API) InitGroup() { // GET /api/v4/groups - api.BaseRoutes.Groups.Handle("", api.ApiSessionRequired(getGroups)).Methods("GET") + api.BaseRoutes.Groups.Handle("", api.APISessionRequired(getGroups)).Methods("GET") // GET /api/v4/groups/:group_id api.BaseRoutes.Groups.Handle("/{group_id:[A-Za-z0-9]+}", - api.ApiSessionRequired(getGroup)).Methods("GET") + api.APISessionRequired(getGroup)).Methods("GET") // PUT /api/v4/groups/:group_id/patch api.BaseRoutes.Groups.Handle("/{group_id:[A-Za-z0-9]+}/patch", - api.ApiSessionRequired(patchGroup)).Methods("PUT") + api.APISessionRequired(patchGroup)).Methods("PUT") // POST /api/v4/groups/:group_id/teams/:team_id/link // POST /api/v4/groups/:group_id/channels/:channel_id/link api.BaseRoutes.Groups.Handle("/{group_id:[A-Za-z0-9]+}/{syncable_type:teams|channels}/{syncable_id:[A-Za-z0-9]+}/link", - api.ApiSessionRequired(linkGroupSyncable)).Methods("POST") + api.APISessionRequired(linkGroupSyncable)).Methods("POST") // DELETE /api/v4/groups/:group_id/teams/:team_id/link // DELETE /api/v4/groups/:group_id/channels/:channel_id/link api.BaseRoutes.Groups.Handle("/{group_id:[A-Za-z0-9]+}/{syncable_type:teams|channels}/{syncable_id:[A-Za-z0-9]+}/link", - api.ApiSessionRequired(unlinkGroupSyncable)).Methods("DELETE") + api.APISessionRequired(unlinkGroupSyncable)).Methods("DELETE") // GET /api/v4/groups/:group_id/teams/:team_id // GET /api/v4/groups/:group_id/channels/:channel_id api.BaseRoutes.Groups.Handle("/{group_id:[A-Za-z0-9]+}/{syncable_type:teams|channels}/{syncable_id:[A-Za-z0-9]+}", - api.ApiSessionRequired(getGroupSyncable)).Methods("GET") + api.APISessionRequired(getGroupSyncable)).Methods("GET") // GET /api/v4/groups/:group_id/teams // GET /api/v4/groups/:group_id/channels api.BaseRoutes.Groups.Handle("/{group_id:[A-Za-z0-9]+}/{syncable_type:teams|channels}", - api.ApiSessionRequired(getGroupSyncables)).Methods("GET") + api.APISessionRequired(getGroupSyncables)).Methods("GET") // PUT /api/v4/groups/:group_id/teams/:team_id/patch // PUT /api/v4/groups/:group_id/channels/:channel_id/patch api.BaseRoutes.Groups.Handle("/{group_id:[A-Za-z0-9]+}/{syncable_type:teams|channels}/{syncable_id:[A-Za-z0-9]+}/patch", - api.ApiSessionRequired(patchGroupSyncable)).Methods("PUT") + api.APISessionRequired(patchGroupSyncable)).Methods("PUT") // GET /api/v4/groups/:group_id/stats api.BaseRoutes.Groups.Handle("/{group_id:[A-Za-z0-9]+}/stats", - api.ApiSessionRequired(getGroupStats)).Methods("GET") + api.APISessionRequired(getGroupStats)).Methods("GET") // GET /api/v4/groups/:group_id/members?page=0&per_page=100 api.BaseRoutes.Groups.Handle("/{group_id:[A-Za-z0-9]+}/members", - api.ApiSessionRequired(getGroupMembers)).Methods("GET") + api.APISessionRequired(getGroupMembers)).Methods("GET") // GET /api/v4/users/:user_id/groups?page=0&per_page=100 api.BaseRoutes.Users.Handle("/{user_id:[A-Za-z0-9]+}/groups", - api.ApiSessionRequired(getGroupsByUserId)).Methods("GET") + api.APISessionRequired(getGroupsByUserId)).Methods("GET") // GET /api/v4/channels/:channel_id/groups?page=0&per_page=100 api.BaseRoutes.Channels.Handle("/{channel_id:[A-Za-z0-9]+}/groups", - api.ApiSessionRequired(getGroupsByChannel)).Methods("GET") + api.APISessionRequired(getGroupsByChannel)).Methods("GET") // GET /api/v4/teams/:team_id/groups?page=0&per_page=100 api.BaseRoutes.Teams.Handle("/{team_id:[A-Za-z0-9]+}/groups", - api.ApiSessionRequired(getGroupsByTeam)).Methods("GET") + api.APISessionRequired(getGroupsByTeam)).Methods("GET") // GET /api/v4/teams/:team_id/groups_by_channels?page=0&per_page=100 api.BaseRoutes.Teams.Handle("/{team_id:[A-Za-z0-9]+}/groups_by_channels", - api.ApiSessionRequired(getGroupsAssociatedToChannelsByTeam)).Methods("GET") + api.APISessionRequired(getGroupsAssociatedToChannelsByTeam)).Methods("GET") } func getGroup(c *Context, w http.ResponseWriter, r *http.Request) { diff --git a/api4/group_local.go b/api4/group_local.go index 03ab55c490..5ede4d7bf3 100644 --- a/api4/group_local.go +++ b/api4/group_local.go @@ -4,6 +4,6 @@ package api4 func (api *API) InitGroupLocal() { - api.BaseRoutes.Channels.Handle("/{channel_id:[A-Za-z0-9]+}/groups", api.ApiLocal(getGroupsByChannel)).Methods("GET") - api.BaseRoutes.Teams.Handle("/{team_id:[A-Za-z0-9]+}/groups", api.ApiLocal(getGroupsByTeam)).Methods("GET") + api.BaseRoutes.Channels.Handle("/{channel_id:[A-Za-z0-9]+}/groups", api.APILocal(getGroupsByChannel)).Methods("GET") + api.BaseRoutes.Teams.Handle("/{team_id:[A-Za-z0-9]+}/groups", api.APILocal(getGroupsByTeam)).Methods("GET") } diff --git a/api4/handlers.go b/api4/handlers.go index 60d453c80a..5feba026e4 100644 --- a/api4/handlers.go +++ b/api4/handlers.go @@ -13,9 +13,9 @@ import ( type Context = web.Context -// ApiHandler provides a handler for API endpoints which do not require the user to be logged in order for access to be +// APIHandler provides a handler for API endpoints which do not require the user to be logged in order for access to be // granted. -func (api *API) ApiHandler(h func(*Context, http.ResponseWriter, *http.Request)) http.Handler { +func (api *API) APIHandler(h func(*Context, http.ResponseWriter, *http.Request)) http.Handler { handler := &web.Handler{ App: api.app, HandleFunc: h, @@ -32,9 +32,9 @@ func (api *API) ApiHandler(h func(*Context, http.ResponseWriter, *http.Request)) return handler } -// ApiSessionRequired provides a handler for API endpoints which require the user to be logged in in order for access to +// APISessionRequired provides a handler for API endpoints which require the user to be logged in in order for access to // be granted. -func (api *API) ApiSessionRequired(h func(*Context, http.ResponseWriter, *http.Request)) http.Handler { +func (api *API) APISessionRequired(h func(*Context, http.ResponseWriter, *http.Request)) http.Handler { handler := &web.Handler{ App: api.app, HandleFunc: h, @@ -52,8 +52,8 @@ func (api *API) ApiSessionRequired(h func(*Context, http.ResponseWriter, *http.R } -// CloudApiKeyRequired provides a handler for webhook endpoints to access Cloud installations from CWS -func (api *API) CloudApiKeyRequired(h func(*Context, http.ResponseWriter, *http.Request)) http.Handler { +// CloudAPIKeyRequired provides a handler for webhook endpoints to access Cloud installations from CWS +func (api *API) CloudAPIKeyRequired(h func(*Context, http.ResponseWriter, *http.Request)) http.Handler { handler := &web.Handler{ App: api.app, HandleFunc: h, @@ -92,10 +92,10 @@ func (api *API) RemoteClusterTokenRequired(h func(*Context, http.ResponseWriter, return handler } -// ApiSessionRequiredMfa provides a handler for API endpoints which require a logged-in user session but when accessed, +// APISessionRequiredMfa provides a handler for API endpoints which require a logged-in user session but when accessed, // if MFA is enabled, the MFA process is not yet complete, and therefore the requirement to have completed the MFA // authentication must be waived. -func (api *API) ApiSessionRequiredMfa(h func(*Context, http.ResponseWriter, *http.Request)) http.Handler { +func (api *API) APISessionRequiredMfa(h func(*Context, http.ResponseWriter, *http.Request)) http.Handler { handler := &web.Handler{ App: api.app, HandleFunc: h, @@ -113,10 +113,10 @@ func (api *API) ApiSessionRequiredMfa(h func(*Context, http.ResponseWriter, *htt } -// ApiHandlerTrustRequester provides a handler for API endpoints which do not require the user to be logged in and are +// APIHandlerTrustRequester provides a handler for API endpoints which do not require the user to be logged in and are // allowed to be requested directly rather than via javascript/XMLHttpRequest, such as site branding images or the // websocket. -func (api *API) ApiHandlerTrustRequester(h func(*Context, http.ResponseWriter, *http.Request)) http.Handler { +func (api *API) APIHandlerTrustRequester(h func(*Context, http.ResponseWriter, *http.Request)) http.Handler { handler := &web.Handler{ App: api.app, HandleFunc: h, @@ -134,9 +134,9 @@ func (api *API) ApiHandlerTrustRequester(h func(*Context, http.ResponseWriter, * } -// ApiSessionRequiredTrustRequester provides a handler for API endpoints which do require the user to be logged in and +// APISessionRequiredTrustRequester provides a handler for API endpoints which do require the user to be logged in and // are allowed to be requested directly rather than via javascript/XMLHttpRequest, such as emoji or file uploads. -func (api *API) ApiSessionRequiredTrustRequester(h func(*Context, http.ResponseWriter, *http.Request)) http.Handler { +func (api *API) APISessionRequiredTrustRequester(h func(*Context, http.ResponseWriter, *http.Request)) http.Handler { handler := &web.Handler{ App: api.app, HandleFunc: h, @@ -156,7 +156,7 @@ func (api *API) ApiSessionRequiredTrustRequester(h func(*Context, http.ResponseW // DisableWhenBusy provides a handler for API endpoints which should be disabled when the server is under load, // responding with HTTP 503 (Service Unavailable). -func (api *API) ApiSessionRequiredDisableWhenBusy(h func(*Context, http.ResponseWriter, *http.Request)) http.Handler { +func (api *API) APISessionRequiredDisableWhenBusy(h func(*Context, http.ResponseWriter, *http.Request)) http.Handler { handler := &web.Handler{ App: api.app, HandleFunc: h, @@ -175,11 +175,11 @@ func (api *API) ApiSessionRequiredDisableWhenBusy(h func(*Context, http.Response } -// ApiLocal provides a handler for API endpoints to be used in local +// APILocal provides a handler for API endpoints to be used in local // mode, this is, through a UNIX socket and without an authenticated // session, but with one that has no user set and no permission // restrictions -func (api *API) ApiLocal(h func(*Context, http.ResponseWriter, *http.Request)) http.Handler { +func (api *API) APILocal(h func(*Context, http.ResponseWriter, *http.Request)) http.Handler { handler := &web.Handler{ App: api.app, HandleFunc: h, diff --git a/api4/handlers_test.go b/api4/handlers_test.go index b30dab112d..14147ccd7e 100644 --- a/api4/handlers_test.go +++ b/api4/handlers_test.go @@ -74,20 +74,20 @@ func TestAPIHandlersWithGzip(t *testing.T) { t.Run("with WebserverMode == \"gzip\"", func(t *testing.T) { th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.WebserverMode = "gzip" }) - testAPIHandlerGzipMode(t, "ApiHandler", api.ApiHandler(handlerForGzip), "") - testAPIHandlerGzipMode(t, "ApiSessionRequired", api.ApiSessionRequired(handlerForGzip), session.Token) - testAPIHandlerGzipMode(t, "ApiSessionRequiredMfa", api.ApiSessionRequiredMfa(handlerForGzip), session.Token) - testAPIHandlerGzipMode(t, "ApiHandlerTrustRequester", api.ApiHandlerTrustRequester(handlerForGzip), "") - testAPIHandlerGzipMode(t, "ApiSessionRequiredTrustRequester", api.ApiSessionRequiredTrustRequester(handlerForGzip), session.Token) + testAPIHandlerGzipMode(t, "ApiHandler", api.APIHandler(handlerForGzip), "") + testAPIHandlerGzipMode(t, "ApiSessionRequired", api.APISessionRequired(handlerForGzip), session.Token) + testAPIHandlerGzipMode(t, "ApiSessionRequiredMfa", api.APISessionRequiredMfa(handlerForGzip), session.Token) + testAPIHandlerGzipMode(t, "ApiHandlerTrustRequester", api.APIHandlerTrustRequester(handlerForGzip), "") + testAPIHandlerGzipMode(t, "ApiSessionRequiredTrustRequester", api.APISessionRequiredTrustRequester(handlerForGzip), session.Token) }) t.Run("with WebserverMode == \"nogzip\"", func(t *testing.T) { th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.WebserverMode = "nogzip" }) - testAPIHandlerNoGzipMode(t, "ApiHandler", api.ApiHandler(handlerForGzip), "") - testAPIHandlerNoGzipMode(t, "ApiSessionRequired", api.ApiSessionRequired(handlerForGzip), session.Token) - testAPIHandlerNoGzipMode(t, "ApiSessionRequiredMfa", api.ApiSessionRequiredMfa(handlerForGzip), session.Token) - testAPIHandlerNoGzipMode(t, "ApiHandlerTrustRequester", api.ApiHandlerTrustRequester(handlerForGzip), "") - testAPIHandlerNoGzipMode(t, "ApiSessionRequiredTrustRequester", api.ApiSessionRequiredTrustRequester(handlerForGzip), session.Token) + testAPIHandlerNoGzipMode(t, "ApiHandler", api.APIHandler(handlerForGzip), "") + testAPIHandlerNoGzipMode(t, "ApiSessionRequired", api.APISessionRequired(handlerForGzip), session.Token) + testAPIHandlerNoGzipMode(t, "ApiSessionRequiredMfa", api.APISessionRequiredMfa(handlerForGzip), session.Token) + testAPIHandlerNoGzipMode(t, "ApiHandlerTrustRequester", api.APIHandlerTrustRequester(handlerForGzip), "") + testAPIHandlerNoGzipMode(t, "ApiSessionRequiredTrustRequester", api.APISessionRequiredTrustRequester(handlerForGzip), session.Token) }) } diff --git a/api4/image.go b/api4/image.go index 10491d59ba..f6f67cd516 100644 --- a/api4/image.go +++ b/api4/image.go @@ -11,7 +11,7 @@ import ( ) func (api *API) InitImage() { - api.BaseRoutes.Image.Handle("", api.ApiSessionRequiredTrustRequester(getImage)).Methods("GET") + api.BaseRoutes.Image.Handle("", api.APISessionRequiredTrustRequester(getImage)).Methods("GET") } func getImage(c *Context, w http.ResponseWriter, r *http.Request) { diff --git a/api4/image_test.go b/api4/image_test.go index 47e479a073..aead2b5bf0 100644 --- a/api4/image_test.go +++ b/api4/image_test.go @@ -33,7 +33,7 @@ func TestGetImage(t *testing.T) { cfg.ImageProxySettings.Enable = model.NewBool(false) }) - r, err := http.NewRequest("GET", th.Client.ApiUrl+"/image?url="+url.QueryEscape(imageURL), nil) + r, err := http.NewRequest("GET", th.Client.APIURL+"/image?url="+url.QueryEscape(imageURL), nil) require.NoError(t, err) r.Header.Set(model.HeaderAuth, th.Client.AuthType+" "+th.Client.AuthToken) @@ -54,7 +54,7 @@ func TestGetImage(t *testing.T) { cfg.ImageProxySettings.RemoteImageProxyURL = model.NewString("https://proxy.foo.bar") }) - r, err := http.NewRequest("GET", th.Client.ApiUrl+"/image?url="+url.QueryEscape(imageURL), nil) + r, err := http.NewRequest("GET", th.Client.APIURL+"/image?url="+url.QueryEscape(imageURL), nil) require.NoError(t, err) r.Header.Set(model.HeaderAuth, th.Client.AuthType+" "+th.Client.AuthToken) @@ -81,7 +81,7 @@ func TestGetImage(t *testing.T) { imageServer := httptest.NewServer(handler) defer imageServer.Close() - r, err := http.NewRequest("GET", th.Client.ApiUrl+"/image?url="+url.QueryEscape(imageServer.URL+"/image.png"), nil) + r, err := http.NewRequest("GET", th.Client.APIURL+"/image?url="+url.QueryEscape(imageServer.URL+"/image.png"), nil) require.NoError(t, err) r.Header.Set(model.HeaderAuth, th.Client.AuthType+" "+th.Client.AuthToken) @@ -94,7 +94,7 @@ func TestGetImage(t *testing.T) { assert.Equal(t, "success", string(respBody)) // local images should not be proxied, but forwarded - r, err = http.NewRequest("GET", th.Client.ApiUrl+"/image?url=/plugins/test/image.png", nil) + r, err = http.NewRequest("GET", th.Client.APIURL+"/image?url=/plugins/test/image.png", nil) require.NoError(t, err) r.Header.Set(model.HeaderAuth, th.Client.AuthType+" "+th.Client.AuthToken) @@ -106,7 +106,7 @@ func TestGetImage(t *testing.T) { th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.SiteURL = model.NewString("http://foo.com") }) - r, err = http.NewRequest("GET", th.Client.ApiUrl+"/image?url="+strings.TrimPrefix(imageServer.URL, "http:")+"/image.png", nil) + r, err = http.NewRequest("GET", th.Client.APIURL+"/image?url="+strings.TrimPrefix(imageServer.URL, "http:")+"/image.png", nil) require.NoError(t, err) r.Header.Set(model.HeaderAuth, th.Client.AuthType+" "+th.Client.AuthToken) @@ -115,7 +115,7 @@ func TestGetImage(t *testing.T) { assert.Equal(t, http.StatusOK, resp.StatusCode) // opaque URLs are not supported, should return an error - r, err = http.NewRequest("GET", th.Client.ApiUrl+"/image?url=mailto:test@example.com", nil) + r, err = http.NewRequest("GET", th.Client.APIURL+"/image?url=mailto:test@example.com", nil) require.NoError(t, err) r.Header.Set(model.HeaderAuth, th.Client.AuthType+" "+th.Client.AuthToken) diff --git a/api4/import.go b/api4/import.go index 5b64279316..bbb7784f5e 100644 --- a/api4/import.go +++ b/api4/import.go @@ -11,7 +11,7 @@ import ( ) func (api *API) InitImport() { - api.BaseRoutes.Imports.Handle("", api.ApiSessionRequired(listImports)).Methods("GET") + api.BaseRoutes.Imports.Handle("", api.APISessionRequired(listImports)).Methods("GET") } func listImports(c *Context, w http.ResponseWriter, r *http.Request) { diff --git a/api4/import_local.go b/api4/import_local.go index bf338c88f6..762aa1c100 100644 --- a/api4/import_local.go +++ b/api4/import_local.go @@ -4,5 +4,5 @@ package api4 func (api *API) InitImportLocal() { - api.BaseRoutes.Imports.Handle("", api.ApiLocal(listImports)).Methods("GET") + api.BaseRoutes.Imports.Handle("", api.APILocal(listImports)).Methods("GET") } diff --git a/api4/integration_action.go b/api4/integration_action.go index b3b6480dc1..680e1239dd 100644 --- a/api4/integration_action.go +++ b/api4/integration_action.go @@ -11,10 +11,10 @@ import ( ) func (api *API) InitAction() { - api.BaseRoutes.Post.Handle("/actions/{action_id:[A-Za-z0-9]+}", api.ApiSessionRequired(doPostAction)).Methods("POST") + api.BaseRoutes.Post.Handle("/actions/{action_id:[A-Za-z0-9]+}", api.APISessionRequired(doPostAction)).Methods("POST") - api.BaseRoutes.ApiRoot.Handle("/actions/dialogs/open", api.ApiHandler(openDialog)).Methods("POST") - api.BaseRoutes.ApiRoot.Handle("/actions/dialogs/submit", api.ApiSessionRequired(submitDialog)).Methods("POST") + api.BaseRoutes.APIRoot.Handle("/actions/dialogs/open", api.APIHandler(openDialog)).Methods("POST") + api.BaseRoutes.APIRoot.Handle("/actions/dialogs/submit", api.APISessionRequired(submitDialog)).Methods("POST") } func doPostAction(c *Context, w http.ResponseWriter, r *http.Request) { diff --git a/api4/job.go b/api4/job.go index 700e839f5e..27af0e0c59 100644 --- a/api4/job.go +++ b/api4/job.go @@ -16,12 +16,12 @@ import ( ) func (api *API) InitJob() { - api.BaseRoutes.Jobs.Handle("", api.ApiSessionRequired(getJobs)).Methods("GET") - api.BaseRoutes.Jobs.Handle("", api.ApiSessionRequired(createJob)).Methods("POST") - api.BaseRoutes.Jobs.Handle("/{job_id:[A-Za-z0-9]+}", api.ApiSessionRequired(getJob)).Methods("GET") - api.BaseRoutes.Jobs.Handle("/{job_id:[A-Za-z0-9]+}/download", api.ApiSessionRequiredTrustRequester(downloadJob)).Methods("GET") - api.BaseRoutes.Jobs.Handle("/{job_id:[A-Za-z0-9]+}/cancel", api.ApiSessionRequired(cancelJob)).Methods("POST") - api.BaseRoutes.Jobs.Handle("/type/{job_type:[A-Za-z0-9_-]+}", api.ApiSessionRequired(getJobsByType)).Methods("GET") + api.BaseRoutes.Jobs.Handle("", api.APISessionRequired(getJobs)).Methods("GET") + api.BaseRoutes.Jobs.Handle("", api.APISessionRequired(createJob)).Methods("POST") + api.BaseRoutes.Jobs.Handle("/{job_id:[A-Za-z0-9]+}", api.APISessionRequired(getJob)).Methods("GET") + api.BaseRoutes.Jobs.Handle("/{job_id:[A-Za-z0-9]+}/download", api.APISessionRequiredTrustRequester(downloadJob)).Methods("GET") + api.BaseRoutes.Jobs.Handle("/{job_id:[A-Za-z0-9]+}/cancel", api.APISessionRequired(cancelJob)).Methods("POST") + api.BaseRoutes.Jobs.Handle("/type/{job_type:[A-Za-z0-9_-]+}", api.APISessionRequired(getJobsByType)).Methods("GET") } func getJob(c *Context, w http.ResponseWriter, r *http.Request) { diff --git a/api4/job_local.go b/api4/job_local.go index 0e9dc34674..fe5ed10aa0 100644 --- a/api4/job_local.go +++ b/api4/job_local.go @@ -4,9 +4,9 @@ package api4 func (api *API) InitJobLocal() { - api.BaseRoutes.Jobs.Handle("", api.ApiLocal(getJobs)).Methods("GET") - api.BaseRoutes.Jobs.Handle("", api.ApiLocal(createJob)).Methods("POST") - api.BaseRoutes.Jobs.Handle("/{job_id:[A-Za-z0-9]+}", api.ApiLocal(getJob)).Methods("GET") - api.BaseRoutes.Jobs.Handle("/{job_id:[A-Za-z0-9]+}/cancel", api.ApiLocal(cancelJob)).Methods("POST") - api.BaseRoutes.Jobs.Handle("/type/{job_type:[A-Za-z0-9_-]+}", api.ApiLocal(getJobsByType)).Methods("GET") + api.BaseRoutes.Jobs.Handle("", api.APILocal(getJobs)).Methods("GET") + api.BaseRoutes.Jobs.Handle("", api.APILocal(createJob)).Methods("POST") + api.BaseRoutes.Jobs.Handle("/{job_id:[A-Za-z0-9]+}", api.APILocal(getJob)).Methods("GET") + api.BaseRoutes.Jobs.Handle("/{job_id:[A-Za-z0-9]+}/cancel", api.APILocal(cancelJob)).Methods("POST") + api.BaseRoutes.Jobs.Handle("/type/{job_type:[A-Za-z0-9_-]+}", api.APILocal(getJobsByType)).Methods("GET") } diff --git a/api4/ldap.go b/api4/ldap.go index 9d02c9d8a1..7f89b803a9 100644 --- a/api4/ldap.go +++ b/api4/ldap.go @@ -20,24 +20,24 @@ type mixedUnlinkedGroup struct { } func (api *API) InitLdap() { - api.BaseRoutes.LDAP.Handle("/sync", api.ApiSessionRequired(syncLdap)).Methods("POST") - api.BaseRoutes.LDAP.Handle("/test", api.ApiSessionRequired(testLdap)).Methods("POST") - api.BaseRoutes.LDAP.Handle("/migrateid", api.ApiSessionRequired(migrateIdLdap)).Methods("POST") + api.BaseRoutes.LDAP.Handle("/sync", api.APISessionRequired(syncLdap)).Methods("POST") + api.BaseRoutes.LDAP.Handle("/test", api.APISessionRequired(testLdap)).Methods("POST") + api.BaseRoutes.LDAP.Handle("/migrateid", api.APISessionRequired(migrateIdLdap)).Methods("POST") // GET /api/v4/ldap/groups?page=0&per_page=1000 - api.BaseRoutes.LDAP.Handle("/groups", api.ApiSessionRequired(getLdapGroups)).Methods("GET") + api.BaseRoutes.LDAP.Handle("/groups", api.APISessionRequired(getLdapGroups)).Methods("GET") // POST /api/v4/ldap/groups/:remote_id/link - api.BaseRoutes.LDAP.Handle(`/groups/{remote_id}/link`, api.ApiSessionRequired(linkLdapGroup)).Methods("POST") + api.BaseRoutes.LDAP.Handle(`/groups/{remote_id}/link`, api.APISessionRequired(linkLdapGroup)).Methods("POST") // DELETE /api/v4/ldap/groups/:remote_id/link - api.BaseRoutes.LDAP.Handle(`/groups/{remote_id}/link`, api.ApiSessionRequired(unlinkLdapGroup)).Methods("DELETE") + api.BaseRoutes.LDAP.Handle(`/groups/{remote_id}/link`, api.APISessionRequired(unlinkLdapGroup)).Methods("DELETE") - api.BaseRoutes.LDAP.Handle("/certificate/public", api.ApiSessionRequired(addLdapPublicCertificate)).Methods("POST") - api.BaseRoutes.LDAP.Handle("/certificate/private", api.ApiSessionRequired(addLdapPrivateCertificate)).Methods("POST") + api.BaseRoutes.LDAP.Handle("/certificate/public", api.APISessionRequired(addLdapPublicCertificate)).Methods("POST") + api.BaseRoutes.LDAP.Handle("/certificate/private", api.APISessionRequired(addLdapPrivateCertificate)).Methods("POST") - api.BaseRoutes.LDAP.Handle("/certificate/public", api.ApiSessionRequired(removeLdapPublicCertificate)).Methods("DELETE") - api.BaseRoutes.LDAP.Handle("/certificate/private", api.ApiSessionRequired(removeLdapPrivateCertificate)).Methods("DELETE") + api.BaseRoutes.LDAP.Handle("/certificate/public", api.APISessionRequired(removeLdapPublicCertificate)).Methods("DELETE") + api.BaseRoutes.LDAP.Handle("/certificate/private", api.APISessionRequired(removeLdapPrivateCertificate)).Methods("DELETE") } diff --git a/api4/ldap_local.go b/api4/ldap_local.go index f82cf52edb..0c1c30717a 100644 --- a/api4/ldap_local.go +++ b/api4/ldap_local.go @@ -4,13 +4,13 @@ package api4 func (api *API) InitLdapLocal() { - api.BaseRoutes.LDAP.Handle("/migrateid", api.ApiLocal(migrateIdLdap)).Methods("POST") - api.BaseRoutes.LDAP.Handle("/sync", api.ApiLocal(syncLdap)).Methods("POST") - api.BaseRoutes.LDAP.Handle("/test", api.ApiLocal(testLdap)).Methods("POST") - api.BaseRoutes.LDAP.Handle("/groups", api.ApiLocal(getLdapGroups)).Methods("GET") - api.BaseRoutes.LDAP.Handle("/certificate/public", api.ApiLocal(addLdapPublicCertificate)).Methods("POST") - api.BaseRoutes.LDAP.Handle("/certificate/private", api.ApiLocal(addLdapPrivateCertificate)).Methods("POST") - api.BaseRoutes.LDAP.Handle("/certificate/public", api.ApiLocal(removeLdapPublicCertificate)).Methods("DELETE") - api.BaseRoutes.LDAP.Handle("/certificate/private", api.ApiLocal(removeLdapPrivateCertificate)).Methods("DELETE") + api.BaseRoutes.LDAP.Handle("/migrateid", api.APILocal(migrateIdLdap)).Methods("POST") + api.BaseRoutes.LDAP.Handle("/sync", api.APILocal(syncLdap)).Methods("POST") + api.BaseRoutes.LDAP.Handle("/test", api.APILocal(testLdap)).Methods("POST") + api.BaseRoutes.LDAP.Handle("/groups", api.APILocal(getLdapGroups)).Methods("GET") + api.BaseRoutes.LDAP.Handle("/certificate/public", api.APILocal(addLdapPublicCertificate)).Methods("POST") + api.BaseRoutes.LDAP.Handle("/certificate/private", api.APILocal(addLdapPrivateCertificate)).Methods("POST") + api.BaseRoutes.LDAP.Handle("/certificate/public", api.APILocal(removeLdapPublicCertificate)).Methods("DELETE") + api.BaseRoutes.LDAP.Handle("/certificate/private", api.APILocal(removeLdapPrivateCertificate)).Methods("DELETE") } diff --git a/api4/license.go b/api4/license.go index 40ec5afe87..e51e5124e8 100644 --- a/api4/license.go +++ b/api4/license.go @@ -19,12 +19,12 @@ import ( ) func (api *API) InitLicense() { - api.BaseRoutes.ApiRoot.Handle("/trial-license", api.ApiSessionRequired(requestTrialLicense)).Methods("POST") - api.BaseRoutes.ApiRoot.Handle("/trial-license/prev", api.ApiSessionRequired(getPrevTrialLicense)).Methods("GET") - api.BaseRoutes.ApiRoot.Handle("/license", api.ApiSessionRequired(addLicense)).Methods("POST") - api.BaseRoutes.ApiRoot.Handle("/license", api.ApiSessionRequired(removeLicense)).Methods("DELETE") - api.BaseRoutes.ApiRoot.Handle("/license/renewal", api.ApiSessionRequired(requestRenewalLink)).Methods("GET") - api.BaseRoutes.ApiRoot.Handle("/license/client", api.ApiHandler(getClientLicense)).Methods("GET") + api.BaseRoutes.APIRoot.Handle("/trial-license", api.APISessionRequired(requestTrialLicense)).Methods("POST") + api.BaseRoutes.APIRoot.Handle("/trial-license/prev", api.APISessionRequired(getPrevTrialLicense)).Methods("GET") + api.BaseRoutes.APIRoot.Handle("/license", api.APISessionRequired(addLicense)).Methods("POST") + api.BaseRoutes.APIRoot.Handle("/license", api.APISessionRequired(removeLicense)).Methods("DELETE") + api.BaseRoutes.APIRoot.Handle("/license/renewal", api.APISessionRequired(requestRenewalLink)).Methods("GET") + api.BaseRoutes.APIRoot.Handle("/license/client", api.APIHandler(getClientLicense)).Methods("GET") } func getClientLicense(c *Context, w http.ResponseWriter, r *http.Request) { diff --git a/api4/license_local.go b/api4/license_local.go index bf7b21c3c8..1f61aaed5b 100644 --- a/api4/license_local.go +++ b/api4/license_local.go @@ -15,8 +15,8 @@ import ( ) func (api *API) InitLicenseLocal() { - api.BaseRoutes.ApiRoot.Handle("/license", api.ApiLocal(localAddLicense)).Methods("POST") - api.BaseRoutes.ApiRoot.Handle("/license", api.ApiLocal(localRemoveLicense)).Methods("DELETE") + api.BaseRoutes.APIRoot.Handle("/license", api.APILocal(localAddLicense)).Methods("POST") + api.BaseRoutes.APIRoot.Handle("/license", api.APILocal(localRemoveLicense)).Methods("DELETE") } func localAddLicense(c *Context, w http.ResponseWriter, r *http.Request) { diff --git a/api4/license_test.go b/api4/license_test.go index dba37eca61..62c01e9847 100644 --- a/api4/license_test.go +++ b/api4/license_test.go @@ -34,12 +34,12 @@ func TestGetOldClientLicense(t *testing.T) { _, _, err = client.GetOldClientLicense("") require.NoError(t, err) - resp, err := client.DoApiGet("/license/client", "") + resp, err := client.DoAPIGet("/license/client", "") require.Error(t, err, "get /license/client did not return an error") require.Equal(t, http.StatusNotImplemented, resp.StatusCode, "expected 501 Not Implemented") - resp, err = client.DoApiGet("/license/client?format=junk", "") + resp, err = client.DoAPIGet("/license/client?format=junk", "") require.Error(t, err, "get /license/client?format=junk did not return an error") require.Equal(t, http.StatusBadRequest, resp.StatusCode, "expected 400 Bad Request") diff --git a/api4/oauth.go b/api4/oauth.go index 281deaed99..caec4423cc 100644 --- a/api4/oauth.go +++ b/api4/oauth.go @@ -13,15 +13,15 @@ import ( ) func (api *API) InitOAuth() { - api.BaseRoutes.OAuthApps.Handle("", api.ApiSessionRequired(createOAuthApp)).Methods("POST") - api.BaseRoutes.OAuthApp.Handle("", api.ApiSessionRequired(updateOAuthApp)).Methods("PUT") - api.BaseRoutes.OAuthApps.Handle("", api.ApiSessionRequired(getOAuthApps)).Methods("GET") - api.BaseRoutes.OAuthApp.Handle("", api.ApiSessionRequired(getOAuthApp)).Methods("GET") - api.BaseRoutes.OAuthApp.Handle("/info", api.ApiSessionRequired(getOAuthAppInfo)).Methods("GET") - api.BaseRoutes.OAuthApp.Handle("", api.ApiSessionRequired(deleteOAuthApp)).Methods("DELETE") - api.BaseRoutes.OAuthApp.Handle("/regen_secret", api.ApiSessionRequired(regenerateOAuthAppSecret)).Methods("POST") + api.BaseRoutes.OAuthApps.Handle("", api.APISessionRequired(createOAuthApp)).Methods("POST") + api.BaseRoutes.OAuthApp.Handle("", api.APISessionRequired(updateOAuthApp)).Methods("PUT") + api.BaseRoutes.OAuthApps.Handle("", api.APISessionRequired(getOAuthApps)).Methods("GET") + api.BaseRoutes.OAuthApp.Handle("", api.APISessionRequired(getOAuthApp)).Methods("GET") + api.BaseRoutes.OAuthApp.Handle("/info", api.APISessionRequired(getOAuthAppInfo)).Methods("GET") + api.BaseRoutes.OAuthApp.Handle("", api.APISessionRequired(deleteOAuthApp)).Methods("DELETE") + api.BaseRoutes.OAuthApp.Handle("/regen_secret", api.APISessionRequired(regenerateOAuthAppSecret)).Methods("POST") - api.BaseRoutes.User.Handle("/oauth/apps/authorized", api.ApiSessionRequired(getAuthorizedOAuthApps)).Methods("GET") + api.BaseRoutes.User.Handle("/oauth/apps/authorized", api.APISessionRequired(getAuthorizedOAuthApps)).Methods("GET") } func createOAuthApp(c *Context, w http.ResponseWriter, r *http.Request) { diff --git a/api4/oauth_test.go b/api4/oauth_test.go index d24a3a3268..2e7b623771 100644 --- a/api4/oauth_test.go +++ b/api4/oauth_test.go @@ -60,7 +60,7 @@ func TestCreateOAuthApp(t *testing.T) { require.Error(t, err) CheckBadRequestStatus(t, resp) - r, err := client.DoApiPost("/oauth/apps", "garbage") + r, err := client.DoAPIPost("/oauth/apps", "garbage") require.Error(t, err, "expected error from garbage post") assert.Equal(t, http.StatusBadRequest, r.StatusCode) @@ -123,8 +123,8 @@ func TestUpdateOAuthApp(t *testing.T) { assert.Equal(t, oapp.IconURL, updatedApp.IconURL, "IconURL should have updated") if len(updatedApp.CallbackUrls) == len(oapp.CallbackUrls) { - for i, callbackUrl := range updatedApp.CallbackUrls { - assert.Equal(t, oapp.CallbackUrls[i], callbackUrl, "Description should have updated") + for i, callbackURL := range updatedApp.CallbackUrls { + assert.Equal(t, oapp.CallbackUrls[i], callbackURL, "Description should have updated") } } assert.Equal(t, oapp.Homepage, updatedApp.Homepage, "Homepage should have updated") @@ -571,7 +571,7 @@ func TestGetAuthorizedOAuthAppsForUser(t *testing.T) { authRequest := &model.AuthorizeRequest{ ResponseType: model.AuthCodeResponseType, ClientId: rapp.Id, - RedirectUri: rapp.CallbackUrls[0], + RedirectURI: rapp.CallbackUrls[0], Scope: "", State: "123", } diff --git a/api4/openGraph.go b/api4/openGraph.go index d9e47baa43..f851908267 100644 --- a/api4/openGraph.go +++ b/api4/openGraph.go @@ -18,7 +18,7 @@ var openGraphDataCache = cache.NewLRU(cache.LRUOptions{ }) func (api *API) InitOpenGraph() { - api.BaseRoutes.OpenGraph.Handle("", api.ApiSessionRequired(getOpenGraphMetadata)).Methods("POST") + api.BaseRoutes.OpenGraph.Handle("", api.APISessionRequired(getOpenGraphMetadata)).Methods("POST") // Dump the image cache if the proxy settings have changed. (need switch URLs to the correct proxy) api.app.AddConfigListener(func(before, after *model.Config) { diff --git a/api4/permission.go b/api4/permission.go index 59b89edf3a..0ed4351071 100644 --- a/api4/permission.go +++ b/api4/permission.go @@ -12,14 +12,14 @@ import ( ) func (api *API) InitPermissions() { - api.BaseRoutes.Permissions.Handle("/ancillary", api.ApiSessionRequired(appendAncillaryPermissions)).Methods("GET") + api.BaseRoutes.Permissions.Handle("/ancillary", api.APISessionRequired(appendAncillaryPermissions)).Methods("GET") } func appendAncillaryPermissions(c *Context, w http.ResponseWriter, r *http.Request) { keys, ok := r.URL.Query()["subsection_permissions"] if !ok || len(keys[0]) < 1 { - c.SetInvalidUrlParam("subsection_permissions") + c.SetInvalidURLParam("subsection_permissions") return } diff --git a/api4/plugin.go b/api4/plugin.go index 9653756639..84046cff36 100644 --- a/api4/plugin.go +++ b/api4/plugin.go @@ -27,22 +27,22 @@ const ( func (api *API) InitPlugin() { mlog.Debug("EXPERIMENTAL: Initializing plugin api") - api.BaseRoutes.Plugins.Handle("", api.ApiSessionRequired(uploadPlugin)).Methods("POST") - api.BaseRoutes.Plugins.Handle("", api.ApiSessionRequired(getPlugins)).Methods("GET") - api.BaseRoutes.Plugin.Handle("", api.ApiSessionRequired(removePlugin)).Methods("DELETE") - api.BaseRoutes.Plugins.Handle("/install_from_url", api.ApiSessionRequired(installPluginFromUrl)).Methods("POST") - api.BaseRoutes.Plugins.Handle("/marketplace", api.ApiSessionRequired(installMarketplacePlugin)).Methods("POST") + api.BaseRoutes.Plugins.Handle("", api.APISessionRequired(uploadPlugin)).Methods("POST") + api.BaseRoutes.Plugins.Handle("", api.APISessionRequired(getPlugins)).Methods("GET") + api.BaseRoutes.Plugin.Handle("", api.APISessionRequired(removePlugin)).Methods("DELETE") + api.BaseRoutes.Plugins.Handle("/install_from_url", api.APISessionRequired(installPluginFromURL)).Methods("POST") + api.BaseRoutes.Plugins.Handle("/marketplace", api.APISessionRequired(installMarketplacePlugin)).Methods("POST") - api.BaseRoutes.Plugins.Handle("/statuses", api.ApiSessionRequired(getPluginStatuses)).Methods("GET") - api.BaseRoutes.Plugin.Handle("/enable", api.ApiSessionRequired(enablePlugin)).Methods("POST") - api.BaseRoutes.Plugin.Handle("/disable", api.ApiSessionRequired(disablePlugin)).Methods("POST") + api.BaseRoutes.Plugins.Handle("/statuses", api.APISessionRequired(getPluginStatuses)).Methods("GET") + api.BaseRoutes.Plugin.Handle("/enable", api.APISessionRequired(enablePlugin)).Methods("POST") + api.BaseRoutes.Plugin.Handle("/disable", api.APISessionRequired(disablePlugin)).Methods("POST") - api.BaseRoutes.Plugins.Handle("/webapp", api.ApiHandler(getWebappPlugins)).Methods("GET") + api.BaseRoutes.Plugins.Handle("/webapp", api.APIHandler(getWebappPlugins)).Methods("GET") - api.BaseRoutes.Plugins.Handle("/marketplace", api.ApiSessionRequired(getMarketplacePlugins)).Methods("GET") + api.BaseRoutes.Plugins.Handle("/marketplace", api.APISessionRequired(getMarketplacePlugins)).Methods("GET") - api.BaseRoutes.Plugins.Handle("/marketplace/first_admin_visit", api.ApiHandler(setFirstAdminVisitMarketplaceStatus)).Methods("POST") - api.BaseRoutes.Plugins.Handle("/marketplace/first_admin_visit", api.ApiSessionRequired(getFirstAdminVisitMarketplaceStatus)).Methods("GET") + api.BaseRoutes.Plugins.Handle("/marketplace/first_admin_visit", api.APIHandler(setFirstAdminVisitMarketplaceStatus)).Methods("POST") + api.BaseRoutes.Plugins.Handle("/marketplace/first_admin_visit", api.APISessionRequired(getFirstAdminVisitMarketplaceStatus)).Methods("GET") } func uploadPlugin(c *Context, w http.ResponseWriter, r *http.Request) { @@ -95,15 +95,15 @@ func uploadPlugin(c *Context, w http.ResponseWriter, r *http.Request) { auditRec.Success() } -func installPluginFromUrl(c *Context, w http.ResponseWriter, r *http.Request) { +func installPluginFromURL(c *Context, w http.ResponseWriter, r *http.Request) { if !*c.App.Config().PluginSettings.Enable || *c.App.Config().PluginSettings.RequirePluginSignature || !*c.App.Config().PluginSettings.EnableUploads { - c.Err = model.NewAppError("installPluginFromUrl", "app.plugin.disabled.app_error", nil, "", http.StatusNotImplemented) + c.Err = model.NewAppError("installPluginFromURL", "app.plugin.disabled.app_error", nil, "", http.StatusNotImplemented) return } - auditRec := c.MakeAuditRecord("installPluginFromUrl", audit.Fail) + auditRec := c.MakeAuditRecord("installPluginFromURL", audit.Fail) defer c.LogAuditRec(auditRec) if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionSysconsoleWritePlugins) { @@ -117,7 +117,7 @@ func installPluginFromUrl(c *Context, w http.ResponseWriter, r *http.Request) { pluginFileBytes, err := c.App.DownloadFromURL(downloadURL) if err != nil { - c.Err = model.NewAppError("installPluginFromUrl", "api.plugin.install.download_failed.app_error", nil, err.Error(), http.StatusBadRequest) + c.Err = model.NewAppError("installPluginFromURL", "api.plugin.install.download_failed.app_error", nil, err.Error(), http.StatusBadRequest) return } diff --git a/api4/plugin_local.go b/api4/plugin_local.go index 4ddd6ac10e..32aca6969a 100644 --- a/api4/plugin_local.go +++ b/api4/plugin_local.go @@ -4,12 +4,12 @@ package api4 func (api *API) InitPluginLocal() { - api.BaseRoutes.Plugins.Handle("", api.ApiLocal(uploadPlugin)).Methods("POST") - api.BaseRoutes.Plugins.Handle("", api.ApiLocal(getPlugins)).Methods("GET") - api.BaseRoutes.Plugins.Handle("/install_from_url", api.ApiLocal(installPluginFromUrl)).Methods("POST") - api.BaseRoutes.Plugin.Handle("", api.ApiLocal(removePlugin)).Methods("DELETE") - api.BaseRoutes.Plugin.Handle("/enable", api.ApiLocal(enablePlugin)).Methods("POST") - api.BaseRoutes.Plugin.Handle("/disable", api.ApiLocal(disablePlugin)).Methods("POST") - api.BaseRoutes.Plugins.Handle("/marketplace", api.ApiLocal(installMarketplacePlugin)).Methods("POST") - api.BaseRoutes.Plugins.Handle("/marketplace", api.ApiLocal(getMarketplacePlugins)).Methods("GET") + api.BaseRoutes.Plugins.Handle("", api.APILocal(uploadPlugin)).Methods("POST") + api.BaseRoutes.Plugins.Handle("", api.APILocal(getPlugins)).Methods("GET") + api.BaseRoutes.Plugins.Handle("/install_from_url", api.APILocal(installPluginFromURL)).Methods("POST") + api.BaseRoutes.Plugin.Handle("", api.APILocal(removePlugin)).Methods("DELETE") + api.BaseRoutes.Plugin.Handle("/enable", api.APILocal(enablePlugin)).Methods("POST") + api.BaseRoutes.Plugin.Handle("/disable", api.APILocal(disablePlugin)).Methods("POST") + api.BaseRoutes.Plugins.Handle("/marketplace", api.APILocal(installMarketplacePlugin)).Methods("POST") + api.BaseRoutes.Plugins.Handle("/marketplace", api.APILocal(getMarketplacePlugins)).Methods("GET") } diff --git a/api4/plugin_test.go b/api4/plugin_test.go index 30e6f1d6ae..9751aed198 100644 --- a/api4/plugin_test.go +++ b/api4/plugin_test.go @@ -40,7 +40,7 @@ func TestPlugin(t *testing.T) { th.App.UpdateConfig(func(cfg *model.Config) { *cfg.PluginSettings.Enable = true *cfg.PluginSettings.EnableUploads = true - *cfg.PluginSettings.AllowInsecureDownloadUrl = true + *cfg.PluginSettings.AllowInsecureDownloadURL = true }) path, _ := fileutils.FindDir("tests") @@ -56,15 +56,15 @@ func TestPlugin(t *testing.T) { url := testServer.URL - manifest, _, err := client.InstallPluginFromUrl(url, false) + manifest, _, err := client.InstallPluginFromURL(url, false) require.NoError(t, err) assert.Equal(t, "testplugin", manifest.Id) - _, resp, err := client.InstallPluginFromUrl(url, false) + _, resp, err := client.InstallPluginFromURL(url, false) require.Error(t, err) CheckBadRequestStatus(t, resp) - manifest, _, err = client.InstallPluginFromUrl(url, true) + manifest, _, err = client.InstallPluginFromURL(url, true) require.NoError(t, err) assert.Equal(t, "testplugin", manifest.Id) @@ -89,7 +89,7 @@ func TestPlugin(t *testing.T) { })) defer func() { slowTestServer.Close() }() - manifest, _, err = client.InstallPluginFromUrl(slowTestServer.URL, true) + manifest, _, err = client.InstallPluginFromURL(slowTestServer.URL, true) require.NoError(t, err) assert.Equal(t, "testplugin", manifest.Id) }) @@ -98,23 +98,23 @@ func TestPlugin(t *testing.T) { th.App.UpdateConfig(func(cfg *model.Config) { *cfg.PluginSettings.Enable = false }) - _, resp, err = client.InstallPluginFromUrl(url, false) + _, resp, err = client.InstallPluginFromURL(url, false) require.Error(t, err) CheckNotImplementedStatus(t, resp) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.PluginSettings.Enable = true }) - _, resp, err = th.Client.InstallPluginFromUrl(url, false) + _, resp, err = th.Client.InstallPluginFromURL(url, false) require.Error(t, err) CheckForbiddenStatus(t, resp) - _, resp, err = client.InstallPluginFromUrl("http://nodata", false) + _, resp, err = client.InstallPluginFromURL("http://nodata", false) require.Error(t, err) CheckBadRequestStatus(t, resp) - th.App.UpdateConfig(func(cfg *model.Config) { *cfg.PluginSettings.AllowInsecureDownloadUrl = false }) + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.PluginSettings.AllowInsecureDownloadURL = false }) - _, resp, err = client.InstallPluginFromUrl(url, false) + _, resp, err = client.InstallPluginFromURL(url, false) require.Error(t, err) CheckBadRequestStatus(t, resp) @@ -153,7 +153,7 @@ func TestPlugin(t *testing.T) { require.Error(t, err) CheckNotImplementedStatus(t, resp) - _, resp, err = client.InstallPluginFromUrl(url, false) + _, resp, err = client.InstallPluginFromURL(url, false) require.Error(t, err) CheckNotImplementedStatus(t, resp) @@ -490,7 +490,7 @@ func TestGetMarketplacePlugins(t *testing.T) { th.TestForSystemAdminAndLocal(t, func(t *testing.T, client *model.Client4) { th.App.UpdateConfig(func(cfg *model.Config) { *cfg.PluginSettings.EnableMarketplace = false - *cfg.PluginSettings.MarketplaceUrl = "invalid.com" + *cfg.PluginSettings.MarketplaceURL = "invalid.com" }) plugins, resp, err := client.GetMarketplacePlugins(&model.MarketplacePluginFilter{}) @@ -502,7 +502,7 @@ func TestGetMarketplacePlugins(t *testing.T) { th.TestForSystemAdminAndLocal(t, func(t *testing.T, client *model.Client4) { th.App.UpdateConfig(func(cfg *model.Config) { *cfg.PluginSettings.EnableMarketplace = true - *cfg.PluginSettings.MarketplaceUrl = "invalid.com" + *cfg.PluginSettings.MarketplaceURL = "invalid.com" }) plugins, resp, err := client.GetMarketplacePlugins(&model.MarketplacePluginFilter{}) @@ -514,7 +514,7 @@ func TestGetMarketplacePlugins(t *testing.T) { t.Run("no permission", func(t *testing.T) { th.App.UpdateConfig(func(cfg *model.Config) { *cfg.PluginSettings.EnableMarketplace = true - *cfg.PluginSettings.MarketplaceUrl = "invalid.com" + *cfg.PluginSettings.MarketplaceURL = "invalid.com" }) plugins, resp, err := th.Client.GetMarketplacePlugins(&model.MarketplacePluginFilter{}) @@ -534,7 +534,7 @@ func TestGetMarketplacePlugins(t *testing.T) { th.App.UpdateConfig(func(cfg *model.Config) { *cfg.PluginSettings.EnableMarketplace = true - *cfg.PluginSettings.MarketplaceUrl = testServer.URL + *cfg.PluginSettings.MarketplaceURL = testServer.URL }) plugins, _, err := client.GetMarketplacePlugins(&model.MarketplacePluginFilter{}) @@ -559,7 +559,7 @@ func TestGetMarketplacePlugins(t *testing.T) { th.App.UpdateConfig(func(cfg *model.Config) { *cfg.PluginSettings.EnableMarketplace = true - *cfg.PluginSettings.MarketplaceUrl = testServer.URL + *cfg.PluginSettings.MarketplaceURL = testServer.URL }) plugins, _, err := client.GetMarketplacePlugins(&model.MarketplacePluginFilter{}) @@ -583,7 +583,7 @@ func TestGetMarketplacePlugins(t *testing.T) { th.App.UpdateConfig(func(cfg *model.Config) { *cfg.PluginSettings.EnableMarketplace = true - *cfg.PluginSettings.MarketplaceUrl = testServer.URL + *cfg.PluginSettings.MarketplaceURL = testServer.URL }) plugins, _, err := client.GetMarketplacePlugins(&model.MarketplacePluginFilter{}) @@ -607,7 +607,7 @@ func TestGetMarketplacePlugins(t *testing.T) { th.App.UpdateConfig(func(cfg *model.Config) { *cfg.PluginSettings.EnableMarketplace = true - *cfg.PluginSettings.MarketplaceUrl = testServer.URL + *cfg.PluginSettings.MarketplaceURL = testServer.URL }) l := model.NewTestLicense() @@ -636,7 +636,7 @@ func TestGetMarketplacePlugins(t *testing.T) { th.App.UpdateConfig(func(cfg *model.Config) { *cfg.PluginSettings.EnableMarketplace = true - *cfg.PluginSettings.MarketplaceUrl = testServer.URL + *cfg.PluginSettings.MarketplaceURL = testServer.URL }) th.App.Srv().SetLicense(model.NewTestLicense("enterprise_plugins")) @@ -662,7 +662,7 @@ func TestGetMarketplacePlugins(t *testing.T) { th.App.UpdateConfig(func(cfg *model.Config) { *cfg.PluginSettings.EnableMarketplace = true - *cfg.PluginSettings.MarketplaceUrl = testServer.URL + *cfg.PluginSettings.MarketplaceURL = testServer.URL }) plugins, _, err := client.GetMarketplacePlugins(&model.MarketplacePluginFilter{}) @@ -686,7 +686,7 @@ func TestGetMarketplacePlugins(t *testing.T) { th.App.UpdateConfig(func(cfg *model.Config) { *cfg.PluginSettings.EnableMarketplace = true - *cfg.PluginSettings.MarketplaceUrl = testServer.URL + *cfg.PluginSettings.MarketplaceURL = testServer.URL }) th.App.Srv().SetLicense(model.NewTestLicense("cloud")) @@ -742,7 +742,7 @@ func TestGetInstalledMarketplacePlugins(t *testing.T) { *cfg.PluginSettings.Enable = true *cfg.PluginSettings.EnableUploads = true *cfg.PluginSettings.EnableMarketplace = true - *cfg.PluginSettings.MarketplaceUrl = testServer.URL + *cfg.PluginSettings.MarketplaceURL = testServer.URL }) plugins, _, err := th.SystemAdminClient.GetMarketplacePlugins(&model.MarketplacePluginFilter{}) @@ -823,7 +823,7 @@ func TestGetInstalledMarketplacePlugins(t *testing.T) { })) defer func() { testServer.Close() }() th.App.UpdateConfig(func(cfg *model.Config) { - *cfg.PluginSettings.MarketplaceUrl = testServer.URL + *cfg.PluginSettings.MarketplaceURL = testServer.URL }) plugins, _, err := th.SystemAdminClient.GetMarketplacePlugins(&model.MarketplacePluginFilter{}) @@ -887,7 +887,7 @@ func TestSearchGetMarketplacePlugins(t *testing.T) { *cfg.PluginSettings.Enable = true *cfg.PluginSettings.EnableUploads = true *cfg.PluginSettings.EnableMarketplace = true - *cfg.PluginSettings.MarketplaceUrl = testServer.URL + *cfg.PluginSettings.MarketplaceURL = testServer.URL }) plugins, _, err := th.SystemAdminClient.GetMarketplacePlugins(&model.MarketplacePluginFilter{}) @@ -998,7 +998,7 @@ func TestGetLocalPluginInMarketplace(t *testing.T) { th.App.UpdateConfig(func(cfg *model.Config) { *cfg.PluginSettings.Enable = true *cfg.PluginSettings.EnableMarketplace = true - *cfg.PluginSettings.MarketplaceUrl = testServer.URL + *cfg.PluginSettings.MarketplaceURL = testServer.URL }) t.Run("Get plugins with EnableRemoteMarketplace enabled", func(t *testing.T) { @@ -1159,7 +1159,7 @@ func TestGetPrepackagedPluginInMarketplace(t *testing.T) { th.App.UpdateConfig(func(cfg *model.Config) { *cfg.PluginSettings.Enable = true *cfg.PluginSettings.EnableMarketplace = true - *cfg.PluginSettings.MarketplaceUrl = testServer.URL + *cfg.PluginSettings.MarketplaceURL = testServer.URL }) prepackagePlugin := &plugin.PrepackagedPlugin{ @@ -1313,7 +1313,7 @@ func TestInstallMarketplacePlugin(t *testing.T) { th.TestForSystemAdminAndLocal(t, func(t *testing.T, client *model.Client4) { th.App.UpdateConfig(func(cfg *model.Config) { *cfg.PluginSettings.EnableMarketplace = false - *cfg.PluginSettings.MarketplaceUrl = "invalid.com" + *cfg.PluginSettings.MarketplaceURL = "invalid.com" }) plugin, resp, err := client.InstallMarketplacePlugin(request) require.Error(t, err) @@ -1331,7 +1331,7 @@ func TestInstallMarketplacePlugin(t *testing.T) { CheckNotImplementedStatus(t, resp) require.Nil(t, manifest) - manifest, resp, err = client.InstallPluginFromUrl("some_url", true) + manifest, resp, err = client.InstallPluginFromURL("some_url", true) require.Error(t, err) CheckNotImplementedStatus(t, resp) require.Nil(t, manifest) @@ -1340,7 +1340,7 @@ func TestInstallMarketplacePlugin(t *testing.T) { th.TestForSystemAdminAndLocal(t, func(t *testing.T, client *model.Client4) { th.App.UpdateConfig(func(cfg *model.Config) { *cfg.PluginSettings.EnableMarketplace = true - *cfg.PluginSettings.MarketplaceUrl = "invalid.com" + *cfg.PluginSettings.MarketplaceURL = "invalid.com" }) plugin, resp, err := client.InstallMarketplacePlugin(request) @@ -1352,7 +1352,7 @@ func TestInstallMarketplacePlugin(t *testing.T) { t.Run("no permission", func(t *testing.T) { th.App.UpdateConfig(func(cfg *model.Config) { *cfg.PluginSettings.EnableMarketplace = true - *cfg.PluginSettings.MarketplaceUrl = "invalid.com" + *cfg.PluginSettings.MarketplaceURL = "invalid.com" }) plugin, resp, err := th.Client.InstallMarketplacePlugin(request) @@ -1372,7 +1372,7 @@ func TestInstallMarketplacePlugin(t *testing.T) { th.App.UpdateConfig(func(cfg *model.Config) { *cfg.PluginSettings.EnableMarketplace = true - *cfg.PluginSettings.MarketplaceUrl = testServer.URL + *cfg.PluginSettings.MarketplaceURL = testServer.URL }) pRequest := &model.InstallMarketplacePluginRequest{Id: "some_plugin_id", Version: "0.0.1"} plugin, resp, err := client.InstallMarketplacePlugin(pRequest) @@ -1392,8 +1392,8 @@ func TestInstallMarketplacePlugin(t *testing.T) { th.App.UpdateConfig(func(cfg *model.Config) { *cfg.PluginSettings.EnableMarketplace = true - *cfg.PluginSettings.MarketplaceUrl = testServer.URL - *cfg.PluginSettings.AllowInsecureDownloadUrl = true + *cfg.PluginSettings.MarketplaceURL = testServer.URL + *cfg.PluginSettings.AllowInsecureDownloadURL = true }) pRequest := &model.InstallMarketplacePluginRequest{Id: "testplugin2", Version: "1.2.2"} plugin, resp, err := client.InstallMarketplacePlugin(pRequest) @@ -1417,7 +1417,7 @@ func TestInstallMarketplacePlugin(t *testing.T) { th.App.UpdateConfig(func(cfg *model.Config) { *cfg.PluginSettings.EnableMarketplace = true *cfg.PluginSettings.EnableRemoteMarketplace = true - *cfg.PluginSettings.MarketplaceUrl = testServer.URL + *cfg.PluginSettings.MarketplaceURL = testServer.URL }) key, err := os.Open(filepath.Join(path, "development-private-key.asc")) @@ -1469,7 +1469,7 @@ func TestInstallMarketplacePlugin(t *testing.T) { th.App.UpdateConfig(func(cfg *model.Config) { *cfg.PluginSettings.EnableMarketplace = true *cfg.PluginSettings.EnableRemoteMarketplace = true - *cfg.PluginSettings.MarketplaceUrl = testServer.URL + *cfg.PluginSettings.MarketplaceURL = testServer.URL }) // The content of the request is irrelevant. This test only cares about enterprise_plugins. @@ -1503,7 +1503,7 @@ func TestInstallMarketplacePlugin(t *testing.T) { th.App.UpdateConfig(func(cfg *model.Config) { *cfg.PluginSettings.EnableMarketplace = true *cfg.PluginSettings.EnableRemoteMarketplace = true - *cfg.PluginSettings.MarketplaceUrl = testServer.URL + *cfg.PluginSettings.MarketplaceURL = testServer.URL }) l := model.NewTestLicense() @@ -1541,7 +1541,7 @@ func TestInstallMarketplacePlugin(t *testing.T) { th.App.UpdateConfig(func(cfg *model.Config) { *cfg.PluginSettings.EnableMarketplace = true - *cfg.PluginSettings.MarketplaceUrl = testServer.URL + *cfg.PluginSettings.MarketplaceURL = testServer.URL }) th.App.Srv().SetLicense(model.NewTestLicense("enterprise_plugins")) @@ -1603,8 +1603,8 @@ func TestInstallMarketplacePlugin(t *testing.T) { th2.App.UpdateConfig(func(cfg *model.Config) { *cfg.PluginSettings.EnableMarketplace = true *cfg.PluginSettings.EnableRemoteMarketplace = false - *cfg.PluginSettings.MarketplaceUrl = testServer.URL - *cfg.PluginSettings.AllowInsecureDownloadUrl = false + *cfg.PluginSettings.MarketplaceURL = testServer.URL + *cfg.PluginSettings.AllowInsecureDownloadURL = false }) env := th2.App.GetPluginsEnvironment() @@ -1656,8 +1656,8 @@ func TestInstallMarketplacePlugin(t *testing.T) { th2.App.UpdateConfig(func(cfg *model.Config) { *cfg.PluginSettings.EnableMarketplace = true *cfg.PluginSettings.EnableRemoteMarketplace = true - *cfg.PluginSettings.MarketplaceUrl = testServer.URL - *cfg.PluginSettings.AllowInsecureDownloadUrl = true + *cfg.PluginSettings.MarketplaceURL = testServer.URL + *cfg.PluginSettings.AllowInsecureDownloadURL = true }) pRequest = &model.InstallMarketplacePluginRequest{Id: "testplugin2", Version: "1.2.3"} @@ -1734,8 +1734,8 @@ func TestInstallMarketplacePlugin(t *testing.T) { th.App.UpdateConfig(func(cfg *model.Config) { *cfg.PluginSettings.EnableMarketplace = true *cfg.PluginSettings.EnableRemoteMarketplace = true - *cfg.PluginSettings.MarketplaceUrl = testServer.URL - *cfg.PluginSettings.AllowInsecureDownloadUrl = true + *cfg.PluginSettings.MarketplaceURL = testServer.URL + *cfg.PluginSettings.AllowInsecureDownloadURL = true }) env := th.App.GetPluginsEnvironment() diff --git a/api4/post.go b/api4/post.go index 5e75a76713..60aa404156 100644 --- a/api4/post.go +++ b/api4/post.go @@ -16,23 +16,23 @@ import ( ) func (api *API) InitPost() { - api.BaseRoutes.Posts.Handle("", api.ApiSessionRequired(createPost)).Methods("POST") - api.BaseRoutes.Post.Handle("", api.ApiSessionRequired(getPost)).Methods("GET") - api.BaseRoutes.Post.Handle("", api.ApiSessionRequired(deletePost)).Methods("DELETE") - api.BaseRoutes.Posts.Handle("/ephemeral", api.ApiSessionRequired(createEphemeralPost)).Methods("POST") - api.BaseRoutes.Post.Handle("/thread", api.ApiSessionRequired(getPostThread)).Methods("GET") - api.BaseRoutes.Post.Handle("/files/info", api.ApiSessionRequired(getFileInfosForPost)).Methods("GET") - api.BaseRoutes.PostsForChannel.Handle("", api.ApiSessionRequired(getPostsForChannel)).Methods("GET") - api.BaseRoutes.PostsForUser.Handle("/flagged", api.ApiSessionRequired(getFlaggedPostsForUser)).Methods("GET") + api.BaseRoutes.Posts.Handle("", api.APISessionRequired(createPost)).Methods("POST") + api.BaseRoutes.Post.Handle("", api.APISessionRequired(getPost)).Methods("GET") + api.BaseRoutes.Post.Handle("", api.APISessionRequired(deletePost)).Methods("DELETE") + api.BaseRoutes.Posts.Handle("/ephemeral", api.APISessionRequired(createEphemeralPost)).Methods("POST") + api.BaseRoutes.Post.Handle("/thread", api.APISessionRequired(getPostThread)).Methods("GET") + api.BaseRoutes.Post.Handle("/files/info", api.APISessionRequired(getFileInfosForPost)).Methods("GET") + api.BaseRoutes.PostsForChannel.Handle("", api.APISessionRequired(getPostsForChannel)).Methods("GET") + api.BaseRoutes.PostsForUser.Handle("/flagged", api.APISessionRequired(getFlaggedPostsForUser)).Methods("GET") - api.BaseRoutes.ChannelForUser.Handle("/posts/unread", api.ApiSessionRequired(getPostsForChannelAroundLastUnread)).Methods("GET") + api.BaseRoutes.ChannelForUser.Handle("/posts/unread", api.APISessionRequired(getPostsForChannelAroundLastUnread)).Methods("GET") - api.BaseRoutes.Team.Handle("/posts/search", api.ApiSessionRequiredDisableWhenBusy(searchPosts)).Methods("POST") - api.BaseRoutes.Post.Handle("", api.ApiSessionRequired(updatePost)).Methods("PUT") - api.BaseRoutes.Post.Handle("/patch", api.ApiSessionRequired(patchPost)).Methods("PUT") - api.BaseRoutes.PostForUser.Handle("/set_unread", api.ApiSessionRequired(setPostUnread)).Methods("POST") - api.BaseRoutes.Post.Handle("/pin", api.ApiSessionRequired(pinPost)).Methods("POST") - api.BaseRoutes.Post.Handle("/unpin", api.ApiSessionRequired(unpinPost)).Methods("POST") + api.BaseRoutes.Team.Handle("/posts/search", api.APISessionRequiredDisableWhenBusy(searchPosts)).Methods("POST") + api.BaseRoutes.Post.Handle("", api.APISessionRequired(updatePost)).Methods("PUT") + api.BaseRoutes.Post.Handle("/patch", api.APISessionRequired(patchPost)).Methods("PUT") + api.BaseRoutes.PostForUser.Handle("/set_unread", api.APISessionRequired(setPostUnread)).Methods("POST") + api.BaseRoutes.Post.Handle("/pin", api.APISessionRequired(pinPost)).Methods("POST") + api.BaseRoutes.Post.Handle("/unpin", api.APISessionRequired(unpinPost)).Methods("POST") } func createPost(c *Context, w http.ResponseWriter, r *http.Request) { @@ -251,7 +251,7 @@ func getPostsForChannelAroundLastUnread(c *Context, w http.ResponseWriter, r *ht } if c.Params.LimitAfter == 0 { - c.SetInvalidUrlParam("limit_after") + c.SetInvalidURLParam("limit_after") return } @@ -446,7 +446,7 @@ func getPostThread(c *Context, w http.ResponseWriter, r *http.Request) { post, ok := list.Posts[c.Params.PostId] if !ok { - c.SetInvalidUrlParam("post_id") + c.SetInvalidURLParam("post_id") return } diff --git a/api4/post_local.go b/api4/post_local.go index 2c27b404fd..d4bdcf93e1 100644 --- a/api4/post_local.go +++ b/api4/post_local.go @@ -4,7 +4,7 @@ package api4 func (api *API) InitPostLocal() { - api.BaseRoutes.Post.Handle("", api.ApiLocal(getPost)).Methods("GET") + api.BaseRoutes.Post.Handle("", api.APILocal(getPost)).Methods("GET") - api.BaseRoutes.PostsForChannel.Handle("", api.ApiLocal(getPostsForChannel)).Methods("GET") + api.BaseRoutes.PostsForChannel.Handle("", api.APILocal(getPostsForChannel)).Methods("GET") } diff --git a/api4/post_test.go b/api4/post_test.go index 547bc39d26..cc40f6a65a 100644 --- a/api4/post_test.go +++ b/api4/post_test.go @@ -207,7 +207,7 @@ func TestCreatePost(t *testing.T) { require.Error(t, err) CheckForbiddenStatus(t, resp) - r, err := client.DoApiPost("/posts", "garbage") + r, err := client.DoAPIPost("/posts", "garbage") require.Error(t, err) require.Equal(t, http.StatusBadRequest, r.StatusCode) @@ -239,7 +239,7 @@ func TestCreatePostEphemeral(t *testing.T) { require.Equal(t, ephemeralPost.Post.Message, rpost.Message, "message didn't match") require.Equal(t, 0, int(rpost.EditAt), "newly created ephemeral post shouldn't have EditAt set") - r, err := client.DoApiPost("/posts/ephemeral", "garbage") + r, err := client.DoAPIPost("/posts/ephemeral", "garbage") require.Error(t, err) require.Equal(t, http.StatusBadRequest, r.StatusCode) @@ -641,7 +641,7 @@ func TestCreatePostCheckOnlineStatus(t *testing.T) { } } - handler := api.ApiHandler(createPost) + handler := api.APIHandler(createPost) resp := httptest.NewRecorder() post := &model.Post{ ChannelId: th.BasicChannel.Id, @@ -926,7 +926,7 @@ func TestPatchPost(t *testing.T) { }) t.Run("invalid requests", func(t *testing.T) { - r, err := client.DoApiPut("/posts/"+post.Id+"/patch", "garbage") + r, err := client.DoAPIPut("/posts/"+post.Id+"/patch", "garbage") require.EqualError(t, err, ": Invalid or missing post in request body., ") require.Equal(t, http.StatusBadRequest, r.StatusCode, "wrong status code") diff --git a/api4/preference.go b/api4/preference.go index b321afec8a..80459df02b 100644 --- a/api4/preference.go +++ b/api4/preference.go @@ -13,11 +13,11 @@ import ( ) func (api *API) InitPreference() { - api.BaseRoutes.Preferences.Handle("", api.ApiSessionRequired(getPreferences)).Methods("GET") - api.BaseRoutes.Preferences.Handle("", api.ApiSessionRequired(updatePreferences)).Methods("PUT") - api.BaseRoutes.Preferences.Handle("/delete", api.ApiSessionRequired(deletePreferences)).Methods("POST") - api.BaseRoutes.Preferences.Handle("/{category:[A-Za-z0-9_]+}", api.ApiSessionRequired(getPreferencesByCategory)).Methods("GET") - api.BaseRoutes.Preferences.Handle("/{category:[A-Za-z0-9_]+}/name/{preference_name:[A-Za-z0-9_]+}", api.ApiSessionRequired(getPreferenceByCategoryAndName)).Methods("GET") + api.BaseRoutes.Preferences.Handle("", api.APISessionRequired(getPreferences)).Methods("GET") + api.BaseRoutes.Preferences.Handle("", api.APISessionRequired(updatePreferences)).Methods("PUT") + api.BaseRoutes.Preferences.Handle("/delete", api.APISessionRequired(deletePreferences)).Methods("POST") + api.BaseRoutes.Preferences.Handle("/{category:[A-Za-z0-9_]+}", api.APISessionRequired(getPreferencesByCategory)).Methods("GET") + api.BaseRoutes.Preferences.Handle("/{category:[A-Za-z0-9_]+}/name/{preference_name:[A-Za-z0-9_]+}", api.APISessionRequired(getPreferenceByCategoryAndName)).Methods("GET") } func getPreferences(c *Context, w http.ResponseWriter, r *http.Request) { diff --git a/api4/reaction.go b/api4/reaction.go index f6114b842b..2f8369071c 100644 --- a/api4/reaction.go +++ b/api4/reaction.go @@ -12,10 +12,10 @@ import ( ) func (api *API) InitReaction() { - api.BaseRoutes.Reactions.Handle("", api.ApiSessionRequired(saveReaction)).Methods("POST") - api.BaseRoutes.Post.Handle("/reactions", api.ApiSessionRequired(getReactions)).Methods("GET") - api.BaseRoutes.ReactionByNameForPostForUser.Handle("", api.ApiSessionRequired(deleteReaction)).Methods("DELETE") - api.BaseRoutes.Posts.Handle("/ids/reactions", api.ApiSessionRequired(getBulkReactions)).Methods("POST") + api.BaseRoutes.Reactions.Handle("", api.APISessionRequired(saveReaction)).Methods("POST") + api.BaseRoutes.Post.Handle("/reactions", api.APISessionRequired(getReactions)).Methods("GET") + api.BaseRoutes.ReactionByNameForPostForUser.Handle("", api.APISessionRequired(deleteReaction)).Methods("DELETE") + api.BaseRoutes.Posts.Handle("/ids/reactions", api.APISessionRequired(getBulkReactions)).Methods("POST") } func saveReaction(c *Context, w http.ResponseWriter, r *http.Request) { diff --git a/api4/remote_cluster.go b/api4/remote_cluster.go index cd160cb5bc..4d03ce9a70 100644 --- a/api4/remote_cluster.go +++ b/api4/remote_cluster.go @@ -262,7 +262,7 @@ func remoteSetProfileImage(c *Context, w http.ResponseWriter, r *http.Request) { user, err := c.App.GetUser(c.Params.UserId) if err != nil || !user.IsRemote() { - c.SetInvalidUrlParam("user_id") + c.SetInvalidURLParam("user_id") return } auditRec.AddMeta("user", user) diff --git a/api4/role.go b/api4/role.go index 5fdd031317..9df05f43b4 100644 --- a/api4/role.go +++ b/api4/role.go @@ -19,10 +19,10 @@ var notAllowedPermissions = []string{ } func (api *API) InitRole() { - api.BaseRoutes.Roles.Handle("/{role_id:[A-Za-z0-9]+}", api.ApiSessionRequiredTrustRequester(getRole)).Methods("GET") - api.BaseRoutes.Roles.Handle("/name/{role_name:[a-z0-9_]+}", api.ApiSessionRequiredTrustRequester(getRoleByName)).Methods("GET") - api.BaseRoutes.Roles.Handle("/names", api.ApiSessionRequiredTrustRequester(getRolesByNames)).Methods("POST") - api.BaseRoutes.Roles.Handle("/{role_id:[A-Za-z0-9]+}/patch", api.ApiSessionRequired(patchRole)).Methods("PUT") + api.BaseRoutes.Roles.Handle("/{role_id:[A-Za-z0-9]+}", api.APISessionRequiredTrustRequester(getRole)).Methods("GET") + api.BaseRoutes.Roles.Handle("/name/{role_name:[a-z0-9_]+}", api.APISessionRequiredTrustRequester(getRoleByName)).Methods("GET") + api.BaseRoutes.Roles.Handle("/names", api.APISessionRequiredTrustRequester(getRolesByNames)).Methods("POST") + api.BaseRoutes.Roles.Handle("/{role_id:[A-Za-z0-9]+}/patch", api.APISessionRequired(patchRole)).Methods("PUT") } func getRole(c *Context, w http.ResponseWriter, r *http.Request) { diff --git a/api4/role_local.go b/api4/role_local.go index a738690eae..9a2bdcb806 100644 --- a/api4/role_local.go +++ b/api4/role_local.go @@ -4,8 +4,8 @@ package api4 func (api *API) InitRoleLocal() { - api.BaseRoutes.Roles.Handle("/{role_id:[A-Za-z0-9]+}", api.ApiLocal(getRole)).Methods("GET") - api.BaseRoutes.Roles.Handle("/name/{role_name:[a-z0-9_]+}", api.ApiLocal(getRoleByName)).Methods("GET") - api.BaseRoutes.Roles.Handle("/names", api.ApiLocal(getRolesByNames)).Methods("POST") - api.BaseRoutes.Roles.Handle("/{role_id:[A-Za-z0-9]+}/patch", api.ApiLocal(patchRole)).Methods("PUT") + api.BaseRoutes.Roles.Handle("/{role_id:[A-Za-z0-9]+}", api.APILocal(getRole)).Methods("GET") + api.BaseRoutes.Roles.Handle("/name/{role_name:[a-z0-9_]+}", api.APILocal(getRoleByName)).Methods("GET") + api.BaseRoutes.Roles.Handle("/names", api.APILocal(getRolesByNames)).Methods("POST") + api.BaseRoutes.Roles.Handle("/{role_id:[A-Za-z0-9]+}/patch", api.APILocal(patchRole)).Methods("PUT") } diff --git a/api4/saml.go b/api4/saml.go index f945c32e79..2c2f2d8981 100644 --- a/api4/saml.go +++ b/api4/saml.go @@ -16,25 +16,25 @@ import ( ) func (api *API) InitSaml() { - api.BaseRoutes.SAML.Handle("/metadata", api.ApiHandler(getSamlMetadata)).Methods("GET") + api.BaseRoutes.SAML.Handle("/metadata", api.APIHandler(getSamlMetadata)).Methods("GET") - api.BaseRoutes.SAML.Handle("/certificate/public", api.ApiSessionRequired(addSamlPublicCertificate)).Methods("POST") - api.BaseRoutes.SAML.Handle("/certificate/private", api.ApiSessionRequired(addSamlPrivateCertificate)).Methods("POST") - api.BaseRoutes.SAML.Handle("/certificate/idp", api.ApiSessionRequired(addSamlIdpCertificate)).Methods("POST") + api.BaseRoutes.SAML.Handle("/certificate/public", api.APISessionRequired(addSamlPublicCertificate)).Methods("POST") + api.BaseRoutes.SAML.Handle("/certificate/private", api.APISessionRequired(addSamlPrivateCertificate)).Methods("POST") + api.BaseRoutes.SAML.Handle("/certificate/idp", api.APISessionRequired(addSamlIdpCertificate)).Methods("POST") - api.BaseRoutes.SAML.Handle("/certificate/public", api.ApiSessionRequired(removeSamlPublicCertificate)).Methods("DELETE") - api.BaseRoutes.SAML.Handle("/certificate/private", api.ApiSessionRequired(removeSamlPrivateCertificate)).Methods("DELETE") - api.BaseRoutes.SAML.Handle("/certificate/idp", api.ApiSessionRequired(removeSamlIdpCertificate)).Methods("DELETE") + api.BaseRoutes.SAML.Handle("/certificate/public", api.APISessionRequired(removeSamlPublicCertificate)).Methods("DELETE") + api.BaseRoutes.SAML.Handle("/certificate/private", api.APISessionRequired(removeSamlPrivateCertificate)).Methods("DELETE") + api.BaseRoutes.SAML.Handle("/certificate/idp", api.APISessionRequired(removeSamlIdpCertificate)).Methods("DELETE") - api.BaseRoutes.SAML.Handle("/certificate/status", api.ApiSessionRequired(getSamlCertificateStatus)).Methods("GET") + api.BaseRoutes.SAML.Handle("/certificate/status", api.APISessionRequired(getSamlCertificateStatus)).Methods("GET") - api.BaseRoutes.SAML.Handle("/metadatafromidp", api.ApiHandler(getSamlMetadataFromIdp)).Methods("POST") + api.BaseRoutes.SAML.Handle("/metadatafromidp", api.APIHandler(getSamlMetadataFromIdp)).Methods("POST") - api.BaseRoutes.SAML.Handle("/reset_auth_data", api.ApiSessionRequired(resetAuthDataToEmail)).Methods("POST") + api.BaseRoutes.SAML.Handle("/reset_auth_data", api.APISessionRequired(resetAuthDataToEmail)).Methods("POST") } func (api *API) InitSamlLocal() { - api.BaseRoutes.SAML.Handle("/reset_auth_data", api.ApiLocal(resetAuthDataToEmail)).Methods("POST") + api.BaseRoutes.SAML.Handle("/reset_auth_data", api.APILocal(resetAuthDataToEmail)).Methods("POST") } func getSamlMetadata(c *Context, w http.ResponseWriter, r *http.Request) { diff --git a/api4/saml_test.go b/api4/saml_test.go index 7100f82410..c1f21c2a70 100644 --- a/api4/saml_test.go +++ b/api4/saml_test.go @@ -29,7 +29,7 @@ func TestSamlCompleteCSRFPass(t *testing.T) { th := Setup(t).InitBasic() defer th.TearDown() - url := th.Client.Url + "/login/sso/saml" + url := th.Client.URL + "/login/sso/saml" req, err := http.NewRequest("POST", url, nil) if err != nil { return diff --git a/api4/scheme.go b/api4/scheme.go index 191407e168..8eea49c4e0 100644 --- a/api4/scheme.go +++ b/api4/scheme.go @@ -13,13 +13,13 @@ import ( ) func (api *API) InitScheme() { - api.BaseRoutes.Schemes.Handle("", api.ApiSessionRequired(getSchemes)).Methods("GET") - api.BaseRoutes.Schemes.Handle("", api.ApiSessionRequired(createScheme)).Methods("POST") - api.BaseRoutes.Schemes.Handle("/{scheme_id:[A-Za-z0-9]+}", api.ApiSessionRequired(deleteScheme)).Methods("DELETE") - api.BaseRoutes.Schemes.Handle("/{scheme_id:[A-Za-z0-9]+}", api.ApiSessionRequiredTrustRequester(getScheme)).Methods("GET") - api.BaseRoutes.Schemes.Handle("/{scheme_id:[A-Za-z0-9]+}/patch", api.ApiSessionRequired(patchScheme)).Methods("PUT") - api.BaseRoutes.Schemes.Handle("/{scheme_id:[A-Za-z0-9]+}/teams", api.ApiSessionRequiredTrustRequester(getTeamsForScheme)).Methods("GET") - api.BaseRoutes.Schemes.Handle("/{scheme_id:[A-Za-z0-9]+}/channels", api.ApiSessionRequiredTrustRequester(getChannelsForScheme)).Methods("GET") + api.BaseRoutes.Schemes.Handle("", api.APISessionRequired(getSchemes)).Methods("GET") + api.BaseRoutes.Schemes.Handle("", api.APISessionRequired(createScheme)).Methods("POST") + api.BaseRoutes.Schemes.Handle("/{scheme_id:[A-Za-z0-9]+}", api.APISessionRequired(deleteScheme)).Methods("DELETE") + api.BaseRoutes.Schemes.Handle("/{scheme_id:[A-Za-z0-9]+}", api.APISessionRequiredTrustRequester(getScheme)).Methods("GET") + api.BaseRoutes.Schemes.Handle("/{scheme_id:[A-Za-z0-9]+}/patch", api.APISessionRequired(patchScheme)).Methods("PUT") + api.BaseRoutes.Schemes.Handle("/{scheme_id:[A-Za-z0-9]+}/teams", api.APISessionRequiredTrustRequester(getTeamsForScheme)).Methods("GET") + api.BaseRoutes.Schemes.Handle("/{scheme_id:[A-Za-z0-9]+}/channels", api.APISessionRequiredTrustRequester(getChannelsForScheme)).Methods("GET") } func createScheme(c *Context, w http.ResponseWriter, r *http.Request) { diff --git a/api4/shared_channel.go b/api4/shared_channel.go index b98a4016b6..a3ef245a98 100644 --- a/api4/shared_channel.go +++ b/api4/shared_channel.go @@ -11,8 +11,8 @@ import ( ) func (api *API) InitSharedChannels() { - api.BaseRoutes.SharedChannels.Handle("/{team_id:[A-Za-z0-9]+}", api.ApiSessionRequired(getSharedChannels)).Methods("GET") - api.BaseRoutes.SharedChannels.Handle("/remote_info/{remote_id:[A-Za-z0-9]+}", api.ApiSessionRequired(getRemoteClusterInfo)).Methods("GET") + api.BaseRoutes.SharedChannels.Handle("/{team_id:[A-Za-z0-9]+}", api.APISessionRequired(getSharedChannels)).Methods("GET") + api.BaseRoutes.SharedChannels.Handle("/remote_info/{remote_id:[A-Za-z0-9]+}", api.APISessionRequired(getRemoteClusterInfo)).Methods("GET") } func getSharedChannels(c *Context, w http.ResponseWriter, r *http.Request) { diff --git a/api4/status.go b/api4/status.go index df4cc86281..3247c9cce5 100644 --- a/api4/status.go +++ b/api4/status.go @@ -12,16 +12,16 @@ import ( ) func (api *API) InitStatus() { - api.BaseRoutes.User.Handle("/status", api.ApiSessionRequired(getUserStatus)).Methods("GET") - api.BaseRoutes.Users.Handle("/status/ids", api.ApiSessionRequired(getUserStatusesByIds)).Methods("POST") - api.BaseRoutes.User.Handle("/status", api.ApiSessionRequired(updateUserStatus)).Methods("PUT") - api.BaseRoutes.User.Handle("/status/custom", api.ApiSessionRequired(updateUserCustomStatus)).Methods("PUT") - api.BaseRoutes.User.Handle("/status/custom", api.ApiSessionRequired(removeUserCustomStatus)).Methods("DELETE") + api.BaseRoutes.User.Handle("/status", api.APISessionRequired(getUserStatus)).Methods("GET") + api.BaseRoutes.Users.Handle("/status/ids", api.APISessionRequired(getUserStatusesByIds)).Methods("POST") + api.BaseRoutes.User.Handle("/status", api.APISessionRequired(updateUserStatus)).Methods("PUT") + api.BaseRoutes.User.Handle("/status/custom", api.APISessionRequired(updateUserCustomStatus)).Methods("PUT") + api.BaseRoutes.User.Handle("/status/custom", api.APISessionRequired(removeUserCustomStatus)).Methods("DELETE") // Both these handlers are for removing the recent custom status but the one with the POST method should be preferred // as DELETE method doesn't support request body in the mobile app. - api.BaseRoutes.User.Handle("/status/custom/recent", api.ApiSessionRequired(removeUserRecentCustomStatus)).Methods("DELETE") - api.BaseRoutes.User.Handle("/status/custom/recent/delete", api.ApiSessionRequired(removeUserRecentCustomStatus)).Methods("POST") + api.BaseRoutes.User.Handle("/status/custom/recent", api.APISessionRequired(removeUserRecentCustomStatus)).Methods("DELETE") + api.BaseRoutes.User.Handle("/status/custom/recent/delete", api.APISessionRequired(removeUserRecentCustomStatus)).Methods("POST") } func getUserStatus(c *Context, w http.ResponseWriter, r *http.Request) { diff --git a/api4/system.go b/api4/system.go index d3374433d7..25b0da4866 100644 --- a/api4/system.go +++ b/api4/system.go @@ -35,39 +35,39 @@ var redirectLocationDataCache = cache.NewLRU(cache.LRUOptions{ }) func (api *API) InitSystem() { - api.BaseRoutes.System.Handle("/ping", api.ApiHandler(getSystemPing)).Methods("GET") + api.BaseRoutes.System.Handle("/ping", api.APIHandler(getSystemPing)).Methods("GET") - api.BaseRoutes.System.Handle("/timezones", api.ApiSessionRequired(getSupportedTimezones)).Methods("GET") + api.BaseRoutes.System.Handle("/timezones", api.APISessionRequired(getSupportedTimezones)).Methods("GET") - api.BaseRoutes.ApiRoot.Handle("/audits", api.ApiSessionRequired(getAudits)).Methods("GET") - api.BaseRoutes.ApiRoot.Handle("/email/test", api.ApiSessionRequired(testEmail)).Methods("POST") - api.BaseRoutes.ApiRoot.Handle("/site_url/test", api.ApiSessionRequired(testSiteURL)).Methods("POST") - api.BaseRoutes.ApiRoot.Handle("/file/s3_test", api.ApiSessionRequired(testS3)).Methods("POST") - api.BaseRoutes.ApiRoot.Handle("/database/recycle", api.ApiSessionRequired(databaseRecycle)).Methods("POST") - api.BaseRoutes.ApiRoot.Handle("/caches/invalidate", api.ApiSessionRequired(invalidateCaches)).Methods("POST") + api.BaseRoutes.APIRoot.Handle("/audits", api.APISessionRequired(getAudits)).Methods("GET") + api.BaseRoutes.APIRoot.Handle("/email/test", api.APISessionRequired(testEmail)).Methods("POST") + api.BaseRoutes.APIRoot.Handle("/site_url/test", api.APISessionRequired(testSiteURL)).Methods("POST") + api.BaseRoutes.APIRoot.Handle("/file/s3_test", api.APISessionRequired(testS3)).Methods("POST") + api.BaseRoutes.APIRoot.Handle("/database/recycle", api.APISessionRequired(databaseRecycle)).Methods("POST") + api.BaseRoutes.APIRoot.Handle("/caches/invalidate", api.APISessionRequired(invalidateCaches)).Methods("POST") - api.BaseRoutes.ApiRoot.Handle("/logs", api.ApiSessionRequired(getLogs)).Methods("GET") - api.BaseRoutes.ApiRoot.Handle("/logs", api.ApiHandler(postLog)).Methods("POST") + api.BaseRoutes.APIRoot.Handle("/logs", api.APISessionRequired(getLogs)).Methods("GET") + api.BaseRoutes.APIRoot.Handle("/logs", api.APIHandler(postLog)).Methods("POST") - api.BaseRoutes.ApiRoot.Handle("/analytics/old", api.ApiSessionRequired(getAnalytics)).Methods("GET") + api.BaseRoutes.APIRoot.Handle("/analytics/old", api.APISessionRequired(getAnalytics)).Methods("GET") - api.BaseRoutes.ApiRoot.Handle("/redirect_location", api.ApiSessionRequiredTrustRequester(getRedirectLocation)).Methods("GET") + api.BaseRoutes.APIRoot.Handle("/redirect_location", api.APISessionRequiredTrustRequester(getRedirectLocation)).Methods("GET") - api.BaseRoutes.ApiRoot.Handle("/notifications/ack", api.ApiSessionRequired(pushNotificationAck)).Methods("POST") + api.BaseRoutes.APIRoot.Handle("/notifications/ack", api.APISessionRequired(pushNotificationAck)).Methods("POST") - api.BaseRoutes.ApiRoot.Handle("/server_busy", api.ApiSessionRequired(setServerBusy)).Methods("POST") - api.BaseRoutes.ApiRoot.Handle("/server_busy", api.ApiSessionRequired(getServerBusyExpires)).Methods("GET") - api.BaseRoutes.ApiRoot.Handle("/server_busy", api.ApiSessionRequired(clearServerBusy)).Methods("DELETE") - api.BaseRoutes.ApiRoot.Handle("/upgrade_to_enterprise", api.ApiSessionRequired(upgradeToEnterprise)).Methods("POST") - api.BaseRoutes.ApiRoot.Handle("/upgrade_to_enterprise/status", api.ApiSessionRequired(upgradeToEnterpriseStatus)).Methods("GET") - api.BaseRoutes.ApiRoot.Handle("/restart", api.ApiSessionRequired(restart)).Methods("POST") - api.BaseRoutes.ApiRoot.Handle("/warn_metrics/status", api.ApiSessionRequired(getWarnMetricsStatus)).Methods("GET") - api.BaseRoutes.ApiRoot.Handle("/warn_metrics/ack/{warn_metric_id:[A-Za-z0-9-_]+}", api.ApiHandler(sendWarnMetricAckEmail)).Methods("POST") - api.BaseRoutes.ApiRoot.Handle("/warn_metrics/trial-license-ack/{warn_metric_id:[A-Za-z0-9-_]+}", api.ApiHandler(requestTrialLicenseAndAckWarnMetric)).Methods("POST") - api.BaseRoutes.System.Handle("/notices/{team_id:[A-Za-z0-9]+}", api.ApiSessionRequired(getProductNotices)).Methods("GET") - api.BaseRoutes.System.Handle("/notices/view", api.ApiSessionRequired(updateViewedProductNotices)).Methods("PUT") + api.BaseRoutes.APIRoot.Handle("/server_busy", api.APISessionRequired(setServerBusy)).Methods("POST") + api.BaseRoutes.APIRoot.Handle("/server_busy", api.APISessionRequired(getServerBusyExpires)).Methods("GET") + api.BaseRoutes.APIRoot.Handle("/server_busy", api.APISessionRequired(clearServerBusy)).Methods("DELETE") + api.BaseRoutes.APIRoot.Handle("/upgrade_to_enterprise", api.APISessionRequired(upgradeToEnterprise)).Methods("POST") + api.BaseRoutes.APIRoot.Handle("/upgrade_to_enterprise/status", api.APISessionRequired(upgradeToEnterpriseStatus)).Methods("GET") + api.BaseRoutes.APIRoot.Handle("/restart", api.APISessionRequired(restart)).Methods("POST") + api.BaseRoutes.APIRoot.Handle("/warn_metrics/status", api.APISessionRequired(getWarnMetricsStatus)).Methods("GET") + api.BaseRoutes.APIRoot.Handle("/warn_metrics/ack/{warn_metric_id:[A-Za-z0-9-_]+}", api.APIHandler(sendWarnMetricAckEmail)).Methods("POST") + api.BaseRoutes.APIRoot.Handle("/warn_metrics/trial-license-ack/{warn_metric_id:[A-Za-z0-9-_]+}", api.APIHandler(requestTrialLicenseAndAckWarnMetric)).Methods("POST") + api.BaseRoutes.System.Handle("/notices/{team_id:[A-Za-z0-9]+}", api.APISessionRequired(getProductNotices)).Methods("GET") + api.BaseRoutes.System.Handle("/notices/view", api.APISessionRequired(updateViewedProductNotices)).Methods("PUT") - api.BaseRoutes.System.Handle("/support_packet", api.ApiSessionRequired(generateSupportPacket)).Methods("GET") + api.BaseRoutes.System.Handle("/support_packet", api.APISessionRequired(generateSupportPacket)).Methods("GET") } func generateSupportPacket(c *Context, w http.ResponseWriter, r *http.Request) { @@ -215,8 +215,8 @@ func testEmail(c *Context, w http.ResponseWriter, r *http.Request) { } func testSiteURL(c *Context, w http.ResponseWriter, r *http.Request) { - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionTestSiteUrl) { - c.SetPermissionError(model.PermissionTestSiteUrl) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionTestSiteURL) { + c.SetPermissionError(model.PermissionTestSiteURL) return } @@ -575,7 +575,7 @@ func setServerBusy(c *Context, w http.ResponseWriter, r *http.Request) { i, err := strconv.ParseInt(secs, 10, 64) if err != nil || i <= 0 || i > MaxServerBusySeconds { - c.SetInvalidUrlParam(fmt.Sprintf("seconds must be 1 - %d", MaxServerBusySeconds)) + c.SetInvalidURLParam(fmt.Sprintf("seconds must be 1 - %d", MaxServerBusySeconds)) return } diff --git a/api4/system_local.go b/api4/system_local.go index 796d0318be..872ac38609 100644 --- a/api4/system_local.go +++ b/api4/system_local.go @@ -12,12 +12,12 @@ import ( ) func (api *API) InitSystemLocal() { - api.BaseRoutes.System.Handle("/ping", api.ApiLocal(getSystemPing)).Methods("GET") - api.BaseRoutes.ApiRoot.Handle("/logs", api.ApiLocal(getLogs)).Methods("GET") - api.BaseRoutes.ApiRoot.Handle("/server_busy", api.ApiLocal(setServerBusy)).Methods("POST") - api.BaseRoutes.ApiRoot.Handle("/server_busy", api.ApiLocal(getServerBusyExpires)).Methods("GET") - api.BaseRoutes.ApiRoot.Handle("/server_busy", api.ApiLocal(clearServerBusy)).Methods("DELETE") - api.BaseRoutes.ApiRoot.Handle("/integrity", api.ApiLocal(localCheckIntegrity)).Methods("POST") + api.BaseRoutes.System.Handle("/ping", api.APILocal(getSystemPing)).Methods("GET") + api.BaseRoutes.APIRoot.Handle("/logs", api.APILocal(getLogs)).Methods("GET") + api.BaseRoutes.APIRoot.Handle("/server_busy", api.APILocal(setServerBusy)).Methods("POST") + api.BaseRoutes.APIRoot.Handle("/server_busy", api.APILocal(getServerBusyExpires)).Methods("GET") + api.BaseRoutes.APIRoot.Handle("/server_busy", api.APILocal(clearServerBusy)).Methods("DELETE") + api.BaseRoutes.APIRoot.Handle("/integrity", api.APILocal(localCheckIntegrity)).Methods("POST") } func localCheckIntegrity(c *Context, w http.ResponseWriter, r *http.Request) { diff --git a/api4/system_test.go b/api4/system_test.go index f5c8731178..75e8474706 100644 --- a/api4/system_test.go +++ b/api4/system_test.go @@ -71,7 +71,7 @@ func TestGetPing(t *testing.T) { th.TestForAllClients(t, func(t *testing.T, client *model.Client4) { th.App.ReloadConfig() - resp, err := client.DoApiGet("/system/ping", "") + resp, err := client.DoAPIGet("/system/ping", "") require.NoError(t, err) require.Equal(t, http.StatusOK, resp.StatusCode) respBytes, err := ioutil.ReadAll(resp.Body) @@ -84,7 +84,7 @@ func TestGetPing(t *testing.T) { defer os.Unsetenv("MM_FEATUREFLAGS_TESTFEATURE") th.App.ReloadConfig() - resp, err = client.DoApiGet("/system/ping", "") + resp, err = client.DoAPIGet("/system/ping", "") require.NoError(t, err) require.Equal(t, http.StatusOK, resp.StatusCode) respBytes, err = ioutil.ReadAll(resp.Body) @@ -750,7 +750,7 @@ func TestPushNotificationAck(t *testing.T) { defer th.TearDown() t.Run("should return error when the ack body is not passed", func(t *testing.T) { - handler := api.ApiHandler(pushNotificationAck) + handler := api.APIHandler(pushNotificationAck) resp := httptest.NewRecorder() req := httptest.NewRequest("POST", "/api/v4/notifications/ack", nil) req.Header.Set(model.HeaderAuth, "Bearer "+session.Token) @@ -764,7 +764,7 @@ func TestPushNotificationAck(t *testing.T) { privateChannel := th.CreateChannelWithClient(th.SystemAdminClient, model.ChannelTypePrivate) privatePost := th.CreatePostWithClient(th.SystemAdminClient, privateChannel) - handler := api.ApiHandler(pushNotificationAck) + handler := api.APIHandler(pushNotificationAck) resp := httptest.NewRecorder() req := httptest.NewRequest("POST", "/api/v4/notifications/ack", nil) req.Header.Set(model.HeaderAuth, "Bearer "+session.Token) diff --git a/api4/team.go b/api4/team.go index aa7cf31ad0..9ce00a67c8 100644 --- a/api4/team.go +++ b/api4/team.go @@ -33,48 +33,48 @@ func init() { } func (api *API) InitTeam() { - api.BaseRoutes.Teams.Handle("", api.ApiSessionRequired(createTeam)).Methods("POST") - api.BaseRoutes.Teams.Handle("", api.ApiSessionRequired(getAllTeams)).Methods("GET") - api.BaseRoutes.Teams.Handle("/{team_id:[A-Za-z0-9]+}/scheme", api.ApiSessionRequired(updateTeamScheme)).Methods("PUT") - api.BaseRoutes.Teams.Handle("/search", api.ApiSessionRequiredDisableWhenBusy(searchTeams)).Methods("POST") - api.BaseRoutes.TeamsForUser.Handle("", api.ApiSessionRequired(getTeamsForUser)).Methods("GET") - api.BaseRoutes.TeamsForUser.Handle("/unread", api.ApiSessionRequired(getTeamsUnreadForUser)).Methods("GET") + api.BaseRoutes.Teams.Handle("", api.APISessionRequired(createTeam)).Methods("POST") + api.BaseRoutes.Teams.Handle("", api.APISessionRequired(getAllTeams)).Methods("GET") + api.BaseRoutes.Teams.Handle("/{team_id:[A-Za-z0-9]+}/scheme", api.APISessionRequired(updateTeamScheme)).Methods("PUT") + api.BaseRoutes.Teams.Handle("/search", api.APISessionRequiredDisableWhenBusy(searchTeams)).Methods("POST") + api.BaseRoutes.TeamsForUser.Handle("", api.APISessionRequired(getTeamsForUser)).Methods("GET") + api.BaseRoutes.TeamsForUser.Handle("/unread", api.APISessionRequired(getTeamsUnreadForUser)).Methods("GET") - api.BaseRoutes.Team.Handle("", api.ApiSessionRequired(getTeam)).Methods("GET") - api.BaseRoutes.Team.Handle("", api.ApiSessionRequired(updateTeam)).Methods("PUT") - api.BaseRoutes.Team.Handle("", api.ApiSessionRequired(deleteTeam)).Methods("DELETE") - api.BaseRoutes.Team.Handle("/patch", api.ApiSessionRequired(patchTeam)).Methods("PUT") - api.BaseRoutes.Team.Handle("/restore", api.ApiSessionRequired(restoreTeam)).Methods("POST") - api.BaseRoutes.Team.Handle("/privacy", api.ApiSessionRequired(updateTeamPrivacy)).Methods("PUT") - api.BaseRoutes.Team.Handle("/stats", api.ApiSessionRequired(getTeamStats)).Methods("GET") - api.BaseRoutes.Team.Handle("/regenerate_invite_id", api.ApiSessionRequired(regenerateTeamInviteId)).Methods("POST") + api.BaseRoutes.Team.Handle("", api.APISessionRequired(getTeam)).Methods("GET") + api.BaseRoutes.Team.Handle("", api.APISessionRequired(updateTeam)).Methods("PUT") + api.BaseRoutes.Team.Handle("", api.APISessionRequired(deleteTeam)).Methods("DELETE") + api.BaseRoutes.Team.Handle("/patch", api.APISessionRequired(patchTeam)).Methods("PUT") + api.BaseRoutes.Team.Handle("/restore", api.APISessionRequired(restoreTeam)).Methods("POST") + api.BaseRoutes.Team.Handle("/privacy", api.APISessionRequired(updateTeamPrivacy)).Methods("PUT") + api.BaseRoutes.Team.Handle("/stats", api.APISessionRequired(getTeamStats)).Methods("GET") + api.BaseRoutes.Team.Handle("/regenerate_invite_id", api.APISessionRequired(regenerateTeamInviteId)).Methods("POST") - api.BaseRoutes.Team.Handle("/image", api.ApiSessionRequiredTrustRequester(getTeamIcon)).Methods("GET") - api.BaseRoutes.Team.Handle("/image", api.ApiSessionRequired(setTeamIcon)).Methods("POST") - api.BaseRoutes.Team.Handle("/image", api.ApiSessionRequired(removeTeamIcon)).Methods("DELETE") + api.BaseRoutes.Team.Handle("/image", api.APISessionRequiredTrustRequester(getTeamIcon)).Methods("GET") + api.BaseRoutes.Team.Handle("/image", api.APISessionRequired(setTeamIcon)).Methods("POST") + api.BaseRoutes.Team.Handle("/image", api.APISessionRequired(removeTeamIcon)).Methods("DELETE") - api.BaseRoutes.TeamMembers.Handle("", api.ApiSessionRequired(getTeamMembers)).Methods("GET") - api.BaseRoutes.TeamMembers.Handle("/ids", api.ApiSessionRequired(getTeamMembersByIds)).Methods("POST") - api.BaseRoutes.TeamMembersForUser.Handle("", api.ApiSessionRequired(getTeamMembersForUser)).Methods("GET") - api.BaseRoutes.TeamMembers.Handle("", api.ApiSessionRequired(addTeamMember)).Methods("POST") - api.BaseRoutes.Teams.Handle("/members/invite", api.ApiSessionRequired(addUserToTeamFromInvite)).Methods("POST") - api.BaseRoutes.TeamMembers.Handle("/batch", api.ApiSessionRequired(addTeamMembers)).Methods("POST") - api.BaseRoutes.TeamMember.Handle("", api.ApiSessionRequired(removeTeamMember)).Methods("DELETE") + api.BaseRoutes.TeamMembers.Handle("", api.APISessionRequired(getTeamMembers)).Methods("GET") + api.BaseRoutes.TeamMembers.Handle("/ids", api.APISessionRequired(getTeamMembersByIds)).Methods("POST") + api.BaseRoutes.TeamMembersForUser.Handle("", api.APISessionRequired(getTeamMembersForUser)).Methods("GET") + api.BaseRoutes.TeamMembers.Handle("", api.APISessionRequired(addTeamMember)).Methods("POST") + api.BaseRoutes.Teams.Handle("/members/invite", api.APISessionRequired(addUserToTeamFromInvite)).Methods("POST") + api.BaseRoutes.TeamMembers.Handle("/batch", api.APISessionRequired(addTeamMembers)).Methods("POST") + api.BaseRoutes.TeamMember.Handle("", api.APISessionRequired(removeTeamMember)).Methods("DELETE") - api.BaseRoutes.TeamForUser.Handle("/unread", api.ApiSessionRequired(getTeamUnread)).Methods("GET") + api.BaseRoutes.TeamForUser.Handle("/unread", api.APISessionRequired(getTeamUnread)).Methods("GET") - api.BaseRoutes.TeamByName.Handle("", api.ApiSessionRequired(getTeamByName)).Methods("GET") - api.BaseRoutes.TeamMember.Handle("", api.ApiSessionRequired(getTeamMember)).Methods("GET") - api.BaseRoutes.TeamByName.Handle("/exists", api.ApiSessionRequired(teamExists)).Methods("GET") - api.BaseRoutes.TeamMember.Handle("/roles", api.ApiSessionRequired(updateTeamMemberRoles)).Methods("PUT") - api.BaseRoutes.TeamMember.Handle("/schemeRoles", api.ApiSessionRequired(updateTeamMemberSchemeRoles)).Methods("PUT") - api.BaseRoutes.Team.Handle("/import", api.ApiSessionRequired(importTeam)).Methods("POST") - api.BaseRoutes.Team.Handle("/invite/email", api.ApiSessionRequired(inviteUsersToTeam)).Methods("POST") - api.BaseRoutes.Team.Handle("/invite-guests/email", api.ApiSessionRequired(inviteGuestsToChannels)).Methods("POST") - api.BaseRoutes.Teams.Handle("/invites/email", api.ApiSessionRequired(invalidateAllEmailInvites)).Methods("DELETE") - api.BaseRoutes.Teams.Handle("/invite/{invite_id:[A-Za-z0-9]+}", api.ApiHandler(getInviteInfo)).Methods("GET") + api.BaseRoutes.TeamByName.Handle("", api.APISessionRequired(getTeamByName)).Methods("GET") + api.BaseRoutes.TeamMember.Handle("", api.APISessionRequired(getTeamMember)).Methods("GET") + api.BaseRoutes.TeamByName.Handle("/exists", api.APISessionRequired(teamExists)).Methods("GET") + api.BaseRoutes.TeamMember.Handle("/roles", api.APISessionRequired(updateTeamMemberRoles)).Methods("PUT") + api.BaseRoutes.TeamMember.Handle("/schemeRoles", api.APISessionRequired(updateTeamMemberSchemeRoles)).Methods("PUT") + api.BaseRoutes.Team.Handle("/import", api.APISessionRequired(importTeam)).Methods("POST") + api.BaseRoutes.Team.Handle("/invite/email", api.APISessionRequired(inviteUsersToTeam)).Methods("POST") + api.BaseRoutes.Team.Handle("/invite-guests/email", api.APISessionRequired(inviteGuestsToChannels)).Methods("POST") + api.BaseRoutes.Teams.Handle("/invites/email", api.APISessionRequired(invalidateAllEmailInvites)).Methods("DELETE") + api.BaseRoutes.Teams.Handle("/invite/{invite_id:[A-Za-z0-9]+}", api.APIHandler(getInviteInfo)).Methods("GET") - api.BaseRoutes.Teams.Handle("/{team_id:[A-Za-z0-9]+}/members_minus_group_members", api.ApiSessionRequired(teamMembersMinusGroupMembers)).Methods("GET") + api.BaseRoutes.Teams.Handle("/{team_id:[A-Za-z0-9]+}/members_minus_group_members", api.APISessionRequired(teamMembersMinusGroupMembers)).Methods("GET") } func createTeam(c *Context, w http.ResponseWriter, r *http.Request) { diff --git a/api4/team_local.go b/api4/team_local.go index a86ec196b8..95f1aef1cb 100644 --- a/api4/team_local.go +++ b/api4/team_local.go @@ -19,21 +19,21 @@ import ( ) func (api *API) InitTeamLocal() { - api.BaseRoutes.Teams.Handle("", api.ApiLocal(localCreateTeam)).Methods("POST") - api.BaseRoutes.Teams.Handle("", api.ApiLocal(getAllTeams)).Methods("GET") - api.BaseRoutes.Teams.Handle("/search", api.ApiLocal(searchTeams)).Methods("POST") + api.BaseRoutes.Teams.Handle("", api.APILocal(localCreateTeam)).Methods("POST") + api.BaseRoutes.Teams.Handle("", api.APILocal(getAllTeams)).Methods("GET") + api.BaseRoutes.Teams.Handle("/search", api.APILocal(searchTeams)).Methods("POST") - api.BaseRoutes.Team.Handle("", api.ApiLocal(getTeam)).Methods("GET") - api.BaseRoutes.Team.Handle("", api.ApiLocal(updateTeam)).Methods("PUT") - api.BaseRoutes.Team.Handle("", api.ApiLocal(localDeleteTeam)).Methods("DELETE") - api.BaseRoutes.Team.Handle("/invite/email", api.ApiLocal(localInviteUsersToTeam)).Methods("POST") - api.BaseRoutes.Team.Handle("/patch", api.ApiLocal(patchTeam)).Methods("PUT") - api.BaseRoutes.Team.Handle("/privacy", api.ApiLocal(updateTeamPrivacy)).Methods("PUT") - api.BaseRoutes.Team.Handle("/restore", api.ApiLocal(restoreTeam)).Methods("POST") + api.BaseRoutes.Team.Handle("", api.APILocal(getTeam)).Methods("GET") + api.BaseRoutes.Team.Handle("", api.APILocal(updateTeam)).Methods("PUT") + api.BaseRoutes.Team.Handle("", api.APILocal(localDeleteTeam)).Methods("DELETE") + api.BaseRoutes.Team.Handle("/invite/email", api.APILocal(localInviteUsersToTeam)).Methods("POST") + api.BaseRoutes.Team.Handle("/patch", api.APILocal(patchTeam)).Methods("PUT") + api.BaseRoutes.Team.Handle("/privacy", api.APILocal(updateTeamPrivacy)).Methods("PUT") + api.BaseRoutes.Team.Handle("/restore", api.APILocal(restoreTeam)).Methods("POST") - api.BaseRoutes.TeamByName.Handle("", api.ApiLocal(getTeamByName)).Methods("GET") - api.BaseRoutes.TeamMembers.Handle("", api.ApiLocal(addTeamMember)).Methods("POST") - api.BaseRoutes.TeamMember.Handle("", api.ApiLocal(removeTeamMember)).Methods("DELETE") + api.BaseRoutes.TeamByName.Handle("", api.APILocal(getTeamByName)).Methods("GET") + api.BaseRoutes.TeamMembers.Handle("", api.APILocal(addTeamMember)).Methods("POST") + api.BaseRoutes.TeamMember.Handle("", api.APILocal(removeTeamMember)).Methods("DELETE") } func localDeleteTeam(c *Context, w http.ResponseWriter, r *http.Request) { diff --git a/api4/team_test.go b/api4/team_test.go index 8b0174a6b8..7395da6bb4 100644 --- a/api4/team_test.go +++ b/api4/team_test.go @@ -52,7 +52,7 @@ func TestCreateTeam(t *testing.T) { CheckErrorID(t, err, "model.team.is_valid.characters.app_error") CheckBadRequestStatus(t, resp) - r, err := client.DoApiPost("/teams", "garbage") + r, err := client.DoAPIPost("/teams", "garbage") require.Error(t, err, "should have errored") require.Equalf(t, r.StatusCode, http.StatusBadRequest, "wrong status code, actual: %s, expected: %s", strconv.Itoa(r.StatusCode), strconv.Itoa(http.StatusBadRequest)) @@ -343,7 +343,7 @@ func TestUpdateTeam(t *testing.T) { originalTeamId := team.Id team.Id = model.NewId() - r, err := th.Client.DoApiPut("/teams/"+originalTeamId, team.ToJson()) + r, err := th.Client.DoAPIPut("/teams/"+originalTeamId, team.ToJson()) assert.Error(t, err) assert.Equal(t, http.StatusBadRequest, r.StatusCode) @@ -484,7 +484,7 @@ func TestPatchTeam(t *testing.T) { require.Error(t, err) CheckBadRequestStatus(t, resp) - r, err2 := client.DoApiPut("/teams/"+team.Id+"/patch", "garbage") + r, err2 := client.DoAPIPut("/teams/"+team.Id+"/patch", "garbage") require.Error(t, err2, "should have errored") require.Equalf(t, r.StatusCode, http.StatusBadRequest, "wrong status code, actual: %s, expected: %s", strconv.Itoa(r.StatusCode), strconv.Itoa(http.StatusBadRequest)) }) @@ -2029,7 +2029,7 @@ func TestAddTeamMember(t *testing.T) { require.NoError(t, err) // Should return error with invalid JSON in body. - _, err = client.DoApiPost("/teams/"+team.Id+"/members", "invalid") + _, err = client.DoAPIPost("/teams/"+team.Id+"/members", "invalid") require.Error(t, err) CheckErrorID(t, err, "api.team.add_team_member.invalid_body.app_error") @@ -3138,7 +3138,7 @@ func TestInviteGuestsToTeam(t *testing.T) { require.NoError(t, err) t.Run("invalid data in request body", func(t *testing.T) { - res, err := th.SystemAdminClient.DoApiPost("/teams/"+th.BasicTeam.Id+"/invite-guests/email", "bad data") + res, err := th.SystemAdminClient.DoAPIPost("/teams/"+th.BasicTeam.Id+"/invite-guests/email", "bad data") require.Error(t, err) CheckErrorID(t, err, "api.team.invite_guests_to_channels.invalid_body.app_error") require.Equal(t, http.StatusBadRequest, res.StatusCode) diff --git a/api4/terms_of_service.go b/api4/terms_of_service.go index 5e39648578..6070ef1a3e 100644 --- a/api4/terms_of_service.go +++ b/api4/terms_of_service.go @@ -14,8 +14,8 @@ import ( ) func (api *API) InitTermsOfService() { - api.BaseRoutes.TermsOfService.Handle("", api.ApiSessionRequired(getLatestTermsOfService)).Methods("GET") - api.BaseRoutes.TermsOfService.Handle("", api.ApiSessionRequired(createTermsOfService)).Methods("POST") + api.BaseRoutes.TermsOfService.Handle("", api.APISessionRequired(getLatestTermsOfService)).Methods("GET") + api.BaseRoutes.TermsOfService.Handle("", api.APISessionRequired(createTermsOfService)).Methods("POST") } func getLatestTermsOfService(c *Context, w http.ResponseWriter, r *http.Request) { diff --git a/api4/upload.go b/api4/upload.go index 2797f51417..4ba35279db 100644 --- a/api4/upload.go +++ b/api4/upload.go @@ -16,9 +16,9 @@ import ( ) func (api *API) InitUpload() { - api.BaseRoutes.Uploads.Handle("", api.ApiSessionRequired(createUpload)).Methods("POST") - api.BaseRoutes.Upload.Handle("", api.ApiSessionRequired(getUpload)).Methods("GET") - api.BaseRoutes.Upload.Handle("", api.ApiSessionRequired(uploadData)).Methods("POST") + api.BaseRoutes.Uploads.Handle("", api.APISessionRequired(createUpload)).Methods("POST") + api.BaseRoutes.Upload.Handle("", api.APISessionRequired(getUpload)).Methods("GET") + api.BaseRoutes.Upload.Handle("", api.APISessionRequired(uploadData)).Methods("POST") } func createUpload(c *Context, w http.ResponseWriter, r *http.Request) { diff --git a/api4/upload_local.go b/api4/upload_local.go index 136beb7c2f..9e6a32c86b 100644 --- a/api4/upload_local.go +++ b/api4/upload_local.go @@ -4,7 +4,7 @@ package api4 func (api *API) InitUploadLocal() { - api.BaseRoutes.Uploads.Handle("", api.ApiLocal(createUpload)).Methods("POST") - api.BaseRoutes.Upload.Handle("", api.ApiLocal(getUpload)).Methods("GET") - api.BaseRoutes.Upload.Handle("", api.ApiLocal(uploadData)).Methods("POST") + api.BaseRoutes.Uploads.Handle("", api.APILocal(createUpload)).Methods("POST") + api.BaseRoutes.Upload.Handle("", api.APILocal(getUpload)).Methods("GET") + api.BaseRoutes.Upload.Handle("", api.APILocal(uploadData)).Methods("POST") } diff --git a/api4/upload_test.go b/api4/upload_test.go index d057eeda71..d08342279e 100644 --- a/api4/upload_test.go +++ b/api4/upload_test.go @@ -320,7 +320,7 @@ func TestUploadDataMultipart(t *testing.T) { t.Run("success", func(t *testing.T) { mpData, contentType := genMultipartData(t, data) - req, err := http.NewRequest("POST", th.Client.ApiUrl+"/uploads/"+us.Id, mpData) + req, err := http.NewRequest("POST", th.Client.APIURL+"/uploads/"+us.Id, mpData) require.NoError(t, err) req.Header.Set("Content-Type", contentType) req.Header.Set(model.HeaderAuth, th.Client.AuthType+" "+th.Client.AuthToken) @@ -344,7 +344,7 @@ func TestUploadDataMultipart(t *testing.T) { require.NotNil(t, u) require.NotEmpty(t, u) - req, err := http.NewRequest("POST", th.Client.ApiUrl+"/uploads/"+u.Id, mpData) + req, err := http.NewRequest("POST", th.Client.APIURL+"/uploads/"+u.Id, mpData) require.NoError(t, err) req.Header.Set("Content-Type", contentType) req.Header.Set(model.HeaderAuth, th.Client.AuthType+" "+th.Client.AuthToken) @@ -355,7 +355,7 @@ func TestUploadDataMultipart(t *testing.T) { mpData, contentType = genMultipartData(t, data[5*1024*1024:]) - req, err = http.NewRequest("POST", th.Client.ApiUrl+"/uploads/"+u.Id, mpData) + req, err = http.NewRequest("POST", th.Client.APIURL+"/uploads/"+u.Id, mpData) require.NoError(t, err) req.Header.Set("Content-Type", contentType) req.Header.Set(model.HeaderAuth, th.Client.AuthType+" "+th.Client.AuthToken) diff --git a/api4/user.go b/api4/user.go index 188b067603..4b05ad3687 100644 --- a/api4/user.go +++ b/api4/user.go @@ -22,83 +22,83 @@ import ( ) func (api *API) InitUser() { - api.BaseRoutes.Users.Handle("", api.ApiHandler(createUser)).Methods("POST") - api.BaseRoutes.Users.Handle("", api.ApiSessionRequired(getUsers)).Methods("GET") - api.BaseRoutes.Users.Handle("/ids", api.ApiSessionRequired(getUsersByIds)).Methods("POST") - api.BaseRoutes.Users.Handle("/usernames", api.ApiSessionRequired(getUsersByNames)).Methods("POST") - api.BaseRoutes.Users.Handle("/known", api.ApiSessionRequired(getKnownUsers)).Methods("GET") - api.BaseRoutes.Users.Handle("/search", api.ApiSessionRequiredDisableWhenBusy(searchUsers)).Methods("POST") - api.BaseRoutes.Users.Handle("/autocomplete", api.ApiSessionRequired(autocompleteUsers)).Methods("GET") - api.BaseRoutes.Users.Handle("/stats", api.ApiSessionRequired(getTotalUsersStats)).Methods("GET") - api.BaseRoutes.Users.Handle("/stats/filtered", api.ApiSessionRequired(getFilteredUsersStats)).Methods("GET") - api.BaseRoutes.Users.Handle("/group_channels", api.ApiSessionRequired(getUsersByGroupChannelIds)).Methods("POST") + api.BaseRoutes.Users.Handle("", api.APIHandler(createUser)).Methods("POST") + api.BaseRoutes.Users.Handle("", api.APISessionRequired(getUsers)).Methods("GET") + api.BaseRoutes.Users.Handle("/ids", api.APISessionRequired(getUsersByIds)).Methods("POST") + api.BaseRoutes.Users.Handle("/usernames", api.APISessionRequired(getUsersByNames)).Methods("POST") + api.BaseRoutes.Users.Handle("/known", api.APISessionRequired(getKnownUsers)).Methods("GET") + api.BaseRoutes.Users.Handle("/search", api.APISessionRequiredDisableWhenBusy(searchUsers)).Methods("POST") + api.BaseRoutes.Users.Handle("/autocomplete", api.APISessionRequired(autocompleteUsers)).Methods("GET") + api.BaseRoutes.Users.Handle("/stats", api.APISessionRequired(getTotalUsersStats)).Methods("GET") + api.BaseRoutes.Users.Handle("/stats/filtered", api.APISessionRequired(getFilteredUsersStats)).Methods("GET") + api.BaseRoutes.Users.Handle("/group_channels", api.APISessionRequired(getUsersByGroupChannelIds)).Methods("POST") - api.BaseRoutes.User.Handle("", api.ApiSessionRequired(getUser)).Methods("GET") - api.BaseRoutes.User.Handle("/image/default", api.ApiSessionRequiredTrustRequester(getDefaultProfileImage)).Methods("GET") - api.BaseRoutes.User.Handle("/image", api.ApiSessionRequiredTrustRequester(getProfileImage)).Methods("GET") - api.BaseRoutes.User.Handle("/image", api.ApiSessionRequired(setProfileImage)).Methods("POST") - api.BaseRoutes.User.Handle("/image", api.ApiSessionRequired(setDefaultProfileImage)).Methods("DELETE") - api.BaseRoutes.User.Handle("", api.ApiSessionRequired(updateUser)).Methods("PUT") - api.BaseRoutes.User.Handle("/patch", api.ApiSessionRequired(patchUser)).Methods("PUT") - api.BaseRoutes.User.Handle("", api.ApiSessionRequired(deleteUser)).Methods("DELETE") - api.BaseRoutes.User.Handle("/roles", api.ApiSessionRequired(updateUserRoles)).Methods("PUT") - api.BaseRoutes.User.Handle("/active", api.ApiSessionRequired(updateUserActive)).Methods("PUT") - api.BaseRoutes.User.Handle("/password", api.ApiSessionRequired(updatePassword)).Methods("PUT") - api.BaseRoutes.User.Handle("/promote", api.ApiSessionRequired(promoteGuestToUser)).Methods("POST") - api.BaseRoutes.User.Handle("/demote", api.ApiSessionRequired(demoteUserToGuest)).Methods("POST") - api.BaseRoutes.User.Handle("/convert_to_bot", api.ApiSessionRequired(convertUserToBot)).Methods("POST") - api.BaseRoutes.Users.Handle("/password/reset", api.ApiHandler(resetPassword)).Methods("POST") - api.BaseRoutes.Users.Handle("/password/reset/send", api.ApiHandler(sendPasswordReset)).Methods("POST") - api.BaseRoutes.Users.Handle("/email/verify", api.ApiHandler(verifyUserEmail)).Methods("POST") - api.BaseRoutes.Users.Handle("/email/verify/send", api.ApiHandler(sendVerificationEmail)).Methods("POST") - api.BaseRoutes.User.Handle("/email/verify/member", api.ApiSessionRequired(verifyUserEmailWithoutToken)).Methods("POST") - api.BaseRoutes.User.Handle("/terms_of_service", api.ApiSessionRequired(saveUserTermsOfService)).Methods("POST") - api.BaseRoutes.User.Handle("/terms_of_service", api.ApiSessionRequired(getUserTermsOfService)).Methods("GET") + api.BaseRoutes.User.Handle("", api.APISessionRequired(getUser)).Methods("GET") + api.BaseRoutes.User.Handle("/image/default", api.APISessionRequiredTrustRequester(getDefaultProfileImage)).Methods("GET") + api.BaseRoutes.User.Handle("/image", api.APISessionRequiredTrustRequester(getProfileImage)).Methods("GET") + api.BaseRoutes.User.Handle("/image", api.APISessionRequired(setProfileImage)).Methods("POST") + api.BaseRoutes.User.Handle("/image", api.APISessionRequired(setDefaultProfileImage)).Methods("DELETE") + api.BaseRoutes.User.Handle("", api.APISessionRequired(updateUser)).Methods("PUT") + api.BaseRoutes.User.Handle("/patch", api.APISessionRequired(patchUser)).Methods("PUT") + api.BaseRoutes.User.Handle("", api.APISessionRequired(deleteUser)).Methods("DELETE") + api.BaseRoutes.User.Handle("/roles", api.APISessionRequired(updateUserRoles)).Methods("PUT") + api.BaseRoutes.User.Handle("/active", api.APISessionRequired(updateUserActive)).Methods("PUT") + api.BaseRoutes.User.Handle("/password", api.APISessionRequired(updatePassword)).Methods("PUT") + api.BaseRoutes.User.Handle("/promote", api.APISessionRequired(promoteGuestToUser)).Methods("POST") + api.BaseRoutes.User.Handle("/demote", api.APISessionRequired(demoteUserToGuest)).Methods("POST") + api.BaseRoutes.User.Handle("/convert_to_bot", api.APISessionRequired(convertUserToBot)).Methods("POST") + api.BaseRoutes.Users.Handle("/password/reset", api.APIHandler(resetPassword)).Methods("POST") + api.BaseRoutes.Users.Handle("/password/reset/send", api.APIHandler(sendPasswordReset)).Methods("POST") + api.BaseRoutes.Users.Handle("/email/verify", api.APIHandler(verifyUserEmail)).Methods("POST") + api.BaseRoutes.Users.Handle("/email/verify/send", api.APIHandler(sendVerificationEmail)).Methods("POST") + api.BaseRoutes.User.Handle("/email/verify/member", api.APISessionRequired(verifyUserEmailWithoutToken)).Methods("POST") + api.BaseRoutes.User.Handle("/terms_of_service", api.APISessionRequired(saveUserTermsOfService)).Methods("POST") + api.BaseRoutes.User.Handle("/terms_of_service", api.APISessionRequired(getUserTermsOfService)).Methods("GET") - api.BaseRoutes.User.Handle("/auth", api.ApiSessionRequiredTrustRequester(updateUserAuth)).Methods("PUT") + api.BaseRoutes.User.Handle("/auth", api.APISessionRequiredTrustRequester(updateUserAuth)).Methods("PUT") - api.BaseRoutes.Users.Handle("/mfa", api.ApiHandler(checkUserMfa)).Methods("POST") - api.BaseRoutes.User.Handle("/mfa", api.ApiSessionRequiredMfa(updateUserMfa)).Methods("PUT") - api.BaseRoutes.User.Handle("/mfa/generate", api.ApiSessionRequiredMfa(generateMfaSecret)).Methods("POST") + api.BaseRoutes.Users.Handle("/mfa", api.APIHandler(checkUserMfa)).Methods("POST") + api.BaseRoutes.User.Handle("/mfa", api.APISessionRequiredMfa(updateUserMfa)).Methods("PUT") + api.BaseRoutes.User.Handle("/mfa/generate", api.APISessionRequiredMfa(generateMfaSecret)).Methods("POST") - api.BaseRoutes.Users.Handle("/login", api.ApiHandler(login)).Methods("POST") - api.BaseRoutes.Users.Handle("/login/switch", api.ApiHandler(switchAccountType)).Methods("POST") - api.BaseRoutes.Users.Handle("/login/cws", api.ApiHandlerTrustRequester(loginCWS)).Methods("POST") - api.BaseRoutes.Users.Handle("/logout", api.ApiHandler(logout)).Methods("POST") + api.BaseRoutes.Users.Handle("/login", api.APIHandler(login)).Methods("POST") + api.BaseRoutes.Users.Handle("/login/switch", api.APIHandler(switchAccountType)).Methods("POST") + api.BaseRoutes.Users.Handle("/login/cws", api.APIHandlerTrustRequester(loginCWS)).Methods("POST") + api.BaseRoutes.Users.Handle("/logout", api.APIHandler(logout)).Methods("POST") - api.BaseRoutes.UserByUsername.Handle("", api.ApiSessionRequired(getUserByUsername)).Methods("GET") - api.BaseRoutes.UserByEmail.Handle("", api.ApiSessionRequired(getUserByEmail)).Methods("GET") + api.BaseRoutes.UserByUsername.Handle("", api.APISessionRequired(getUserByUsername)).Methods("GET") + api.BaseRoutes.UserByEmail.Handle("", api.APISessionRequired(getUserByEmail)).Methods("GET") - api.BaseRoutes.User.Handle("/sessions", api.ApiSessionRequired(getSessions)).Methods("GET") - api.BaseRoutes.User.Handle("/sessions/revoke", api.ApiSessionRequired(revokeSession)).Methods("POST") - api.BaseRoutes.User.Handle("/sessions/revoke/all", api.ApiSessionRequired(revokeAllSessionsForUser)).Methods("POST") - api.BaseRoutes.Users.Handle("/sessions/revoke/all", api.ApiSessionRequired(revokeAllSessionsAllUsers)).Methods("POST") - api.BaseRoutes.Users.Handle("/sessions/device", api.ApiSessionRequired(attachDeviceId)).Methods("PUT") - api.BaseRoutes.User.Handle("/audits", api.ApiSessionRequired(getUserAudits)).Methods("GET") + api.BaseRoutes.User.Handle("/sessions", api.APISessionRequired(getSessions)).Methods("GET") + api.BaseRoutes.User.Handle("/sessions/revoke", api.APISessionRequired(revokeSession)).Methods("POST") + api.BaseRoutes.User.Handle("/sessions/revoke/all", api.APISessionRequired(revokeAllSessionsForUser)).Methods("POST") + api.BaseRoutes.Users.Handle("/sessions/revoke/all", api.APISessionRequired(revokeAllSessionsAllUsers)).Methods("POST") + api.BaseRoutes.Users.Handle("/sessions/device", api.APISessionRequired(attachDeviceId)).Methods("PUT") + api.BaseRoutes.User.Handle("/audits", api.APISessionRequired(getUserAudits)).Methods("GET") - api.BaseRoutes.User.Handle("/tokens", api.ApiSessionRequired(createUserAccessToken)).Methods("POST") - api.BaseRoutes.User.Handle("/tokens", api.ApiSessionRequired(getUserAccessTokensForUser)).Methods("GET") - api.BaseRoutes.Users.Handle("/tokens", api.ApiSessionRequired(getUserAccessTokens)).Methods("GET") - api.BaseRoutes.Users.Handle("/tokens/search", api.ApiSessionRequired(searchUserAccessTokens)).Methods("POST") - api.BaseRoutes.Users.Handle("/tokens/{token_id:[A-Za-z0-9]+}", api.ApiSessionRequired(getUserAccessToken)).Methods("GET") - api.BaseRoutes.Users.Handle("/tokens/revoke", api.ApiSessionRequired(revokeUserAccessToken)).Methods("POST") - api.BaseRoutes.Users.Handle("/tokens/disable", api.ApiSessionRequired(disableUserAccessToken)).Methods("POST") - api.BaseRoutes.Users.Handle("/tokens/enable", api.ApiSessionRequired(enableUserAccessToken)).Methods("POST") + api.BaseRoutes.User.Handle("/tokens", api.APISessionRequired(createUserAccessToken)).Methods("POST") + api.BaseRoutes.User.Handle("/tokens", api.APISessionRequired(getUserAccessTokensForUser)).Methods("GET") + api.BaseRoutes.Users.Handle("/tokens", api.APISessionRequired(getUserAccessTokens)).Methods("GET") + api.BaseRoutes.Users.Handle("/tokens/search", api.APISessionRequired(searchUserAccessTokens)).Methods("POST") + api.BaseRoutes.Users.Handle("/tokens/{token_id:[A-Za-z0-9]+}", api.APISessionRequired(getUserAccessToken)).Methods("GET") + api.BaseRoutes.Users.Handle("/tokens/revoke", api.APISessionRequired(revokeUserAccessToken)).Methods("POST") + api.BaseRoutes.Users.Handle("/tokens/disable", api.APISessionRequired(disableUserAccessToken)).Methods("POST") + api.BaseRoutes.Users.Handle("/tokens/enable", api.APISessionRequired(enableUserAccessToken)).Methods("POST") - api.BaseRoutes.User.Handle("/typing", api.ApiSessionRequiredDisableWhenBusy(publishUserTyping)).Methods("POST") + api.BaseRoutes.User.Handle("/typing", api.APISessionRequiredDisableWhenBusy(publishUserTyping)).Methods("POST") - api.BaseRoutes.Users.Handle("/migrate_auth/ldap", api.ApiSessionRequired(migrateAuthToLDAP)).Methods("POST") - api.BaseRoutes.Users.Handle("/migrate_auth/saml", api.ApiSessionRequired(migrateAuthToSaml)).Methods("POST") + api.BaseRoutes.Users.Handle("/migrate_auth/ldap", api.APISessionRequired(migrateAuthToLDAP)).Methods("POST") + api.BaseRoutes.Users.Handle("/migrate_auth/saml", api.APISessionRequired(migrateAuthToSaml)).Methods("POST") - api.BaseRoutes.User.Handle("/uploads", api.ApiSessionRequired(getUploadsForUser)).Methods("GET") + api.BaseRoutes.User.Handle("/uploads", api.APISessionRequired(getUploadsForUser)).Methods("GET") - api.BaseRoutes.UserThreads.Handle("", api.ApiSessionRequired(getThreadsForUser)).Methods("GET") - api.BaseRoutes.UserThreads.Handle("/read", api.ApiSessionRequired(updateReadStateAllThreadsByUser)).Methods("PUT") + api.BaseRoutes.UserThreads.Handle("", api.APISessionRequired(getThreadsForUser)).Methods("GET") + api.BaseRoutes.UserThreads.Handle("/read", api.APISessionRequired(updateReadStateAllThreadsByUser)).Methods("PUT") - api.BaseRoutes.UserThread.Handle("", api.ApiSessionRequired(getThreadForUser)).Methods("GET") - api.BaseRoutes.UserThread.Handle("/following", api.ApiSessionRequired(followThreadByUser)).Methods("PUT") - api.BaseRoutes.UserThread.Handle("/following", api.ApiSessionRequired(unfollowThreadByUser)).Methods("DELETE") - api.BaseRoutes.UserThread.Handle("/read/{timestamp:[0-9]+}", api.ApiSessionRequired(updateReadStateThreadByUser)).Methods("PUT") + api.BaseRoutes.UserThread.Handle("", api.APISessionRequired(getThreadForUser)).Methods("GET") + api.BaseRoutes.UserThread.Handle("/following", api.APISessionRequired(followThreadByUser)).Methods("PUT") + api.BaseRoutes.UserThread.Handle("/following", api.APISessionRequired(unfollowThreadByUser)).Methods("DELETE") + api.BaseRoutes.UserThread.Handle("/read/{timestamp:[0-9]+}", api.APISessionRequired(updateReadStateThreadByUser)).Methods("PUT") } func createUser(c *Context, w http.ResponseWriter, r *http.Request) { @@ -475,7 +475,7 @@ func setProfileImage(c *Context, w http.ResponseWriter, r *http.Request) { user, err := c.App.GetUser(c.Params.UserId) if err != nil { - c.SetInvalidUrlParam("user_id") + c.SetInvalidURLParam("user_id") return } auditRec.AddMeta("user", user) @@ -658,23 +658,23 @@ func getUsers(c *Context, w http.ResponseWriter, r *http.Request) { teamRolesString := r.URL.Query().Get("team_roles") if notInChannelId != "" && inTeamId == "" { - c.SetInvalidUrlParam("team_id") + c.SetInvalidURLParam("team_id") return } if sort != "" && sort != "last_activity_at" && sort != "create_at" && sort != "status" { - c.SetInvalidUrlParam("sort") + c.SetInvalidURLParam("sort") return } // Currently only supports sorting on a team // or sort="status" on inChannelId if (sort == "last_activity_at" || sort == "create_at") && (inTeamId == "" || notInTeamId != "" || inChannelId != "" || notInChannelId != "" || withoutTeam != "" || inGroupId != "") { - c.SetInvalidUrlParam("sort") + c.SetInvalidURLParam("sort") return } if sort == "status" && inChannelId == "" { - c.SetInvalidUrlParam("sort") + c.SetInvalidURLParam("sort") return } @@ -684,7 +684,7 @@ func getUsers(c *Context, w http.ResponseWriter, r *http.Request) { activeBool, _ := strconv.ParseBool(active) if inactiveBool && activeBool { - c.SetInvalidUrlParam("inactive") + c.SetInvalidURLParam("inactive") } roles := []string{} @@ -1984,7 +1984,7 @@ func revokeSession(c *Context, w http.ResponseWriter, r *http.Request) { auditRec.AddMeta("session", session) if session.UserId != c.Params.UserId { - c.SetInvalidUrlParam("user_id") + c.SetInvalidURLParam("user_id") return } diff --git a/api4/user_local.go b/api4/user_local.go index 65e26b6350..38fa2b3668 100644 --- a/api4/user_local.go +++ b/api4/user_local.go @@ -15,35 +15,35 @@ import ( ) func (api *API) InitUserLocal() { - api.BaseRoutes.Users.Handle("", api.ApiLocal(localGetUsers)).Methods("GET") - api.BaseRoutes.Users.Handle("", api.ApiLocal(localPermanentDeleteAllUsers)).Methods("DELETE") - api.BaseRoutes.Users.Handle("", api.ApiLocal(createUser)).Methods("POST") - api.BaseRoutes.Users.Handle("/password/reset/send", api.ApiLocal(sendPasswordReset)).Methods("POST") - api.BaseRoutes.Users.Handle("/ids", api.ApiLocal(localGetUsersByIds)).Methods("POST") + api.BaseRoutes.Users.Handle("", api.APILocal(localGetUsers)).Methods("GET") + api.BaseRoutes.Users.Handle("", api.APILocal(localPermanentDeleteAllUsers)).Methods("DELETE") + api.BaseRoutes.Users.Handle("", api.APILocal(createUser)).Methods("POST") + api.BaseRoutes.Users.Handle("/password/reset/send", api.APILocal(sendPasswordReset)).Methods("POST") + api.BaseRoutes.Users.Handle("/ids", api.APILocal(localGetUsersByIds)).Methods("POST") - api.BaseRoutes.User.Handle("", api.ApiLocal(localGetUser)).Methods("GET") - api.BaseRoutes.User.Handle("", api.ApiLocal(updateUser)).Methods("PUT") - api.BaseRoutes.User.Handle("", api.ApiLocal(localDeleteUser)).Methods("DELETE") - api.BaseRoutes.User.Handle("/roles", api.ApiLocal(updateUserRoles)).Methods("PUT") - api.BaseRoutes.User.Handle("/mfa", api.ApiLocal(updateUserMfa)).Methods("PUT") - api.BaseRoutes.User.Handle("/active", api.ApiLocal(updateUserActive)).Methods("PUT") - api.BaseRoutes.User.Handle("/password", api.ApiLocal(updatePassword)).Methods("PUT") - api.BaseRoutes.User.Handle("/convert_to_bot", api.ApiLocal(convertUserToBot)).Methods("POST") - api.BaseRoutes.User.Handle("/email/verify/member", api.ApiLocal(verifyUserEmailWithoutToken)).Methods("POST") - api.BaseRoutes.User.Handle("/promote", api.ApiLocal(promoteGuestToUser)).Methods("POST") - api.BaseRoutes.User.Handle("/demote", api.ApiLocal(demoteUserToGuest)).Methods("POST") + api.BaseRoutes.User.Handle("", api.APILocal(localGetUser)).Methods("GET") + api.BaseRoutes.User.Handle("", api.APILocal(updateUser)).Methods("PUT") + api.BaseRoutes.User.Handle("", api.APILocal(localDeleteUser)).Methods("DELETE") + api.BaseRoutes.User.Handle("/roles", api.APILocal(updateUserRoles)).Methods("PUT") + api.BaseRoutes.User.Handle("/mfa", api.APILocal(updateUserMfa)).Methods("PUT") + api.BaseRoutes.User.Handle("/active", api.APILocal(updateUserActive)).Methods("PUT") + api.BaseRoutes.User.Handle("/password", api.APILocal(updatePassword)).Methods("PUT") + api.BaseRoutes.User.Handle("/convert_to_bot", api.APILocal(convertUserToBot)).Methods("POST") + api.BaseRoutes.User.Handle("/email/verify/member", api.APILocal(verifyUserEmailWithoutToken)).Methods("POST") + api.BaseRoutes.User.Handle("/promote", api.APILocal(promoteGuestToUser)).Methods("POST") + api.BaseRoutes.User.Handle("/demote", api.APILocal(demoteUserToGuest)).Methods("POST") - api.BaseRoutes.UserByUsername.Handle("", api.ApiLocal(localGetUserByUsername)).Methods("GET") - api.BaseRoutes.UserByEmail.Handle("", api.ApiLocal(localGetUserByEmail)).Methods("GET") + api.BaseRoutes.UserByUsername.Handle("", api.APILocal(localGetUserByUsername)).Methods("GET") + api.BaseRoutes.UserByEmail.Handle("", api.APILocal(localGetUserByEmail)).Methods("GET") - api.BaseRoutes.Users.Handle("/tokens/revoke", api.ApiLocal(revokeUserAccessToken)).Methods("POST") - api.BaseRoutes.User.Handle("/tokens", api.ApiLocal(getUserAccessTokensForUser)).Methods("GET") - api.BaseRoutes.User.Handle("/tokens", api.ApiLocal(createUserAccessToken)).Methods("POST") + api.BaseRoutes.Users.Handle("/tokens/revoke", api.APILocal(revokeUserAccessToken)).Methods("POST") + api.BaseRoutes.User.Handle("/tokens", api.APILocal(getUserAccessTokensForUser)).Methods("GET") + api.BaseRoutes.User.Handle("/tokens", api.APILocal(createUserAccessToken)).Methods("POST") - api.BaseRoutes.Users.Handle("/migrate_auth/ldap", api.ApiLocal(migrateAuthToLDAP)).Methods("POST") - api.BaseRoutes.Users.Handle("/migrate_auth/saml", api.ApiLocal(migrateAuthToSaml)).Methods("POST") + api.BaseRoutes.Users.Handle("/migrate_auth/ldap", api.APILocal(migrateAuthToLDAP)).Methods("POST") + api.BaseRoutes.Users.Handle("/migrate_auth/saml", api.APILocal(migrateAuthToSaml)).Methods("POST") - api.BaseRoutes.User.Handle("/uploads", api.ApiLocal(localGetUploadsForUser)).Methods("GET") + api.BaseRoutes.User.Handle("/uploads", api.APILocal(localGetUploadsForUser)).Methods("GET") } func localGetUsers(c *Context, w http.ResponseWriter, r *http.Request) { @@ -59,23 +59,23 @@ func localGetUsers(c *Context, w http.ResponseWriter, r *http.Request) { sort := r.URL.Query().Get("sort") if notInChannelId != "" && inTeamId == "" { - c.SetInvalidUrlParam("team_id") + c.SetInvalidURLParam("team_id") return } if sort != "" && sort != "last_activity_at" && sort != "create_at" && sort != "status" { - c.SetInvalidUrlParam("sort") + c.SetInvalidURLParam("sort") return } // Currently only supports sorting on a team // or sort="status" on inChannelId if (sort == "last_activity_at" || sort == "create_at") && (inTeamId == "" || notInTeamId != "" || inChannelId != "" || notInChannelId != "" || withoutTeam != "") { - c.SetInvalidUrlParam("sort") + c.SetInvalidURLParam("sort") return } if sort == "status" && inChannelId == "" { - c.SetInvalidUrlParam("sort") + c.SetInvalidURLParam("sort") return } diff --git a/api4/user_test.go b/api4/user_test.go index a85548dbbc..785bb49373 100644 --- a/api4/user_test.go +++ b/api4/user_test.go @@ -89,7 +89,7 @@ func TestCreateUser(t *testing.T) { // Creating a user as sysadmin should verify the user with the EmailVerified flag. require.True(t, ruser2.EmailVerified) - r, err2 := client.DoApiPost("/users", "garbage") + r, err2 := client.DoAPIPost("/users", "garbage") require.Error(t, err2, "should have errored") assert.Equal(t, http.StatusBadRequest, r.StatusCode) }) @@ -885,7 +885,7 @@ func TestSaveUserTermsOfService(t *testing.T) { defer th.TearDown() t.Run("Invalid data", func(t *testing.T) { - resp, err := th.Client.DoApiPost("/users/"+th.BasicUser.Id+"/terms_of_service", "{}") + resp, err := th.Client.DoAPIPost("/users/"+th.BasicUser.Id+"/terms_of_service", "{}") require.Error(t, err) assert.Equal(t, http.StatusBadRequest, resp.StatusCode) }) @@ -1718,7 +1718,7 @@ func TestUpdateUser(t *testing.T) { require.Error(t, err) CheckForbiddenStatus(t, resp) - r, err := th.Client.DoApiPut("/users/"+ruser.Id, "garbage") + r, err := th.Client.DoAPIPut("/users/"+ruser.Id, "garbage") require.Error(t, err) require.Equal(t, http.StatusBadRequest, r.StatusCode) @@ -1832,7 +1832,7 @@ func TestPatchUser(t *testing.T) { require.Error(t, err) CheckForbiddenStatus(t, resp) - r, err := th.Client.DoApiPut("/users/"+user.Id+"/patch", "garbage") + r, err := th.Client.DoAPIPut("/users/"+user.Id+"/patch", "garbage") require.Error(t, err) require.Equal(t, http.StatusBadRequest, r.StatusCode) @@ -2403,7 +2403,7 @@ func TestGetUsers(t *testing.T) { require.Empty(t, rusers, "should be no users") // Check default params for page and per_page - _, err = client.DoApiGet("/users", "") + _, err = client.DoAPIGet("/users", "") require.NoError(t, err) }) @@ -2484,7 +2484,7 @@ func TestGetActiveUsersInTeam(t *testing.T) { require.Len(t, rusers, 1, "should be 1 per page") // Check case where we have supplied both active and inactive flags - _, err = th.Client.DoApiGet("/users?inactive=true&active=true", "") + _, err = th.Client.DoAPIGet("/users?inactive=true&active=true", "") require.Error(t, err) th.Client.Logout() @@ -5010,9 +5010,9 @@ func TestLoginErrorMessage(t *testing.T) { *cfg.SamlSettings.Enable = true *cfg.SamlSettings.Verify = false *cfg.SamlSettings.Encrypt = false - *cfg.SamlSettings.IdpUrl = "https://localhost/adfs/ls" - *cfg.SamlSettings.IdpDescriptorUrl = "https://localhost/adfs/services/trust" - *cfg.SamlSettings.IdpMetadataUrl = "https://localhost/adfs/metadata" + *cfg.SamlSettings.IdpURL = "https://localhost/adfs/ls" + *cfg.SamlSettings.IdpDescriptorURL = "https://localhost/adfs/services/trust" + *cfg.SamlSettings.IdpMetadataURL = "https://localhost/adfs/metadata" *cfg.SamlSettings.ServiceProviderIdentifier = "https://localhost/login/sso/saml" *cfg.SamlSettings.AssertionConsumerServiceURL = "https://localhost/login/sso/saml" *cfg.SamlSettings.IdpCertificateFile = app.SamlIdpCertificateName diff --git a/api4/user_viewmembers_test.go b/api4/user_viewmembers_test.go index f8abae4ced..6217947b9a 100644 --- a/api4/user_viewmembers_test.go +++ b/api4/user_viewmembers_test.go @@ -11,7 +11,7 @@ import ( "github.com/mattermost/mattermost-server/v6/model" ) -func TestApiResctrictedViewMembers(t *testing.T) { +func TestAPIResctrictedViewMembers(t *testing.T) { th := Setup(t) defer th.TearDown() diff --git a/api4/webhook.go b/api4/webhook.go index 9cd2f8282c..355f9ad3ff 100644 --- a/api4/webhook.go +++ b/api4/webhook.go @@ -13,18 +13,18 @@ import ( ) func (api *API) InitWebhook() { - api.BaseRoutes.IncomingHooks.Handle("", api.ApiSessionRequired(createIncomingHook)).Methods("POST") - api.BaseRoutes.IncomingHooks.Handle("", api.ApiSessionRequired(getIncomingHooks)).Methods("GET") - api.BaseRoutes.IncomingHook.Handle("", api.ApiSessionRequired(getIncomingHook)).Methods("GET") - api.BaseRoutes.IncomingHook.Handle("", api.ApiSessionRequired(updateIncomingHook)).Methods("PUT") - api.BaseRoutes.IncomingHook.Handle("", api.ApiSessionRequired(deleteIncomingHook)).Methods("DELETE") + api.BaseRoutes.IncomingHooks.Handle("", api.APISessionRequired(createIncomingHook)).Methods("POST") + api.BaseRoutes.IncomingHooks.Handle("", api.APISessionRequired(getIncomingHooks)).Methods("GET") + api.BaseRoutes.IncomingHook.Handle("", api.APISessionRequired(getIncomingHook)).Methods("GET") + api.BaseRoutes.IncomingHook.Handle("", api.APISessionRequired(updateIncomingHook)).Methods("PUT") + api.BaseRoutes.IncomingHook.Handle("", api.APISessionRequired(deleteIncomingHook)).Methods("DELETE") - api.BaseRoutes.OutgoingHooks.Handle("", api.ApiSessionRequired(createOutgoingHook)).Methods("POST") - api.BaseRoutes.OutgoingHooks.Handle("", api.ApiSessionRequired(getOutgoingHooks)).Methods("GET") - api.BaseRoutes.OutgoingHook.Handle("", api.ApiSessionRequired(getOutgoingHook)).Methods("GET") - api.BaseRoutes.OutgoingHook.Handle("", api.ApiSessionRequired(updateOutgoingHook)).Methods("PUT") - api.BaseRoutes.OutgoingHook.Handle("", api.ApiSessionRequired(deleteOutgoingHook)).Methods("DELETE") - api.BaseRoutes.OutgoingHook.Handle("/regen_token", api.ApiSessionRequired(regenOutgoingHookToken)).Methods("POST") + api.BaseRoutes.OutgoingHooks.Handle("", api.APISessionRequired(createOutgoingHook)).Methods("POST") + api.BaseRoutes.OutgoingHooks.Handle("", api.APISessionRequired(getOutgoingHooks)).Methods("GET") + api.BaseRoutes.OutgoingHook.Handle("", api.APISessionRequired(getOutgoingHook)).Methods("GET") + api.BaseRoutes.OutgoingHook.Handle("", api.APISessionRequired(updateOutgoingHook)).Methods("PUT") + api.BaseRoutes.OutgoingHook.Handle("", api.APISessionRequired(deleteOutgoingHook)).Methods("DELETE") + api.BaseRoutes.OutgoingHook.Handle("/regen_token", api.APISessionRequired(regenOutgoingHookToken)).Methods("POST") } func createIncomingHook(c *Context, w http.ResponseWriter, r *http.Request) { diff --git a/api4/webhook_local.go b/api4/webhook_local.go index b2448ee26f..765af76679 100644 --- a/api4/webhook_local.go +++ b/api4/webhook_local.go @@ -13,17 +13,17 @@ import ( ) func (api *API) InitWebhookLocal() { - api.BaseRoutes.IncomingHooks.Handle("", api.ApiLocal(localCreateIncomingHook)).Methods("POST") - api.BaseRoutes.IncomingHooks.Handle("", api.ApiLocal(getIncomingHooks)).Methods("GET") - api.BaseRoutes.IncomingHook.Handle("", api.ApiLocal(getIncomingHook)).Methods("GET") - api.BaseRoutes.IncomingHook.Handle("", api.ApiLocal(updateIncomingHook)).Methods("PUT") - api.BaseRoutes.IncomingHook.Handle("", api.ApiLocal(deleteIncomingHook)).Methods("DELETE") + api.BaseRoutes.IncomingHooks.Handle("", api.APILocal(localCreateIncomingHook)).Methods("POST") + api.BaseRoutes.IncomingHooks.Handle("", api.APILocal(getIncomingHooks)).Methods("GET") + api.BaseRoutes.IncomingHook.Handle("", api.APILocal(getIncomingHook)).Methods("GET") + api.BaseRoutes.IncomingHook.Handle("", api.APILocal(updateIncomingHook)).Methods("PUT") + api.BaseRoutes.IncomingHook.Handle("", api.APILocal(deleteIncomingHook)).Methods("DELETE") - api.BaseRoutes.OutgoingHooks.Handle("", api.ApiLocal(localCreateOutgoingHook)).Methods("POST") - api.BaseRoutes.OutgoingHooks.Handle("", api.ApiLocal(getOutgoingHooks)).Methods("GET") - api.BaseRoutes.OutgoingHook.Handle("", api.ApiLocal(getOutgoingHook)).Methods("GET") - api.BaseRoutes.OutgoingHook.Handle("", api.ApiLocal(updateOutgoingHook)).Methods("PUT") - api.BaseRoutes.OutgoingHook.Handle("", api.ApiLocal(deleteOutgoingHook)).Methods("DELETE") + api.BaseRoutes.OutgoingHooks.Handle("", api.APILocal(localCreateOutgoingHook)).Methods("POST") + api.BaseRoutes.OutgoingHooks.Handle("", api.APILocal(getOutgoingHooks)).Methods("GET") + api.BaseRoutes.OutgoingHook.Handle("", api.APILocal(getOutgoingHook)).Methods("GET") + api.BaseRoutes.OutgoingHook.Handle("", api.APILocal(updateOutgoingHook)).Methods("PUT") + api.BaseRoutes.OutgoingHook.Handle("", api.APILocal(deleteOutgoingHook)).Methods("DELETE") } func localCreateIncomingHook(c *Context, w http.ResponseWriter, r *http.Request) { diff --git a/api4/websocket.go b/api4/websocket.go index b0f5a5a763..9dff314065 100644 --- a/api4/websocket.go +++ b/api4/websocket.go @@ -20,7 +20,7 @@ const ( func (api *API) InitWebSocket() { // Optionally supports a trailing slash - api.BaseRoutes.ApiRoot.Handle("/{websocket:websocket(?:\\/)?}", api.ApiHandlerTrustRequester(connectWebSocket)).Methods("GET") + api.BaseRoutes.APIRoot.Handle("/{websocket:websocket(?:\\/)?}", api.APIHandlerTrustRequester(connectWebSocket)).Methods("GET") } func connectWebSocket(c *Context, w http.ResponseWriter, r *http.Request) { diff --git a/api4/websocket_test.go b/api4/websocket_test.go index cb2d5860df..19b3ac7fd1 100644 --- a/api4/websocket_test.go +++ b/api4/websocket_test.go @@ -21,7 +21,7 @@ func TestWebSocketTrailingSlash(t *testing.T) { defer th.TearDown() url := fmt.Sprintf("ws://localhost:%v", th.App.Srv().ListenAddr.Port) - _, _, err := websocket.DefaultDialer.Dial(url+model.ApiUrlSuffix+"/websocket/", nil) + _, _, err := websocket.DefaultDialer.Dial(url+model.APIURLSuffix+"/websocket/", nil) require.NoError(t, err) } @@ -156,42 +156,42 @@ func TestWebsocketOriginSecurity(t *testing.T) { url := fmt.Sprintf("ws://localhost:%v", th.App.Srv().ListenAddr.Port) // Should fail because origin doesn't match - _, _, err := websocket.DefaultDialer.Dial(url+model.ApiUrlSuffix+"/websocket", http.Header{ + _, _, err := websocket.DefaultDialer.Dial(url+model.APIURLSuffix+"/websocket", http.Header{ "Origin": []string{"http://www.evil.com"}, }) require.Error(t, err, "Should have errored because Origin does not match host! SECURITY ISSUE!") // We are not a browser so we can spoof this just fine - _, _, err = websocket.DefaultDialer.Dial(url+model.ApiUrlSuffix+"/websocket", http.Header{ + _, _, err = websocket.DefaultDialer.Dial(url+model.APIURLSuffix+"/websocket", http.Header{ "Origin": []string{fmt.Sprintf("http://localhost:%v", th.App.Srv().ListenAddr.Port)}, }) require.NoError(t, err, err) // Should succeed now because open CORS th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.AllowCorsFrom = "*" }) - _, _, err = websocket.DefaultDialer.Dial(url+model.ApiUrlSuffix+"/websocket", http.Header{ + _, _, err = websocket.DefaultDialer.Dial(url+model.APIURLSuffix+"/websocket", http.Header{ "Origin": []string{"http://www.evil.com"}, }) require.NoError(t, err, err) // Should succeed now because matching CORS th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.AllowCorsFrom = "http://www.evil.com" }) - _, _, err = websocket.DefaultDialer.Dial(url+model.ApiUrlSuffix+"/websocket", http.Header{ + _, _, err = websocket.DefaultDialer.Dial(url+model.APIURLSuffix+"/websocket", http.Header{ "Origin": []string{"http://www.evil.com"}, }) require.NoError(t, err, err) // Should fail because non-matching CORS th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.AllowCorsFrom = "http://www.good.com" }) - _, _, err = websocket.DefaultDialer.Dial(url+model.ApiUrlSuffix+"/websocket", http.Header{ + _, _, err = websocket.DefaultDialer.Dial(url+model.APIURLSuffix+"/websocket", http.Header{ "Origin": []string{"http://www.evil.com"}, }) require.Error(t, err, "Should have errored because Origin contain AllowCorsFrom") // Should fail because non-matching CORS th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.AllowCorsFrom = "http://www.good.com" }) - _, _, err = websocket.DefaultDialer.Dial(url+model.ApiUrlSuffix+"/websocket", http.Header{ + _, _, err = websocket.DefaultDialer.Dial(url+model.APIURLSuffix+"/websocket", http.Header{ "Origin": []string{"http://www.good.co"}, }) require.Error(t, err, "Should have errored because Origin does not match host! SECURITY ISSUE!") diff --git a/app/app.go b/app/app.go index 2b33fa10cc..f1fb5d9929 100644 --- a/app/app.go +++ b/app/app.go @@ -288,13 +288,13 @@ func (a *App) notifyAdminsOfWarnMetricStatus(c *request.Context, warnMetricId st actionId := "contactUs" actionName := T("api.server.warn_metric.contact_us") postActionValue := T("api.server.warn_metric.contacting_us") - postActionUrl := fmt.Sprintf("/warn_metrics/ack/%s", warnMetricId) + postActionURL := fmt.Sprintf("/warn_metrics/ack/%s", warnMetricId) if isE0Edition { actionId = "startTrial" actionName = T("api.server.warn_metric.start_trial") postActionValue = T("api.server.warn_metric.starting_trial") - postActionUrl = fmt.Sprintf("/warn_metrics/trial-license-ack/%s", warnMetricId) + postActionURL = fmt.Sprintf("/warn_metrics/trial-license-ack/%s", warnMetricId) } actions := []*model.PostAction{} @@ -318,7 +318,7 @@ func (a *App) notifyAdminsOfWarnMetricStatus(c *request.Context, warnMetricId st "bot_user_id": warnMetricsBot.UserId, "force_ack": false, }, - URL: postActionUrl, + URL: postActionURL, }, }, ) diff --git a/app/app_iface.go b/app/app_iface.go index b3826358c3..6990ba11de 100644 --- a/app/app_iface.go +++ b/app/app_iface.go @@ -162,9 +162,9 @@ type AppIface interface { GetClusterPluginStatuses() (model.PluginStatuses, *model.AppError) // GetConfigFile proxies access to the given configuration file to the underlying config store. GetConfigFile(name string) ([]byte, error) - // GetEmojiStaticUrl returns a relative static URL for system default emojis, + // GetEmojiStaticURL returns a relative static URL for system default emojis, // and the API route for custom ones. Errors if not found or if custom and deleted. - GetEmojiStaticUrl(emojiName string) (string, *model.AppError) + GetEmojiStaticURL(emojiName string) (string, *model.AppError) // GetEnvironmentConfig returns a map of configuration keys whose values have been overridden by an environment variable. // If filter is not nil and returns false for a struct field, that field will be omitted. GetEnvironmentConfig(filter func(reflect.StructField) bool) map[string]interface{} @@ -409,7 +409,7 @@ type AppIface interface { AttachDeviceId(sessionID string, deviceID string, expiresAt int64) *model.AppError AttachSessionCookies(c *request.Context, w http.ResponseWriter, r *http.Request) AuthenticateUserForLogin(c *request.Context, id, loginId, password, mfaToken, cwsToken string, ldapOnly bool) (user *model.User, err *model.AppError) - AuthorizeOAuthUser(w http.ResponseWriter, r *http.Request, service, code, state, redirectUri string) (io.ReadCloser, string, map[string]string, *model.User, *model.AppError) + AuthorizeOAuthUser(w http.ResponseWriter, r *http.Request, service, code, state, redirectURI string) (io.ReadCloser, string, map[string]string, *model.User, *model.AppError) AutocompleteChannels(teamID string, term string) (*model.ChannelList, *model.AppError) AutocompleteChannelsForSearch(teamID string, userID string, term string) (*model.ChannelList, *model.AppError) AutocompleteUsersInChannel(teamID string, channelID string, term string, options *model.UserSearchOptions) (*model.UserAutocompleteInChannel, *model.AppError) @@ -650,7 +650,7 @@ type AppIface interface { GetNextPostIdFromPostList(postList *model.PostList, collapsedThreads bool) string GetNotificationNameFormat(user *model.User) string GetNumberOfChannelsOnTeam(teamID string) (int, *model.AppError) - GetOAuthAccessTokenForCodeFlow(clientId, grantType, redirectUri, code, secret, refreshToken string) (*model.AccessResponse, *model.AppError) + GetOAuthAccessTokenForCodeFlow(clientId, grantType, redirectURI, code, secret, refreshToken string) (*model.AccessResponse, *model.AppError) GetOAuthAccessTokenForImplicitFlow(userID string, authRequest *model.AuthorizeRequest) (*model.Session, *model.AppError) GetOAuthApp(appID string) (*model.OAuthApp, *model.AppError) GetOAuthApps(page, perPage int) ([]*model.OAuthApp, *model.AppError) @@ -709,7 +709,7 @@ type AppIface interface { GetRolesByNames(names []string) ([]*model.Role, *model.AppError) GetSamlCertificateStatus() *model.SamlCertificateStatus GetSamlMetadata() (string, *model.AppError) - GetSamlMetadataFromIdp(idpMetadataUrl string) (*model.SamlMetadataResponse, *model.AppError) + GetSamlMetadataFromIdp(idpMetadataURL string) (*model.SamlMetadataResponse, *model.AppError) GetSanitizeOptions(asAdmin bool) map[string]bool GetScheme(id string) (*model.Scheme, *model.AppError) GetSchemeByName(name string) (*model.Scheme, *model.AppError) diff --git a/app/download.go b/app/download.go index a0ed03df5b..e1a8ae0e58 100644 --- a/app/download.go +++ b/app/download.go @@ -27,7 +27,7 @@ func (a *App) DownloadFromURL(downloadURL string) ([]byte, error) { } func (s *Server) downloadFromURL(downloadURL string) ([]byte, error) { - if !model.IsValidHTTPUrl(downloadURL) { + if !model.IsValidHTTPURL(downloadURL) { return nil, errors.Errorf("invalid url %s", downloadURL) } @@ -35,7 +35,7 @@ func (s *Server) downloadFromURL(downloadURL string) ([]byte, error) { if err != nil { return nil, errors.Errorf("failed to parse url %s", downloadURL) } - if !*s.Config().PluginSettings.AllowInsecureDownloadUrl && u.Scheme != "https" { + if !*s.Config().PluginSettings.AllowInsecureDownloadURL && u.Scheme != "https" { return nil, errors.Errorf("insecure url not allowed %s", downloadURL) } diff --git a/app/download_test.go b/app/download_test.go index 1f34fc16ac..7830647d27 100644 --- a/app/download_test.go +++ b/app/download_test.go @@ -19,7 +19,7 @@ func TestDownloadFromURL(t *testing.T) { defer th.TearDown() app := th.App - app.Config().PluginSettings.AllowInsecureDownloadUrl = model.NewBool(true) + app.Config().PluginSettings.AllowInsecureDownloadURL = model.NewBool(true) // To keep track of how many times an endpoint is retried. This needs to be reset // for each test run. diff --git a/app/emoji.go b/app/emoji.go index 2affcaa457..80c67a073e 100644 --- a/app/emoji.go +++ b/app/emoji.go @@ -274,9 +274,9 @@ func (a *App) SearchEmoji(name string, prefixOnly bool, limit int) ([]*model.Emo return list, nil } -// GetEmojiStaticUrl returns a relative static URL for system default emojis, +// GetEmojiStaticURL returns a relative static URL for system default emojis, // and the API route for custom ones. Errors if not found or if custom and deleted. -func (a *App) GetEmojiStaticUrl(emojiName string) (string, *model.AppError) { +func (a *App) GetEmojiStaticURL(emojiName string) (string, *model.AppError) { subPath, _ := utils.GetSubpathFromConfig(a.Config()) if id, found := model.GetSystemEmojiId(emojiName); found { @@ -290,9 +290,9 @@ func (a *App) GetEmojiStaticUrl(emojiName string) (string, *model.AppError) { var nfErr *store.ErrNotFound switch { case errors.As(err, &nfErr): - return "", model.NewAppError("GetEmojiStaticUrl", "app.emoji.get_by_name.no_result", nil, err.Error(), http.StatusNotFound) + return "", model.NewAppError("GetEmojiStaticURL", "app.emoji.get_by_name.no_result", nil, err.Error(), http.StatusNotFound) default: - return "", model.NewAppError("GetEmojiStaticUrl", "app.emoji.get_by_name.app_error", nil, err.Error(), http.StatusInternalServerError) + return "", model.NewAppError("GetEmojiStaticURL", "app.emoji.get_by_name.app_error", nil, err.Error(), http.StatusInternalServerError) } } diff --git a/app/integration_action_test.go b/app/integration_action_test.go index b41830ba3c..8cb29061ff 100644 --- a/app/integration_action_test.go +++ b/app/integration_action_test.go @@ -530,7 +530,7 @@ func TestSubmitInteractiveDialog(t *testing.T) { })) defer ts.Close() - setupPluginApiTest(t, + setupPluginAPITest(t, ` package main @@ -818,7 +818,7 @@ func TestPostActionRelativePluginURL(t *testing.T) { th := Setup(t).InitBasic() defer th.TearDown() - setupPluginApiTest(t, + setupPluginAPITest(t, ` package main @@ -1016,7 +1016,7 @@ func TestDoPluginRequest(t *testing.T) { *cfg.ServiceSettings.AllowedUntrustedInternalConnections = "localhost,127.0.0.1" }) - setupPluginApiTest(t, + setupPluginAPITest(t, ` package main diff --git a/app/notification_push.go b/app/notification_push.go index 9367e9e93e..e394cfd71f 100644 --- a/app/notification_push.go +++ b/app/notification_push.go @@ -363,7 +363,7 @@ func (a *App) sendToPushProxy(msg *model.PushNotification, session *model.Sessio mlog.String("status", model.PushSendPrepare), ) - url := strings.TrimRight(*a.Config().EmailSettings.PushNotificationServer, "/") + model.ApiUrlSuffixV1 + "/send_push" + url := strings.TrimRight(*a.Config().EmailSettings.PushNotificationServer, "/") + model.APIURLSuffixV1 + "/send_push" request, err := http.NewRequest("POST", url, strings.NewReader(msg.ToJson())) if err != nil { return err @@ -403,7 +403,7 @@ func (a *App) SendAckToPushProxy(ack *model.PushNotificationAck) error { request, err := http.NewRequest( "POST", - strings.TrimRight(*a.Config().EmailSettings.PushNotificationServer, "/")+model.ApiUrlSuffixV1+"/ack", + strings.TrimRight(*a.Config().EmailSettings.PushNotificationServer, "/")+model.APIURLSuffixV1+"/ack", strings.NewReader(ack.ToJson()), ) @@ -571,7 +571,7 @@ func (a *App) buildFullPushNotificationMessage(contentsConfig string, post *mode } if oi, ok := post.GetProp("override_icon_url").(string); ok && *cfg.ServiceSettings.EnablePostIconOverride { - msg.OverrideIconUrl = oi + msg.OverrideIconURL = oi } if fw, ok := post.GetProp("from_webhook").(string); ok { diff --git a/app/oauth.go b/app/oauth.go index 3a7f05fba6..83c1da2f79 100644 --- a/app/oauth.go +++ b/app/oauth.go @@ -159,18 +159,18 @@ func (a *App) GetOAuthImplicitRedirect(userID string, authRequest *model.Authori values.Add("scope", authRequest.Scope) values.Add("state", authRequest.State) - return fmt.Sprintf("%s#%s", authRequest.RedirectUri, values.Encode()), nil + return fmt.Sprintf("%s#%s", authRequest.RedirectURI, values.Encode()), nil } func (a *App) GetOAuthCodeRedirect(userID string, authRequest *model.AuthorizeRequest) (string, *model.AppError) { - authData := &model.AuthData{UserId: userID, ClientId: authRequest.ClientId, CreateAt: model.GetMillis(), RedirectUri: authRequest.RedirectUri, State: authRequest.State, Scope: authRequest.Scope} + authData := &model.AuthData{UserId: userID, ClientId: authRequest.ClientId, CreateAt: model.GetMillis(), RedirectUri: authRequest.RedirectURI, State: authRequest.State, Scope: authRequest.Scope} authData.Code = model.NewId() + model.NewId() if _, err := a.Srv().Store.OAuth().SaveAuthData(authData); err != nil { - return authRequest.RedirectUri + "?error=server_error&state=" + authRequest.State, nil + return authRequest.RedirectURI + "?error=server_error&state=" + authRequest.State, nil } - return authRequest.RedirectUri + "?code=" + url.QueryEscape(authData.Code) + "&state=" + url.QueryEscape(authData.State), nil + return authRequest.RedirectURI + "?code=" + url.QueryEscape(authData.Code) + "&state=" + url.QueryEscape(authData.State), nil } func (a *App) AllowOAuthAppAccessToUser(userID string, authRequest *model.AuthorizeRequest) (string, *model.AppError) { @@ -193,7 +193,7 @@ func (a *App) AllowOAuthAppAccessToUser(userID string, authRequest *model.Author } } - if !oauthApp.IsValidRedirectURL(authRequest.RedirectUri) { + if !oauthApp.IsValidRedirectURL(authRequest.RedirectURI) { return "", model.NewAppError("AllowOAuthAppAccessToUser", "api.oauth.allow_oauth.redirect_callback.app_error", nil, "", http.StatusBadRequest) } @@ -205,12 +205,12 @@ func (a *App) AllowOAuthAppAccessToUser(userID string, authRequest *model.Author case model.ImplicitResponseType: redirectURI, err = a.GetOAuthImplicitRedirect(userID, authRequest) default: - return authRequest.RedirectUri + "?error=unsupported_response_type&state=" + authRequest.State, nil + return authRequest.RedirectURI + "?error=unsupported_response_type&state=" + authRequest.State, nil } if err != nil { mlog.Warn("error getting oauth redirect uri", mlog.Err(err)) - return authRequest.RedirectUri + "?error=server_error&state=" + authRequest.State, nil + return authRequest.RedirectURI + "?error=server_error&state=" + authRequest.State, nil } // This saves the OAuth2 app as authorized @@ -223,7 +223,7 @@ func (a *App) AllowOAuthAppAccessToUser(userID string, authRequest *model.Author if nErr := a.Srv().Store.Preference().Save(&model.Preferences{authorizedApp}); nErr != nil { mlog.Warn("error saving store preference", mlog.Err(nErr)) - return authRequest.RedirectUri + "?error=server_error&state=" + authRequest.State, nil + return authRequest.RedirectURI + "?error=server_error&state=" + authRequest.State, nil } return redirectURI, nil @@ -249,7 +249,7 @@ func (a *App) GetOAuthAccessTokenForImplicitFlow(userID string, authRequest *mod return nil, err } - accessData := &model.AccessData{ClientId: authRequest.ClientId, UserId: user.Id, Token: session.Token, RefreshToken: "", RedirectUri: authRequest.RedirectUri, ExpiresAt: session.ExpiresAt, Scope: authRequest.Scope} + accessData := &model.AccessData{ClientId: authRequest.ClientId, UserId: user.Id, Token: session.Token, RefreshToken: "", RedirectUri: authRequest.RedirectURI, ExpiresAt: session.ExpiresAt, Scope: authRequest.Scope} if _, err := a.Srv().Store.OAuth().SaveAccessData(accessData); err != nil { return nil, model.NewAppError("GetOAuthAccessToken", "api.oauth.get_access_token.internal_saving.app_error", nil, "", http.StatusInternalServerError) @@ -258,7 +258,7 @@ func (a *App) GetOAuthAccessTokenForImplicitFlow(userID string, authRequest *mod return session, nil } -func (a *App) GetOAuthAccessTokenForCodeFlow(clientId, grantType, redirectUri, code, secret, refreshToken string) (*model.AccessResponse, *model.AppError) { +func (a *App) GetOAuthAccessTokenForCodeFlow(clientId, grantType, redirectURI, code, secret, refreshToken string) (*model.AccessResponse, *model.AppError) { if !*a.Config().ServiceSettings.EnableOAuthServiceProvider { return nil, model.NewAppError("GetOAuthAccessToken", "api.oauth.get_access_token.disabled.app_error", nil, "", http.StatusNotImplemented) } @@ -289,7 +289,7 @@ func (a *App) GetOAuthAccessTokenForCodeFlow(clientId, grantType, redirectUri, c return nil, model.NewAppError("GetOAuthAccessToken", "api.oauth.get_access_token.expired_code.app_error", nil, "", http.StatusForbidden) } - if authData.RedirectUri != redirectUri { + if authData.RedirectUri != redirectURI { return nil, model.NewAppError("GetOAuthAccessToken", "api.oauth.get_access_token.redirect_uri.app_error", nil, "", http.StatusBadRequest) } @@ -328,7 +328,7 @@ func (a *App) GetOAuthAccessTokenForCodeFlow(clientId, grantType, redirectUri, c return nil, err } - accessData = &model.AccessData{ClientId: clientId, UserId: user.Id, Token: session.Token, RefreshToken: model.NewId(), RedirectUri: redirectUri, ExpiresAt: session.ExpiresAt, Scope: authData.Scope} + accessData = &model.AccessData{ClientId: clientId, UserId: user.Id, Token: session.Token, RefreshToken: model.NewId(), RedirectUri: redirectURI, ExpiresAt: session.ExpiresAt, Scope: authData.Scope} if _, nErr = a.Srv().Store.OAuth().SaveAccessData(accessData); nErr != nil { return nil, model.NewAppError("GetOAuthAccessToken", "api.oauth.get_access_token.internal_saving.app_error", nil, "", http.StatusInternalServerError) @@ -427,12 +427,12 @@ func (a *App) GetOAuthLoginEndpoint(w http.ResponseWriter, r *http.Request, serv stateProps[model.UserAuthServiceIsMobile] = strconv.FormatBool(isMobile) - authUrl, err := a.GetAuthorizationCode(w, r, service, stateProps, loginHint) + authURL, err := a.GetAuthorizationCode(w, r, service, stateProps, loginHint) if err != nil { return "", err } - return authUrl, nil + return authURL, nil } func (a *App) GetOAuthSignupEndpoint(w http.ResponseWriter, r *http.Request, service, teamID string) (string, *model.AppError) { @@ -442,12 +442,12 @@ func (a *App) GetOAuthSignupEndpoint(w http.ResponseWriter, r *http.Request, ser stateProps["team_id"] = teamID } - authUrl, err := a.GetAuthorizationCode(w, r, service, stateProps, "") + authURL, err := a.GetAuthorizationCode(w, r, service, stateProps, "") if err != nil { return "", err } - return authUrl, nil + return authURL, nil } func (a *App) GetAuthorizedAppsForUser(userID string, page, perPage int) ([]*model.OAuthApp, *model.AppError) { @@ -746,27 +746,27 @@ func (a *App) GetAuthorizationCode(w http.ResponseWriter, r *http.Request, servi props["token"] = stateToken.Token state := b64.StdEncoding.EncodeToString([]byte(model.MapToJson(props))) - siteUrl := a.GetSiteURL() - if strings.TrimSpace(siteUrl) == "" { - siteUrl = GetProtocol(r) + "://" + r.Host + siteURL := a.GetSiteURL() + if strings.TrimSpace(siteURL) == "" { + siteURL = GetProtocol(r) + "://" + r.Host } - redirectUri := siteUrl + "/signup/" + service + "/complete" + redirectURI := siteURL + "/signup/" + service + "/complete" - authUrl := endpoint + "?response_type=code&client_id=" + clientId + "&redirect_uri=" + url.QueryEscape(redirectUri) + "&state=" + url.QueryEscape(state) + authURL := endpoint + "?response_type=code&client_id=" + clientId + "&redirect_uri=" + url.QueryEscape(redirectURI) + "&state=" + url.QueryEscape(state) if scope != "" { - authUrl += "&scope=" + utils.URLEncode(scope) + authURL += "&scope=" + utils.URLEncode(scope) } if loginHint != "" { - authUrl += "&login_hint=" + utils.URLEncode(loginHint) + authURL += "&login_hint=" + utils.URLEncode(loginHint) } - return authUrl, nil + return authURL, nil } -func (a *App) AuthorizeOAuthUser(w http.ResponseWriter, r *http.Request, service, code, state, redirectUri string) (io.ReadCloser, string, map[string]string, *model.User, *model.AppError) { +func (a *App) AuthorizeOAuthUser(w http.ResponseWriter, r *http.Request, service, code, state, redirectURI string) (io.ReadCloser, string, map[string]string, *model.User, *model.AppError) { provider, e := a.getSSOProvider(service) if e != nil { return nil, "", nil, nil, e @@ -830,7 +830,7 @@ func (a *App) AuthorizeOAuthUser(w http.ResponseWriter, r *http.Request, service p.Set("client_secret", *sso.Secret) p.Set("code", code) p.Set("grant_type", model.AccessTokenGrantType) - p.Set("redirect_uri", redirectUri) + p.Set("redirect_uri", redirectURI) req, requestErr := http.NewRequest("POST", *sso.TokenEndpoint, strings.NewReader(p.Encode())) if requestErr != nil { @@ -873,7 +873,7 @@ func (a *App) AuthorizeOAuthUser(w http.ResponseWriter, r *http.Request, service } } - req, requestErr = http.NewRequest("GET", *sso.UserApiEndpoint, strings.NewReader("")) + req, requestErr = http.NewRequest("GET", *sso.UserAPIEndpoint, strings.NewReader("")) if requestErr != nil { return nil, "", stateProps, nil, model.NewAppError("AuthorizeOAuthUser", "api.user.authorize_oauth_user.service.app_error", map[string]interface{}{"Service": service}, requestErr.Error(), http.StatusInternalServerError) } @@ -928,12 +928,12 @@ func (a *App) SwitchEmailToOAuth(w http.ResponseWriter, r *http.Request, email, return a.GetSiteURL() + "/login/sso/saml?action=" + model.OAuthActionEmailToSSO + "&email=" + utils.URLEncode(email), nil } - authUrl, err := a.GetAuthorizationCode(w, r, service, stateProps, "") + authURL, err := a.GetAuthorizationCode(w, r, service, stateProps, "") if err != nil { return "", err } - return authUrl, nil + return authURL, nil } func (a *App) SwitchOAuthToEmail(email, password, requesterId string) (string, *model.AppError) { diff --git a/app/oauth_test.go b/app/oauth_test.go index 6cd36f246c..b128fbdee6 100644 --- a/app/oauth_test.go +++ b/app/oauth_test.go @@ -37,7 +37,7 @@ func TestGetOAuthAccessTokenForImplicitFlow(t *testing.T) { authRequest := &model.AuthorizeRequest{ ResponseType: model.ImplicitResponseType, ClientId: oapp.Id, - RedirectUri: oapp.CallbackUrls[0], + RedirectURI: oapp.CallbackUrls[0], Scope: "", State: "123", } @@ -142,9 +142,9 @@ func TestAuthorizeOAuthUser(t *testing.T) { } if userEndpoint { - *cfg.GitLabSettings.UserApiEndpoint = serverURL + "/user" + *cfg.GitLabSettings.UserAPIEndpoint = serverURL + "/user" } else { - *cfg.GitLabSettings.UserApiEndpoint = "" + *cfg.GitLabSettings.UserAPIEndpoint = "" } }) diff --git a/app/opentracing/opentracing_layer.go b/app/opentracing/opentracing_layer.go index 1bfcaad994..783beee676 100644 --- a/app/opentracing/opentracing_layer.go +++ b/app/opentracing/opentracing_layer.go @@ -746,7 +746,7 @@ func (a *OpenTracingAppLayer) AuthenticateUserForLogin(c *request.Context, id st return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) AuthorizeOAuthUser(w http.ResponseWriter, r *http.Request, service string, code string, state string, redirectUri string) (io.ReadCloser, string, map[string]string, *model.User, *model.AppError) { +func (a *OpenTracingAppLayer) AuthorizeOAuthUser(w http.ResponseWriter, r *http.Request, service string, code string, state string, redirectURI string) (io.ReadCloser, string, map[string]string, *model.User, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.AuthorizeOAuthUser") @@ -758,7 +758,7 @@ func (a *OpenTracingAppLayer) AuthorizeOAuthUser(w http.ResponseWriter, r *http. }() defer span.Finish() - resultVar0, resultVar1, resultVar2, resultVar3, resultVar4 := a.app.AuthorizeOAuthUser(w, r, service, code, state, redirectUri) + resultVar0, resultVar1, resultVar2, resultVar3, resultVar4 := a.app.AuthorizeOAuthUser(w, r, service, code, state, redirectURI) if resultVar4 != nil { span.LogFields(spanlog.Error(resultVar4)) @@ -5568,9 +5568,9 @@ func (a *OpenTracingAppLayer) GetEmojiList(page int, perPage int, sort string) ( return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) GetEmojiStaticUrl(emojiName string) (string, *model.AppError) { +func (a *OpenTracingAppLayer) GetEmojiStaticURL(emojiName string) (string, *model.AppError) { origCtx := a.ctx - span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetEmojiStaticUrl") + span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetEmojiStaticURL") a.ctx = newCtx a.app.Srv().Store.SetContext(newCtx) @@ -5580,7 +5580,7 @@ func (a *OpenTracingAppLayer) GetEmojiStaticUrl(emojiName string) (string, *mode }() defer span.Finish() - resultVar0, resultVar1 := a.app.GetEmojiStaticUrl(emojiName) + resultVar0, resultVar1 := a.app.GetEmojiStaticURL(emojiName) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -6753,7 +6753,7 @@ func (a *OpenTracingAppLayer) GetNumberOfChannelsOnTeam(teamID string) (int, *mo return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) GetOAuthAccessTokenForCodeFlow(clientId string, grantType string, redirectUri string, code string, secret string, refreshToken string) (*model.AccessResponse, *model.AppError) { +func (a *OpenTracingAppLayer) GetOAuthAccessTokenForCodeFlow(clientId string, grantType string, redirectURI string, code string, secret string, refreshToken string) (*model.AccessResponse, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetOAuthAccessTokenForCodeFlow") @@ -6765,7 +6765,7 @@ func (a *OpenTracingAppLayer) GetOAuthAccessTokenForCodeFlow(clientId string, gr }() defer span.Finish() - resultVar0, resultVar1 := a.app.GetOAuthAccessTokenForCodeFlow(clientId, grantType, redirectUri, code, secret, refreshToken) + resultVar0, resultVar1 := a.app.GetOAuthAccessTokenForCodeFlow(clientId, grantType, redirectURI, code, secret, refreshToken) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -8158,7 +8158,7 @@ func (a *OpenTracingAppLayer) GetSamlMetadata() (string, *model.AppError) { return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) GetSamlMetadataFromIdp(idpMetadataUrl string) (*model.SamlMetadataResponse, *model.AppError) { +func (a *OpenTracingAppLayer) GetSamlMetadataFromIdp(idpMetadataURL string) (*model.SamlMetadataResponse, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetSamlMetadataFromIdp") @@ -8170,7 +8170,7 @@ func (a *OpenTracingAppLayer) GetSamlMetadataFromIdp(idpMetadataUrl string) (*mo }() defer span.Finish() - resultVar0, resultVar1 := a.app.GetSamlMetadataFromIdp(idpMetadataUrl) + resultVar0, resultVar1 := a.app.GetSamlMetadataFromIdp(idpMetadataURL) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) diff --git a/app/permissions_migrations.go b/app/permissions_migrations.go index 36168b48ad..9f2c91bbca 100644 --- a/app/permissions_migrations.go +++ b/app/permissions_migrations.go @@ -755,7 +755,7 @@ func (a *App) getAddEnvironmentSubsectionPermissions() (permissionsMap, error) { transformations = append(transformations, permissionTransformation{ On: permissionExists(model.PermissionSysconsoleWriteEnvironmentWebServer.Id), Add: []string{ - model.PermissionTestSiteUrl.Id, + model.PermissionTestSiteURL.Id, model.PermissionReloadConfig.Id, model.PermissionInvalidateCaches.Id, }, diff --git a/app/plugin.go b/app/plugin.go index 66671e0dbe..2791d887a3 100644 --- a/app/plugin.go +++ b/app/plugin.go @@ -195,11 +195,11 @@ func (s *Server) initPlugins(c *request.Context, pluginDir, webappPluginDir stri return } - newApiFunc := func(manifest *model.Manifest) plugin.API { + newAPIFunc := func(manifest *model.Manifest) plugin.API { return New(ServerConnector(s)).NewPluginAPI(c, manifest) } - env, err := plugin.NewEnvironment(newApiFunc, NewDriverImpl(s), pluginDir, webappPluginDir, s.Log, s.Metrics) + env, err := plugin.NewEnvironment(newAPIFunc, NewDriverImpl(s), pluginDir, webappPluginDir, s.Log, s.Metrics) if err != nil { mlog.Error("Failed to start up plugins", mlog.Err(err)) return @@ -553,7 +553,7 @@ func (s *Server) getPrepackagedPlugin(pluginID, version string) (*plugin.Prepack // getRemoteMarketplacePlugin returns plugin from marketplace-server. func (s *Server) getRemoteMarketplacePlugin(pluginID, version string) (*model.BaseMarketplacePlugin, *model.AppError) { marketplaceClient, err := marketplace.NewClient( - *s.Config().PluginSettings.MarketplaceUrl, + *s.Config().PluginSettings.MarketplaceURL, s.HTTPService(), ) if err != nil { @@ -581,7 +581,7 @@ func (a *App) getRemotePlugins() (map[string]*model.MarketplacePlugin, *model.Ap } marketplaceClient, err := marketplace.NewClient( - *a.Config().PluginSettings.MarketplaceUrl, + *a.Config().PluginSettings.MarketplaceURL, a.HTTPService(), ) if err != nil { diff --git a/app/plugin_api_test.go b/app/plugin_api_test.go index 09d8d9b0f3..ac7ccc02c1 100644 --- a/app/plugin_api_test.go +++ b/app/plugin_api_test.go @@ -69,7 +69,7 @@ func setDefaultPluginConfig(th *TestHelper, pluginID string) { }) } -func setupMultiPluginApiTest(t *testing.T, pluginCodes []string, pluginManifests []string, pluginIDs []string, asMain bool, app *App, c *request.Context) string { +func setupMultiPluginAPITest(t *testing.T, pluginCodes []string, pluginManifests []string, pluginIDs []string, asMain bool, app *App, c *request.Context) string { pluginDir, err := ioutil.TempDir("", "") require.NoError(t, err) t.Cleanup(func() { @@ -124,10 +124,10 @@ func setupMultiPluginApiTest(t *testing.T, pluginCodes []string, pluginManifests return pluginDir } -func setupPluginApiTest(t *testing.T, pluginCode string, pluginManifest string, pluginID string, app *App, c *request.Context) string { +func setupPluginAPITest(t *testing.T, pluginCode string, pluginManifest string, pluginID string, app *App, c *request.Context) string { asMain := pluginID != "test_db_driver" - return setupMultiPluginApiTest(t, + return setupMultiPluginAPITest(t, []string{pluginCode}, []string{pluginManifest}, []string{pluginID}, asMain, app, c) } @@ -138,7 +138,7 @@ func TestPublicFilesPathConfiguration(t *testing.T) { pluginID := "com.mattermost.sample" - pluginDir := setupPluginApiTest(t, + pluginDir := setupPluginAPITest(t, ` package main @@ -847,9 +847,9 @@ func TestPluginAPIInstallPlugin(t *testing.T) { } func TestInstallPlugin(t *testing.T) { - // TODO(ilgooz): remove this setup func to use existent setupPluginApiTest(). - // following setupTest() func is a modified version of setupPluginApiTest(). - // we need a modified version of setupPluginApiTest() because it wasn't possible to use it directly here + // TODO(ilgooz): remove this setup func to use existent setupPluginAPITest(). + // following setupTest() func is a modified version of setupPluginAPITest(). + // we need a modified version of setupPluginAPITest() because it wasn't possible to use it directly here // since it removes plugin dirs right after it returns, does not update App configs with the plugin // dirs and this behavior tends to break this test as a result. setupTest := func(t *testing.T, pluginCode string, pluginManifest string, pluginID string, app *App, c *request.Context) (func(), string) { @@ -1067,7 +1067,7 @@ func pluginAPIHookTest(t *testing.T, th *TestHelper, fileName string, id string, schema = settingsSchema } th.App.srv.sqlStore = th.GetSqlStore() - setupPluginApiTest(t, code, + setupPluginAPITest(t, code, fmt.Sprintf(`{"id": "%v", "server": {"executable": "backend.exe"}, "settings_schema": %v}`, id, schema), id, th.App, th.Context) hooks, err := th.App.GetPluginsEnvironment().HooksForPlugin(id) @@ -1404,7 +1404,7 @@ func TestInterpluginPluginHTTP(t *testing.T) { th := Setup(t) defer th.TearDown() - setupMultiPluginApiTest(t, + setupMultiPluginAPITest(t, []string{` package main @@ -1529,7 +1529,7 @@ func TestInterpluginPluginHTTP(t *testing.T) { assert.Equal(t, "ok", ret) } -func TestApiMetrics(t *testing.T) { +func TestAPIMetrics(t *testing.T) { th := Setup(t) defer th.TearDown() @@ -1581,7 +1581,7 @@ func TestApiMetrics(t *testing.T) { metricsMock.On("ObservePluginMultiHookDuration", mock.Anything).Return() // Setup mocks - metricsMock.On("ObservePluginApiDuration", pluginID, "UpdateUser", true, mock.Anything).Return() + metricsMock.On("ObservePluginAPIDuration", pluginID, "UpdateUser", true, mock.Anything).Return() _, _, activationErr := env.Activate(pluginID) require.NoError(t, activationErr) diff --git a/app/plugin_hooks_test.go b/app/plugin_hooks_test.go index eb435e0f90..cd1c00d6a2 100644 --- a/app/plugin_hooks_test.go +++ b/app/plugin_hooks_test.go @@ -1093,7 +1093,7 @@ func TestHookMetrics(t *testing.T) { metricsMock.On("ObservePluginHookDuration", pluginID, "UserHasBeenCreated", true, mock.Anything).Return() // Don't care about these calls. - metricsMock.On("ObservePluginApiDuration", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return() + metricsMock.On("ObservePluginAPIDuration", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return() metricsMock.On("ObservePluginMultiHookIterationDuration", mock.Anything, mock.Anything, mock.Anything).Return() metricsMock.On("ObservePluginMultiHookDuration", mock.Anything).Return() diff --git a/app/post_metadata.go b/app/post_metadata.go index 66cd719110..a591f2d23a 100644 --- a/app/post_metadata.go +++ b/app/post_metadata.go @@ -87,8 +87,8 @@ func (a *App) OverrideIconURLIfEmoji(post *model.Post) { emojiName = strings.ReplaceAll(emojiName, ":", "") - if emojiUrl, err := a.GetEmojiStaticUrl(emojiName); err == nil { - post.AddProp(model.PostPropsOverrideIconUrl, emojiUrl) + if emojiURL, err := a.GetEmojiStaticURL(emojiName); err == nil { + post.AddProp(model.PostPropsOverrideIconURL, emojiURL) } else { mlog.Warn("Failed to retrieve URL for overridden profile icon (emoji)", mlog.String("emojiName", emojiName), mlog.Err(err)) } diff --git a/app/post_metadata_test.go b/app/post_metadata_test.go index c16e8ceb47..4204008937 100644 --- a/app/post_metadata_test.go +++ b/app/post_metadata_test.go @@ -301,7 +301,7 @@ func TestPreparePostForClient(t *testing.T) { require.Nil(t, err) - post.AddProp(model.PostPropsOverrideIconUrl, url) + post.AddProp(model.PostPropsOverrideIconURL, url) post.AddProp(model.PostPropsOverrideIconEmoji, emoji) return th.App.PreparePostForClient(post, false, false) @@ -309,12 +309,12 @@ func TestPreparePostForClient(t *testing.T) { emoji := "basketball" url := "http://host.com/image.png" - overridenUrl := "/static/emoji/1f3c0.png" + overridenURL := "/static/emoji/1f3c0.png" t.Run("does not override icon URL", func(t *testing.T) { clientPost := prepare(false, url, emoji) - s, ok := clientPost.GetProps()[model.PostPropsOverrideIconUrl] + s, ok := clientPost.GetProps()[model.PostPropsOverrideIconURL] assert.True(t, ok) assert.EqualValues(t, url, s) s, ok = clientPost.GetProps()[model.PostPropsOverrideIconEmoji] @@ -325,9 +325,9 @@ func TestPreparePostForClient(t *testing.T) { t.Run("overrides icon URL", func(t *testing.T) { clientPost := prepare(true, url, emoji) - s, ok := clientPost.GetProps()[model.PostPropsOverrideIconUrl] + s, ok := clientPost.GetProps()[model.PostPropsOverrideIconURL] assert.True(t, ok) - assert.EqualValues(t, overridenUrl, s) + assert.EqualValues(t, overridenURL, s) s, ok = clientPost.GetProps()[model.PostPropsOverrideIconEmoji] assert.True(t, ok) assert.EqualValues(t, emoji, s) @@ -337,9 +337,9 @@ func TestPreparePostForClient(t *testing.T) { colonEmoji := ":basketball:" clientPost := prepare(true, url, colonEmoji) - s, ok := clientPost.GetProps()[model.PostPropsOverrideIconUrl] + s, ok := clientPost.GetProps()[model.PostPropsOverrideIconURL] assert.True(t, ok) - assert.EqualValues(t, overridenUrl, s) + assert.EqualValues(t, overridenURL, s) s, ok = clientPost.GetProps()[model.PostPropsOverrideIconEmoji] assert.True(t, ok) assert.EqualValues(t, colonEmoji, s) diff --git a/app/post_test.go b/app/post_test.go index 050ebe919a..7cccb59e26 100644 --- a/app/post_test.go +++ b/app/post_test.go @@ -53,7 +53,7 @@ func TestCreatePostDeduplicate(t *testing.T) { }) t.Run("post rejected by plugin leaves cache ready for non-deduplicated try", func(t *testing.T) { - setupPluginApiTest(t, ` + setupPluginAPITest(t, ` package main import ( @@ -102,7 +102,7 @@ func TestCreatePostDeduplicate(t *testing.T) { }) t.Run("slow posting after cache entry blocks duplicate request", func(t *testing.T) { - setupPluginApiTest(t, ` + setupPluginAPITest(t, ` package main import ( diff --git a/app/saml.go b/app/saml.go index 1e5be0f6d3..0d76cbd522 100644 --- a/app/saml.go +++ b/app/saml.go @@ -178,17 +178,17 @@ func (a *App) GetSamlCertificateStatus() *model.SamlCertificateStatus { return status } -func (a *App) GetSamlMetadataFromIdp(idpMetadataUrl string) (*model.SamlMetadataResponse, *model.AppError) { +func (a *App) GetSamlMetadataFromIdp(idpMetadataURL string) (*model.SamlMetadataResponse, *model.AppError) { if a.Saml() == nil { err := model.NewAppError("GetSamlMetadataFromIdp", "api.admin.saml.not_available.app_error", nil, "", http.StatusNotImplemented) return nil, err } - if !strings.HasPrefix(idpMetadataUrl, "http://") && !strings.HasPrefix(idpMetadataUrl, "https://") { - idpMetadataUrl = "https://" + idpMetadataUrl + if !strings.HasPrefix(idpMetadataURL, "http://") && !strings.HasPrefix(idpMetadataURL, "https://") { + idpMetadataURL = "https://" + idpMetadataURL } - idpMetadataRaw, err := a.FetchSamlMetadataFromIdp(idpMetadataUrl) + idpMetadataRaw, err := a.FetchSamlMetadataFromIdp(idpMetadataURL) if err != nil { return nil, err } @@ -228,7 +228,7 @@ func (a *App) BuildSamlMetadataObject(idpMetadata []byte) (*model.SamlMetadataRe } data := &model.SamlMetadataResponse{} - data.IdpDescriptorUrl = entityDescriptor.EntityID + data.IdpDescriptorURL = entityDescriptor.EntityID if entityDescriptor.IDPSSODescriptors == nil || len(entityDescriptor.IDPSSODescriptors) == 0 { err := model.NewAppError("BuildSamlMetadataObject", "api.admin.saml.invalid_xml_missing_idpssodescriptors.app_error", nil, "", http.StatusInternalServerError) @@ -241,7 +241,7 @@ func (a *App) BuildSamlMetadataObject(idpMetadata []byte) (*model.SamlMetadataRe return nil, err } - data.IdpUrl = idpSSODescriptor.SingleSignOnServices[0].Location + data.IdpURL = idpSSODescriptor.SingleSignOnServices[0].Location if idpSSODescriptor.SSODescriptor.RoleDescriptor.KeyDescriptors == nil || len(idpSSODescriptor.SSODescriptor.RoleDescriptor.KeyDescriptors) == 0 { err := model.NewAppError("BuildSamlMetadataObject", "api.admin.saml.invalid_xml_missing_keydescriptor.app_error", nil, "", http.StatusInternalServerError) return nil, err diff --git a/app/searchengine.go b/app/searchengine.go index 7c4c0cbc83..eba9878814 100644 --- a/app/searchengine.go +++ b/app/searchengine.go @@ -12,7 +12,7 @@ import ( func (a *App) TestElasticsearch(cfg *model.Config) *model.AppError { if *cfg.ElasticsearchSettings.Password == model.FakeSetting { - if *cfg.ElasticsearchSettings.ConnectionUrl == *a.Config().ElasticsearchSettings.ConnectionUrl && *cfg.ElasticsearchSettings.Username == *a.Config().ElasticsearchSettings.Username { + if *cfg.ElasticsearchSettings.ConnectionURL == *a.Config().ElasticsearchSettings.ConnectionURL && *cfg.ElasticsearchSettings.Username == *a.Config().ElasticsearchSettings.Username { *cfg.ElasticsearchSettings.Password = *a.Config().ElasticsearchSettings.Password } else { return model.NewAppError("TestElasticsearch", "ent.elasticsearch.test_config.reenter_password", nil, "", http.StatusBadRequest) diff --git a/app/server.go b/app/server.go index 9f0765334a..a0f4e86b5c 100644 --- a/app/server.go +++ b/app/server.go @@ -591,7 +591,7 @@ func NewServer(options ...Option) (*Server, error) { mlog.Info("Printing current working", mlog.String("directory", pwd)) mlog.Info("Loaded config", mlog.String("source", s.configStore.String())) - s.checkPushNotificationServerUrl() + s.checkPushNotificationServerURL() s.ReloadConfig() @@ -1431,7 +1431,7 @@ func (a *App) OriginChecker() func(*http.Request) bool { return nil } -func (s *Server) checkPushNotificationServerUrl() { +func (s *Server) checkPushNotificationServerURL() { notificationServer := *s.Config().EmailSettings.PushNotificationServer if strings.HasPrefix(notificationServer, "http://") { mlog.Warn("Your push notification server is configured with HTTP. For improved security, update to HTTPS in your configuration.") @@ -1766,7 +1766,7 @@ func (s *Server) StartSearchEngine() (string, string) { mlog.Error(err.Error()) } }) - } else if s.SearchEngine.ElasticsearchEngine != nil && *oldConfig.ElasticsearchSettings.Password != *newConfig.ElasticsearchSettings.Password || *oldConfig.ElasticsearchSettings.Username != *newConfig.ElasticsearchSettings.Username || *oldConfig.ElasticsearchSettings.ConnectionUrl != *newConfig.ElasticsearchSettings.ConnectionUrl || *oldConfig.ElasticsearchSettings.Sniff != *newConfig.ElasticsearchSettings.Sniff { + } else if s.SearchEngine.ElasticsearchEngine != nil && *oldConfig.ElasticsearchSettings.Password != *newConfig.ElasticsearchSettings.Password || *oldConfig.ElasticsearchSettings.Username != *newConfig.ElasticsearchSettings.Username || *oldConfig.ElasticsearchSettings.ConnectionURL != *newConfig.ElasticsearchSettings.ConnectionURL || *oldConfig.ElasticsearchSettings.Sniff != *newConfig.ElasticsearchSettings.Sniff { s.Go(func() { if *oldConfig.ElasticsearchSettings.EnableIndexing { if err := s.SearchEngine.ElasticsearchEngine.Stop(); err != nil { diff --git a/app/slashcommands/command_loadtest.go b/app/slashcommands/command_loadtest.go index 75495fbea0..cd410db8b5 100644 --- a/app/slashcommands/command_loadtest.go +++ b/app/slashcommands/command_loadtest.go @@ -157,7 +157,7 @@ func (lt *LoadTestProvider) doCommand(a *app.App, c *request.Context, args *mode } if strings.HasPrefix(message, "url") { - return lt.UrlCommand(a, c, args, message) + return lt.URLCommand(a, c, args, message) } if strings.HasPrefix(message, "json") { @@ -460,7 +460,7 @@ func (*LoadTestProvider) PostCommand(a *app.App, args *model.CommandArgs, messag return &model.CommandResponse{Text: "Added a post to " + channel.DisplayName, ResponseType: model.CommandResponseTypeEphemeral}, nil } -func (*LoadTestProvider) UrlCommand(a *app.App, c *request.Context, args *model.CommandArgs, message string) (*model.CommandResponse, error) { +func (*LoadTestProvider) URLCommand(a *app.App, c *request.Context, args *model.CommandArgs, message string) (*model.CommandResponse, error) { url := strings.TrimSpace(strings.TrimPrefix(message, "url")) if url == "" { return &model.CommandResponse{Text: "Command must contain a url", ResponseType: model.CommandResponseTypeEphemeral}, nil diff --git a/app/webhook_test.go b/app/webhook_test.go index 265cef1841..3f0dffc753 100644 --- a/app/webhook_test.go +++ b/app/webhook_test.go @@ -611,11 +611,11 @@ func TestTriggerOutGoingWebhookWithUsernameAndIconURL(t *testing.T) { WebhookResponse *model.OutgoingWebhookResponse } - createOutgoingWebhook := func(channel *model.Channel, testCallBackUrl string, th *TestHelper) (*model.OutgoingWebhook, *model.AppError) { + createOutgoingWebhook := func(channel *model.Channel, testCallBackURL string, th *TestHelper) (*model.OutgoingWebhook, *model.AppError) { outgoingWebhook := model.OutgoingWebhook{ ChannelId: channel.Id, TeamId: channel.TeamId, - CallbackURLs: []string{testCallBackUrl}, + CallbackURLs: []string{testCallBackURL}, Username: "some-user-name", IconURL: "http://some-icon/", DisplayName: "some-display-name", diff --git a/cmd/mattermost/commands/config_test.go b/cmd/mattermost/commands/config_test.go index 32699a4996..32841f9328 100644 --- a/cmd/mattermost/commands/config_test.go +++ b/cmd/mattermost/commands/config_test.go @@ -61,7 +61,7 @@ type TestNewConfig struct { } type TestNewServiceSettings struct { - SiteUrl *string + SiteURL *string UseLetsEncrypt *bool TLSStrictTransportMaxAge *int64 AllowedThemes []string @@ -483,7 +483,7 @@ func TestUpdateMap(t *testing.T) { // create a config to make changes config := TestNewConfig{ TestNewServiceSettings{ - SiteUrl: model.NewString("abc.def"), + SiteURL: model.NewString("abc.def"), UseLetsEncrypt: model.NewBool(false), TLSStrictTransportMaxAge: model.NewInt64(36), AllowedThemes: []string{"Hello", "World"}, @@ -505,7 +505,7 @@ func TestUpdateMap(t *testing.T) { }{ { Name: "check for Map and string", - configSettings: []string{"TestNewServiceSettings", "SiteUrl"}, + configSettings: []string{"TestNewServiceSettings", "SiteURL"}, newVal: []string{"siteurl"}, expected: "siteurl", }, diff --git a/cmd/mattermost/commands/webhook.go b/cmd/mattermost/commands/webhook.go index 6e3c02a57b..b4bc4a9d4f 100644 --- a/cmd/mattermost/commands/webhook.go +++ b/cmd/mattermost/commands/webhook.go @@ -245,9 +245,9 @@ func modifyIncomingWebhookCmdF(command *cobra.Command, args []string) (cmdError if description != "" { updatedHook.Description = description } - iconUrl, _ := command.Flags().GetString("icon") - if iconUrl != "" { - updatedHook.IconURL = iconUrl + iconURL, _ := command.Flags().GetString("icon") + if iconURL != "" { + updatedHook.IconURL = iconURL } channelLocked, _ := command.Flags().GetBool("lock-to-channel") updatedHook.ChannelLocked = channelLocked diff --git a/cmd/mattermost/commands/webhook_test.go b/cmd/mattermost/commands/webhook_test.go index 803b807a3e..5f5a56583e 100644 --- a/cmd/mattermost/commands/webhook_test.go +++ b/cmd/mattermost/commands/webhook_test.go @@ -218,18 +218,18 @@ func TestModifyIncomingWebhook(t *testing.T) { modifiedDescription := "myhookincdesc2" modifiedDisplayName := "myhookincname2" - modifiedIconUrl := "myhookincicon2" + modifiedIconURL := "myhookincicon2" modifiedChannelLocked := true modifiedChannelId := th.BasicChannel2.Id - th.CheckCommand(t, "webhook", "modify-incoming", oldHook.Id, "--channel", modifiedChannelId, "--description", modifiedDescription, "--display-name", modifiedDisplayName, "--icon", modifiedIconUrl, "--lock-to-channel", strconv.FormatBool(modifiedChannelLocked)) + th.CheckCommand(t, "webhook", "modify-incoming", oldHook.Id, "--channel", modifiedChannelId, "--description", modifiedDescription, "--display-name", modifiedDisplayName, "--icon", modifiedIconURL, "--lock-to-channel", strconv.FormatBool(modifiedChannelLocked)) modifiedHook, err := th.App.GetIncomingWebhook(oldHook.Id) require.Nil(t, err, "unable to retrieve modified incoming webhook") successUpdate := modifiedHook.DisplayName != modifiedDisplayName || modifiedHook.Description != modifiedDescription || - modifiedHook.IconURL != modifiedIconUrl || + modifiedHook.IconURL != modifiedIconURL || modifiedHook.ChannelLocked != modifiedChannelLocked || modifiedHook.ChannelId != modifiedChannelId require.False(t, successUpdate, "Failed to update incoming webhook") diff --git a/config/client.go b/config/client.go index 5aa9174448..d758a86462 100644 --- a/config/client.go +++ b/config/client.go @@ -85,8 +85,8 @@ func GenerateClientConfig(c *model.Config, telemetryID string, license *model.Li props["EnableEmojiPicker"] = strconv.FormatBool(*c.ServiceSettings.EnableEmojiPicker) props["EnableGifPicker"] = strconv.FormatBool(*c.ServiceSettings.EnableGifPicker) - props["GfycatApiKey"] = *c.ServiceSettings.GfycatApiKey - props["GfycatApiSecret"] = *c.ServiceSettings.GfycatApiSecret + props["GfycatApiKey"] = *c.ServiceSettings.GfycatAPIKey + props["GfycatApiSecret"] = *c.ServiceSettings.GfycatAPISecret props["MaxFileSize"] = strconv.FormatInt(*c.FileSettings.MaxFileSize, 10) props["MaxNotificationsPerChannel"] = strconv.FormatInt(*c.TeamSettings.MaxNotificationsPerChannel, 10) @@ -138,8 +138,8 @@ func GenerateClientConfig(c *model.Config, telemetryID string, license *model.Li props["DataRetentionFileRetentionDays"] = "0" props["CWSUrl"] = "" - props["CustomUrlSchemes"] = strings.Join(c.DisplaySettings.CustomUrlSchemes, ",") - props["IsDefaultMarketplace"] = strconv.FormatBool(*c.PluginSettings.MarketplaceUrl == model.PluginSettingsDefaultMarketplaceUrl) + props["CustomUrlSchemes"] = strings.Join(c.DisplaySettings.CustomURLSchemes, ",") + props["IsDefaultMarketplace"] = strconv.FormatBool(*c.PluginSettings.MarketplaceURL == model.PluginSettingsDefaultMarketplaceURL) props["ExperimentalSharedChannels"] = "false" props["CollapsedThreads"] = *c.ServiceSettings.CollapsedThreads @@ -205,7 +205,7 @@ func GenerateClientConfig(c *model.Config, telemetryID string, license *model.Li } if *license.Features.Cloud { - props["CWSUrl"] = *c.CloudSettings.CWSUrl + props["CWSUrl"] = *c.CloudSettings.CWSURL } if *license.Features.SharedChannels { diff --git a/config/client_test.go b/config/client_test.go index 4d282a3b96..b10ff9bdaf 100644 --- a/config/client_test.go +++ b/config/client_test.go @@ -142,7 +142,7 @@ func TestGetClientConfig(t *testing.T) { "default marketplace", &model.Config{ PluginSettings: model.PluginSettings{ - MarketplaceUrl: model.NewString(model.PluginSettingsDefaultMarketplaceUrl), + MarketplaceURL: model.NewString(model.PluginSettingsDefaultMarketplaceURL), }, }, "tag1", @@ -155,7 +155,7 @@ func TestGetClientConfig(t *testing.T) { "non-default marketplace", &model.Config{ PluginSettings: model.PluginSettings{ - MarketplaceUrl: model.NewString("http://example.com"), + MarketplaceURL: model.NewString("http://example.com"), }, }, "tag1", diff --git a/config/utils.go b/config/utils.go index 7c9eae64f1..cd8f05c1e4 100644 --- a/config/utils.go +++ b/config/utils.go @@ -85,8 +85,8 @@ func desanitize(actual, target *model.Config) { *target.MessageExportSettings.GlobalRelaySettings.SMTPPassword = *actual.MessageExportSettings.GlobalRelaySettings.SMTPPassword } - if target.ServiceSettings.GfycatApiSecret != nil && *target.ServiceSettings.GfycatApiSecret == model.FakeSetting { - *target.ServiceSettings.GfycatApiSecret = *actual.ServiceSettings.GfycatApiSecret + if target.ServiceSettings.GfycatAPISecret != nil && *target.ServiceSettings.GfycatAPISecret == model.FakeSetting { + *target.ServiceSettings.GfycatAPISecret = *actual.ServiceSettings.GfycatAPISecret } if *target.ServiceSettings.SplitKey == model.FakeSetting { diff --git a/einterfaces/metrics.go b/einterfaces/metrics.go index 2e0f4deb7f..4815a35b01 100644 --- a/einterfaces/metrics.go +++ b/einterfaces/metrics.go @@ -54,7 +54,7 @@ type MetricsInterface interface { IncrementFilesSearchCounter() ObserveFilesSearchDuration(elapsed float64) ObserveStoreMethodDuration(method, success string, elapsed float64) - ObserveApiEndpointDuration(endpoint, method, statusCode string, elapsed float64) + ObserveAPIEndpointDuration(endpoint, method, statusCode string, elapsed float64) IncrementPostIndexCounter() IncrementFileIndexCounter() IncrementUserIndexCounter() @@ -63,7 +63,7 @@ type MetricsInterface interface { ObservePluginHookDuration(pluginID, hookName string, success bool, elapsed float64) ObservePluginMultiHookIterationDuration(pluginID string, elapsed float64) ObservePluginMultiHookDuration(elapsed float64) - ObservePluginApiDuration(pluginID, apiName string, success bool, elapsed float64) + ObservePluginAPIDuration(pluginID, apiName string, success bool, elapsed float64) ObserveEnabledUsers(users int64) GetLoggerMetricsCollector() logr.MetricsCollector diff --git a/einterfaces/mocks/MetricsInterface.go b/einterfaces/mocks/MetricsInterface.go index f00a9c8cb1..b854a567b2 100644 --- a/einterfaces/mocks/MetricsInterface.go +++ b/einterfaces/mocks/MetricsInterface.go @@ -237,8 +237,8 @@ func (_m *MetricsInterface) IncrementWebsocketReconnectEvent(eventType string) { _m.Called(eventType) } -// ObserveApiEndpointDuration provides a mock function with given fields: endpoint, method, statusCode, elapsed -func (_m *MetricsInterface) ObserveApiEndpointDuration(endpoint string, method string, statusCode string, elapsed float64) { +// ObserveAPIEndpointDuration provides a mock function with given fields: endpoint, method, statusCode, elapsed +func (_m *MetricsInterface) ObserveAPIEndpointDuration(endpoint string, method string, statusCode string, elapsed float64) { _m.Called(endpoint, method, statusCode, elapsed) } @@ -257,8 +257,8 @@ func (_m *MetricsInterface) ObserveFilesSearchDuration(elapsed float64) { _m.Called(elapsed) } -// ObservePluginApiDuration provides a mock function with given fields: pluginID, apiName, success, elapsed -func (_m *MetricsInterface) ObservePluginApiDuration(pluginID string, apiName string, success bool, elapsed float64) { +// ObservePluginAPIDuration provides a mock function with given fields: pluginID, apiName, success, elapsed +func (_m *MetricsInterface) ObservePluginAPIDuration(pluginID string, apiName string, success bool, elapsed float64) { _m.Called(pluginID, apiName, success, elapsed) } diff --git a/manualtesting/manual_testing.go b/manualtesting/manual_testing.go index ca92b05f11..0f80c479bf 100644 --- a/manualtesting/manual_testing.go +++ b/manualtesting/manual_testing.go @@ -35,7 +35,7 @@ type TestEnvironment struct { // Init adds manualtest endpoint to the API. func Init(api4 *api4.API) { - api4.BaseRoutes.Root.Handle("/manualtest", api4.ApiHandler(manualTest)).Methods("GET") + api4.BaseRoutes.Root.Handle("/manualtest", api4.APIHandler(manualTest)).Methods("GET") } func manualTest(c *web.Context, w http.ResponseWriter, r *http.Request) { diff --git a/model/access.go b/model/access.go index 4ea07d1805..f17c8fbe95 100644 --- a/model/access.go +++ b/model/access.go @@ -35,7 +35,6 @@ type AccessResponse struct { // IsValid validates the AccessData and returns an error if it isn't configured // correctly. func (ad *AccessData) IsValid() *AppError { - if ad.ClientId == "" || len(ad.ClientId) > 26 { return NewAppError("AccessData.IsValid", "model.access.is_valid.client_id.app_error", nil, "", http.StatusBadRequest) } @@ -52,7 +51,7 @@ func (ad *AccessData) IsValid() *AppError { return NewAppError("AccessData.IsValid", "model.access.is_valid.refresh_token.app_error", nil, "", http.StatusBadRequest) } - if ad.RedirectUri == "" || len(ad.RedirectUri) > 256 || !IsValidHTTPUrl(ad.RedirectUri) { + if ad.RedirectUri == "" || len(ad.RedirectUri) > 256 || !IsValidHTTPURL(ad.RedirectUri) { return NewAppError("AccessData.IsValid", "model.access.is_valid.redirect_uri.app_error", nil, "", http.StatusBadRequest) } diff --git a/model/authorize.go b/model/authorize.go index c0dd49e9bf..1a767e3c21 100644 --- a/model/authorize.go +++ b/model/authorize.go @@ -28,7 +28,7 @@ type AuthData struct { type AuthorizeRequest struct { ResponseType string `json:"response_type"` ClientId string `json:"client_id"` - RedirectUri string `json:"redirect_uri"` + RedirectURI string `json:"redirect_uri"` Scope string `json:"scope"` State string `json:"state"` } @@ -57,7 +57,7 @@ func (ad *AuthData) IsValid() *AppError { return NewAppError("AuthData.IsValid", "model.authorize.is_valid.create_at.app_error", nil, "client_id="+ad.ClientId, http.StatusBadRequest) } - if len(ad.RedirectUri) > 256 || !IsValidHTTPUrl(ad.RedirectUri) { + if len(ad.RedirectUri) > 256 || !IsValidHTTPURL(ad.RedirectUri) { return NewAppError("AuthData.IsValid", "model.authorize.is_valid.redirect_uri.app_error", nil, "client_id="+ad.ClientId, http.StatusBadRequest) } @@ -84,7 +84,7 @@ func (ar *AuthorizeRequest) IsValid() *AppError { return NewAppError("AuthData.IsValid", "model.authorize.is_valid.response_type.app_error", nil, "", http.StatusBadRequest) } - if ar.RedirectUri == "" || len(ar.RedirectUri) > 256 || !IsValidHTTPUrl(ar.RedirectUri) { + if ar.RedirectURI == "" || len(ar.RedirectURI) > 256 || !IsValidHTTPURL(ar.RedirectURI) { return NewAppError("AuthData.IsValid", "model.authorize.is_valid.redirect_uri.app_error", nil, "client_id="+ar.ClientId, http.StatusBadRequest) } diff --git a/model/client4.go b/model/client4.go index cd88de794e..7b9c8b4d0b 100644 --- a/model/client4.go +++ b/model/client4.go @@ -44,9 +44,9 @@ const ( ClientDir = "client" - ApiUrlSuffixV1 = "/api/v1" - ApiUrlSuffixV4 = "/api/v4" - ApiUrlSuffix = ApiUrlSuffixV4 + APIURLSuffixV1 = "/api/v1" + APIURLSuffixV4 = "/api/v4" + APIURLSuffix = APIURLSuffixV4 ) type Response struct { @@ -58,8 +58,8 @@ type Response struct { } type Client4 struct { - Url string // The location of the server, for example "http://localhost:8065" - ApiUrl string // The api location of the server, for example "http://localhost:8065/api/v4" + URL string // The location of the server, for example "http://localhost:8065" + APIURL string // The api location of the server, for example "http://localhost:8065/api/v4" HTTPClient *http.Client // The http client AuthToken string AuthType string @@ -108,7 +108,7 @@ func closeBody(r *http.Response) { func NewAPIv4Client(url string) *Client4 { url = strings.TrimRight(url, "/") - return &Client4{url, url + ApiUrlSuffix, &http.Client{}, "", "", map[string]string{}, "", ""} + return &Client4{url, url + APIURLSuffix, &http.Client{}, "", "", map[string]string{}, "", ""} } func NewAPIv4SocketClient(socketPath string) *Client4 { @@ -547,51 +547,51 @@ func (c *Client4) permissionsRoute() string { return "/permissions" } -func (c *Client4) DoApiGet(url string, etag string) (*http.Response, error) { - return c.DoApiRequest(http.MethodGet, c.ApiUrl+url, "", etag) +func (c *Client4) DoAPIGet(url string, etag string) (*http.Response, error) { + return c.DoAPIRequest(http.MethodGet, c.APIURL+url, "", etag) } -func (c *Client4) DoApiPost(url string, data string) (*http.Response, error) { - return c.DoApiRequest(http.MethodPost, c.ApiUrl+url, data, "") +func (c *Client4) DoAPIPost(url string, data string) (*http.Response, error) { + return c.DoAPIRequest(http.MethodPost, c.APIURL+url, data, "") } -func (c *Client4) doApiDeleteBytes(url string, data []byte) (*http.Response, error) { - return c.doApiRequestBytes(http.MethodDelete, c.ApiUrl+url, data, "") +func (c *Client4) DoAPIDeleteBytes(url string, data []byte) (*http.Response, error) { + return c.DoAPIRequestBytes(http.MethodDelete, c.APIURL+url, data, "") } -func (c *Client4) doApiPatchBytes(url string, data []byte) (*http.Response, error) { - return c.doApiRequestBytes(http.MethodPatch, c.ApiUrl+url, data, "") +func (c *Client4) DoAPIPatchBytes(url string, data []byte) (*http.Response, error) { + return c.DoAPIRequestBytes(http.MethodPatch, c.APIURL+url, data, "") } -func (c *Client4) doApiPostBytes(url string, data []byte) (*http.Response, error) { - return c.doApiRequestBytes(http.MethodPost, c.ApiUrl+url, data, "") +func (c *Client4) DoAPIPostBytes(url string, data []byte) (*http.Response, error) { + return c.DoAPIRequestBytes(http.MethodPost, c.APIURL+url, data, "") } -func (c *Client4) DoApiPut(url string, data string) (*http.Response, error) { - return c.DoApiRequest(http.MethodPut, c.ApiUrl+url, data, "") +func (c *Client4) DoAPIPut(url string, data string) (*http.Response, error) { + return c.DoAPIRequest(http.MethodPut, c.APIURL+url, data, "") } -func (c *Client4) doApiPutBytes(url string, data []byte) (*http.Response, error) { - return c.doApiRequestBytes(http.MethodPut, c.ApiUrl+url, data, "") +func (c *Client4) DoAPIPutBytes(url string, data []byte) (*http.Response, error) { + return c.DoAPIRequestBytes(http.MethodPut, c.APIURL+url, data, "") } -func (c *Client4) DoApiDelete(url string) (*http.Response, error) { - return c.DoApiRequest(http.MethodDelete, c.ApiUrl+url, "", "") +func (c *Client4) DoAPIDelete(url string) (*http.Response, error) { + return c.DoAPIRequest(http.MethodDelete, c.APIURL+url, "", "") } -func (c *Client4) DoApiRequest(method, url, data, etag string) (*http.Response, error) { - return c.doApiRequestReader(method, url, strings.NewReader(data), map[string]string{HeaderEtagClient: etag}) +func (c *Client4) DoAPIRequest(method, url, data, etag string) (*http.Response, error) { + return c.DoAPIRequestReader(method, url, strings.NewReader(data), map[string]string{HeaderEtagClient: etag}) } -func (c *Client4) DoApiRequestWithHeaders(method, url, data string, headers map[string]string) (*http.Response, error) { - return c.doApiRequestReader(method, url, strings.NewReader(data), headers) +func (c *Client4) DoAPIRequestWithHeaders(method, url, data string, headers map[string]string) (*http.Response, error) { + return c.DoAPIRequestReader(method, url, strings.NewReader(data), headers) } -func (c *Client4) doApiRequestBytes(method, url string, data []byte, etag string) (*http.Response, error) { - return c.doApiRequestReader(method, url, bytes.NewReader(data), map[string]string{HeaderEtagClient: etag}) +func (c *Client4) DoAPIRequestBytes(method, url string, data []byte, etag string) (*http.Response, error) { + return c.DoAPIRequestReader(method, url, bytes.NewReader(data), map[string]string{HeaderEtagClient: etag}) } -func (c *Client4) doApiRequestReader(method, url string, data io.Reader, headers map[string]string) (*http.Response, error) { +func (c *Client4) DoAPIRequestReader(method, url string, data io.Reader, headers map[string]string) (*http.Response, error) { rq, err := http.NewRequest(method, url, data) if err != nil { return nil, err @@ -633,7 +633,7 @@ func (c *Client4) DoUploadFile(url string, data []byte, contentType string) (*Fi } func (c *Client4) doUploadFile(url string, body io.Reader, contentType string, contentLength int64) (*FileUploadResponse, *Response, error) { - rq, err := http.NewRequest("POST", c.ApiUrl+url, body) + rq, err := http.NewRequest("POST", c.APIURL+url, body) if err != nil { return nil, nil, err } @@ -660,7 +660,7 @@ func (c *Client4) doUploadFile(url string, body io.Reader, contentType string, c } func (c *Client4) DoEmojiUploadFile(url string, data []byte, contentType string) (*Emoji, *Response, error) { - rq, err := http.NewRequest("POST", c.ApiUrl+url, bytes.NewReader(data)) + rq, err := http.NewRequest("POST", c.APIURL+url, bytes.NewReader(data)) if err != nil { return nil, nil, err } @@ -684,7 +684,7 @@ func (c *Client4) DoEmojiUploadFile(url string, data []byte, contentType string) } func (c *Client4) DoUploadImportTeam(url string, data []byte, contentType string) (map[string]string, *Response, error) { - rq, err := http.NewRequest("POST", c.ApiUrl+url, bytes.NewReader(data)) + rq, err := http.NewRequest("POST", c.APIURL+url, bytes.NewReader(data)) if err != nil { return nil, nil, err } @@ -756,7 +756,7 @@ func (c *Client4) LoginWithMFA(loginId, password, mfaToken string) (*User, *Resp } func (c *Client4) login(m map[string]string) (*User, *Response, error) { - r, err := c.DoApiPost("/users/login", MapToJson(m)) + r, err := c.DoAPIPost("/users/login", MapToJson(m)) if err != nil { return nil, BuildResponse(r), err } @@ -768,7 +768,7 @@ func (c *Client4) login(m map[string]string) (*User, *Response, error) { // Logout terminates the current user's session. func (c *Client4) Logout() (*Response, error) { - r, err := c.DoApiPost("/users/logout", "") + r, err := c.DoAPIPost("/users/logout", "") if err != nil { return BuildResponse(r), err } @@ -784,7 +784,7 @@ func (c *Client4) SwitchAccountType(switchRequest *SwitchRequest) (string, *Resp if err != nil { return "", BuildResponse(nil), NewAppError("SwitchAccountType", "api.marshal_error", nil, err.Error(), http.StatusInternalServerError) } - r, err := c.doApiPostBytes(c.usersRoute()+"/login/switch", buf) + r, err := c.DoAPIPostBytes(c.usersRoute()+"/login/switch", buf) if err != nil { return "", BuildResponse(r), err } @@ -796,7 +796,7 @@ func (c *Client4) SwitchAccountType(switchRequest *SwitchRequest) (string, *Resp // CreateUser creates a user in the system based on the provided user struct. func (c *Client4) CreateUser(user *User) (*User, *Response, error) { - r, err := c.DoApiPost(c.usersRoute(), user.ToJson()) + r, err := c.DoAPIPost(c.usersRoute(), user.ToJson()) if err != nil { return nil, BuildResponse(r), err } @@ -815,7 +815,7 @@ func (c *Client4) CreateUserWithToken(user *User, tokenId string) (*User, *Respo if err != nil { return nil, nil, NewAppError("CreateUserWithToken", "api.marshal_error", nil, err.Error(), http.StatusInternalServerError) } - r, err := c.doApiPostBytes(c.usersRoute()+query, buf) + r, err := c.DoAPIPostBytes(c.usersRoute()+query, buf) if err != nil { return nil, BuildResponse(r), err } @@ -835,7 +835,7 @@ func (c *Client4) CreateUserWithInviteId(user *User, inviteId string) (*User, *R if err != nil { return nil, nil, NewAppError("CreateUserWithInviteId", "api.marshal_error", nil, err.Error(), http.StatusInternalServerError) } - r, err := c.doApiPostBytes(c.usersRoute()+query, buf) + r, err := c.DoAPIPostBytes(c.usersRoute()+query, buf) if err != nil { return nil, BuildResponse(r), err } @@ -846,7 +846,7 @@ func (c *Client4) CreateUserWithInviteId(user *User, inviteId string) (*User, *R // GetMe returns the logged in user. func (c *Client4) GetMe(etag string) (*User, *Response, error) { - r, err := c.DoApiGet(c.userRoute(Me), etag) + r, err := c.DoAPIGet(c.userRoute(Me), etag) if err != nil { return nil, BuildResponse(r), err } @@ -856,7 +856,7 @@ func (c *Client4) GetMe(etag string) (*User, *Response, error) { // GetUser returns a user based on the provided user id string. func (c *Client4) GetUser(userId, etag string) (*User, *Response, error) { - r, err := c.DoApiGet(c.userRoute(userId), etag) + r, err := c.DoAPIGet(c.userRoute(userId), etag) if err != nil { return nil, BuildResponse(r), err } @@ -866,7 +866,7 @@ func (c *Client4) GetUser(userId, etag string) (*User, *Response, error) { // GetUserByUsername returns a user based on the provided user name string. func (c *Client4) GetUserByUsername(userName, etag string) (*User, *Response, error) { - r, err := c.DoApiGet(c.userByUsernameRoute(userName), etag) + r, err := c.DoAPIGet(c.userByUsernameRoute(userName), etag) if err != nil { return nil, BuildResponse(r), err } @@ -876,7 +876,7 @@ func (c *Client4) GetUserByUsername(userName, etag string) (*User, *Response, er // GetUserByEmail returns a user based on the provided user email string. func (c *Client4) GetUserByEmail(email, etag string) (*User, *Response, error) { - r, err := c.DoApiGet(c.userByEmailRoute(email), etag) + r, err := c.DoAPIGet(c.userByEmailRoute(email), etag) if err != nil { return nil, BuildResponse(r), err } @@ -887,7 +887,7 @@ func (c *Client4) GetUserByEmail(email, etag string) (*User, *Response, error) { // AutocompleteUsersInTeam returns the users on a team based on search term. func (c *Client4) AutocompleteUsersInTeam(teamId string, username string, limit int, etag string) (*UserAutocomplete, *Response, error) { query := fmt.Sprintf("?in_team=%v&name=%v&limit=%d", teamId, username, limit) - r, err := c.DoApiGet(c.usersRoute()+"/autocomplete"+query, etag) + r, err := c.DoAPIGet(c.usersRoute()+"/autocomplete"+query, etag) if err != nil { return nil, BuildResponse(r), err } @@ -898,7 +898,7 @@ func (c *Client4) AutocompleteUsersInTeam(teamId string, username string, limit // AutocompleteUsersInChannel returns the users in a channel based on search term. func (c *Client4) AutocompleteUsersInChannel(teamId string, channelId string, username string, limit int, etag string) (*UserAutocomplete, *Response, error) { query := fmt.Sprintf("?in_team=%v&in_channel=%v&name=%v&limit=%d", teamId, channelId, username, limit) - r, err := c.DoApiGet(c.usersRoute()+"/autocomplete"+query, etag) + r, err := c.DoAPIGet(c.usersRoute()+"/autocomplete"+query, etag) if err != nil { return nil, BuildResponse(r), err } @@ -909,7 +909,7 @@ func (c *Client4) AutocompleteUsersInChannel(teamId string, channelId string, us // AutocompleteUsers returns the users in the system based on search term. func (c *Client4) AutocompleteUsers(username string, limit int, etag string) (*UserAutocomplete, *Response, error) { query := fmt.Sprintf("?name=%v&limit=%d", username, limit) - r, err := c.DoApiGet(c.usersRoute()+"/autocomplete"+query, etag) + r, err := c.DoAPIGet(c.usersRoute()+"/autocomplete"+query, etag) if err != nil { return nil, BuildResponse(r), err } @@ -919,7 +919,7 @@ func (c *Client4) AutocompleteUsers(username string, limit int, etag string) (*U // GetDefaultProfileImage gets the default user's profile image. Must be logged in. func (c *Client4) GetDefaultProfileImage(userId string) ([]byte, *Response, error) { - r, err := c.DoApiGet(c.userRoute(userId)+"/image/default", "") + r, err := c.DoAPIGet(c.userRoute(userId)+"/image/default", "") if err != nil { return nil, BuildResponse(r), err } @@ -935,7 +935,7 @@ func (c *Client4) GetDefaultProfileImage(userId string) ([]byte, *Response, erro // GetProfileImage gets user's profile image. Must be logged in. func (c *Client4) GetProfileImage(userId, etag string) ([]byte, *Response, error) { - r, err := c.DoApiGet(c.userRoute(userId)+"/image", etag) + r, err := c.DoAPIGet(c.userRoute(userId)+"/image", etag) if err != nil { return nil, BuildResponse(r), err } @@ -951,7 +951,7 @@ func (c *Client4) GetProfileImage(userId, etag string) ([]byte, *Response, error // GetUsers returns a page of users on the system. Page counting starts at 0. func (c *Client4) GetUsers(page int, perPage int, etag string) ([]*User, *Response, error) { query := fmt.Sprintf("?page=%v&per_page=%v", page, perPage) - r, err := c.DoApiGet(c.usersRoute()+query, etag) + r, err := c.DoAPIGet(c.usersRoute()+query, etag) if err != nil { return nil, BuildResponse(r), err } @@ -962,7 +962,7 @@ func (c *Client4) GetUsers(page int, perPage int, etag string) ([]*User, *Respon // GetUsersInTeam returns a page of users on a team. Page counting starts at 0. func (c *Client4) GetUsersInTeam(teamId string, page int, perPage int, etag string) ([]*User, *Response, error) { query := fmt.Sprintf("?in_team=%v&page=%v&per_page=%v", teamId, page, perPage) - r, err := c.DoApiGet(c.usersRoute()+query, etag) + r, err := c.DoAPIGet(c.usersRoute()+query, etag) if err != nil { return nil, BuildResponse(r), err } @@ -973,7 +973,7 @@ func (c *Client4) GetUsersInTeam(teamId string, page int, perPage int, etag stri // GetNewUsersInTeam returns a page of users on a team. Page counting starts at 0. func (c *Client4) GetNewUsersInTeam(teamId string, page int, perPage int, etag string) ([]*User, *Response, error) { query := fmt.Sprintf("?sort=create_at&in_team=%v&page=%v&per_page=%v", teamId, page, perPage) - r, err := c.DoApiGet(c.usersRoute()+query, etag) + r, err := c.DoAPIGet(c.usersRoute()+query, etag) if err != nil { return nil, BuildResponse(r), err } @@ -984,7 +984,7 @@ func (c *Client4) GetNewUsersInTeam(teamId string, page int, perPage int, etag s // GetRecentlyActiveUsersInTeam returns a page of users on a team. Page counting starts at 0. func (c *Client4) GetRecentlyActiveUsersInTeam(teamId string, page int, perPage int, etag string) ([]*User, *Response, error) { query := fmt.Sprintf("?sort=last_activity_at&in_team=%v&page=%v&per_page=%v", teamId, page, perPage) - r, err := c.DoApiGet(c.usersRoute()+query, etag) + r, err := c.DoAPIGet(c.usersRoute()+query, etag) if err != nil { return nil, BuildResponse(r), err } @@ -995,7 +995,7 @@ func (c *Client4) GetRecentlyActiveUsersInTeam(teamId string, page int, perPage // GetActiveUsersInTeam returns a page of users on a team. Page counting starts at 0. func (c *Client4) GetActiveUsersInTeam(teamId string, page int, perPage int, etag string) ([]*User, *Response, error) { query := fmt.Sprintf("?active=true&in_team=%v&page=%v&per_page=%v", teamId, page, perPage) - r, err := c.DoApiGet(c.usersRoute()+query, etag) + r, err := c.DoAPIGet(c.usersRoute()+query, etag) if err != nil { return nil, BuildResponse(r), err } @@ -1006,7 +1006,7 @@ func (c *Client4) GetActiveUsersInTeam(teamId string, page int, perPage int, eta // GetUsersNotInTeam returns a page of users who are not in a team. Page counting starts at 0. func (c *Client4) GetUsersNotInTeam(teamId string, page int, perPage int, etag string) ([]*User, *Response, error) { query := fmt.Sprintf("?not_in_team=%v&page=%v&per_page=%v", teamId, page, perPage) - r, err := c.DoApiGet(c.usersRoute()+query, etag) + r, err := c.DoAPIGet(c.usersRoute()+query, etag) if err != nil { return nil, BuildResponse(r), err } @@ -1017,7 +1017,7 @@ func (c *Client4) GetUsersNotInTeam(teamId string, page int, perPage int, etag s // GetUsersInChannel returns a page of users in a channel. Page counting starts at 0. func (c *Client4) GetUsersInChannel(channelId string, page int, perPage int, etag string) ([]*User, *Response, error) { query := fmt.Sprintf("?in_channel=%v&page=%v&per_page=%v", channelId, page, perPage) - r, err := c.DoApiGet(c.usersRoute()+query, etag) + r, err := c.DoAPIGet(c.usersRoute()+query, etag) if err != nil { return nil, BuildResponse(r), err } @@ -1028,7 +1028,7 @@ func (c *Client4) GetUsersInChannel(channelId string, page int, perPage int, eta // GetUsersInChannelByStatus returns a page of users in a channel. Page counting starts at 0. Sorted by Status func (c *Client4) GetUsersInChannelByStatus(channelId string, page int, perPage int, etag string) ([]*User, *Response, error) { query := fmt.Sprintf("?in_channel=%v&page=%v&per_page=%v&sort=status", channelId, page, perPage) - r, err := c.DoApiGet(c.usersRoute()+query, etag) + r, err := c.DoAPIGet(c.usersRoute()+query, etag) if err != nil { return nil, BuildResponse(r), err } @@ -1039,7 +1039,7 @@ func (c *Client4) GetUsersInChannelByStatus(channelId string, page int, perPage // GetUsersNotInChannel returns a page of users not in a channel. Page counting starts at 0. func (c *Client4) GetUsersNotInChannel(teamId, channelId string, page int, perPage int, etag string) ([]*User, *Response, error) { query := fmt.Sprintf("?in_team=%v¬_in_channel=%v&page=%v&per_page=%v", teamId, channelId, page, perPage) - r, err := c.DoApiGet(c.usersRoute()+query, etag) + r, err := c.DoAPIGet(c.usersRoute()+query, etag) if err != nil { return nil, BuildResponse(r), err } @@ -1050,7 +1050,7 @@ func (c *Client4) GetUsersNotInChannel(teamId, channelId string, page int, perPa // GetUsersWithoutTeam returns a page of users on the system that aren't on any teams. Page counting starts at 0. func (c *Client4) GetUsersWithoutTeam(page int, perPage int, etag string) ([]*User, *Response, error) { query := fmt.Sprintf("?without_team=1&page=%v&per_page=%v", page, perPage) - r, err := c.DoApiGet(c.usersRoute()+query, etag) + r, err := c.DoAPIGet(c.usersRoute()+query, etag) if err != nil { return nil, BuildResponse(r), err } @@ -1061,7 +1061,7 @@ func (c *Client4) GetUsersWithoutTeam(page int, perPage int, etag string) ([]*Us // GetUsersInGroup returns a page of users in a group. Page counting starts at 0. func (c *Client4) GetUsersInGroup(groupID string, page int, perPage int, etag string) ([]*User, *Response, error) { query := fmt.Sprintf("?in_group=%v&page=%v&per_page=%v", groupID, page, perPage) - r, err := c.DoApiGet(c.usersRoute()+query, etag) + r, err := c.DoAPIGet(c.usersRoute()+query, etag) if err != nil { return nil, BuildResponse(r), err } @@ -1071,7 +1071,7 @@ func (c *Client4) GetUsersInGroup(groupID string, page int, perPage int, etag st // GetUsersByIds returns a list of users based on the provided user ids. func (c *Client4) GetUsersByIds(userIds []string) ([]*User, *Response, error) { - r, err := c.DoApiPost(c.usersRoute()+"/ids", ArrayToJson(userIds)) + r, err := c.DoAPIPost(c.usersRoute()+"/ids", ArrayToJson(userIds)) if err != nil { return nil, BuildResponse(r), err } @@ -1091,7 +1091,7 @@ func (c *Client4) GetUsersByIdsWithOptions(userIds []string, options *UserGetByI url += "?" + v.Encode() } - r, err := c.DoApiPost(url, ArrayToJson(userIds)) + r, err := c.DoAPIPost(url, ArrayToJson(userIds)) if err != nil { return nil, BuildResponse(r), err } @@ -1101,7 +1101,7 @@ func (c *Client4) GetUsersByIdsWithOptions(userIds []string, options *UserGetByI // GetUsersByUsernames returns a list of users based on the provided usernames. func (c *Client4) GetUsersByUsernames(usernames []string) ([]*User, *Response, error) { - r, err := c.DoApiPost(c.usersRoute()+"/usernames", ArrayToJson(usernames)) + r, err := c.DoAPIPost(c.usersRoute()+"/usernames", ArrayToJson(usernames)) if err != nil { return nil, BuildResponse(r), err } @@ -1112,7 +1112,7 @@ func (c *Client4) GetUsersByUsernames(usernames []string) ([]*User, *Response, e // GetUsersByGroupChannelIds returns a map with channel ids as keys // and a list of users as values based on the provided user ids. func (c *Client4) GetUsersByGroupChannelIds(groupChannelIds []string) (map[string][]*User, *Response, error) { - r, err := c.DoApiPost(c.usersRoute()+"/group_channels", ArrayToJson(groupChannelIds)) + r, err := c.DoAPIPost(c.usersRoute()+"/group_channels", ArrayToJson(groupChannelIds)) if err != nil { return nil, BuildResponse(r), err } @@ -1129,7 +1129,7 @@ func (c *Client4) SearchUsers(search *UserSearch) ([]*User, *Response, error) { if err != nil { return nil, nil, NewAppError("SearchUsers", "api.marshal_error", nil, err.Error(), http.StatusInternalServerError) } - r, err := c.doApiPostBytes(c.usersRoute()+"/search", buf) + r, err := c.DoAPIPostBytes(c.usersRoute()+"/search", buf) if err != nil { return nil, BuildResponse(r), err } @@ -1143,7 +1143,7 @@ func (c *Client4) UpdateUser(user *User) (*User, *Response, error) { if err != nil { return nil, nil, NewAppError("UpdateUser", "api.marshal_error", nil, err.Error(), http.StatusInternalServerError) } - r, err := c.doApiPutBytes(c.userRoute(user.Id), buf) + r, err := c.DoAPIPutBytes(c.userRoute(user.Id), buf) if err != nil { return nil, BuildResponse(r), err } @@ -1157,7 +1157,7 @@ func (c *Client4) PatchUser(userId string, patch *UserPatch) (*User, *Response, if err != nil { return nil, nil, NewAppError("PatchUser", "api.marshal_error", nil, err.Error(), http.StatusInternalServerError) } - r, err := c.doApiPutBytes(c.userRoute(userId)+"/patch", buf) + r, err := c.DoAPIPutBytes(c.userRoute(userId)+"/patch", buf) if err != nil { return nil, BuildResponse(r), err } @@ -1171,7 +1171,7 @@ func (c *Client4) UpdateUserAuth(userId string, userAuth *UserAuth) (*UserAuth, if err != nil { return nil, nil, NewAppError("UpdateUserAuth", "api.marshal_error", nil, err.Error(), http.StatusInternalServerError) } - r, err := c.doApiPutBytes(c.userRoute(userId)+"/auth", buf) + r, err := c.DoAPIPutBytes(c.userRoute(userId)+"/auth", buf) if err != nil { return nil, BuildResponse(r), err } @@ -1187,7 +1187,7 @@ func (c *Client4) UpdateUserMfa(userId, code string, activate bool) (*Response, requestBody["activate"] = activate requestBody["code"] = code - r, err := c.DoApiPut(c.userRoute(userId)+"/mfa", StringInterfaceToJson(requestBody)) + r, err := c.DoAPIPut(c.userRoute(userId)+"/mfa", StringInterfaceToJson(requestBody)) if err != nil { return BuildResponse(r), err } @@ -1198,7 +1198,7 @@ func (c *Client4) UpdateUserMfa(userId, code string, activate bool) (*Response, // GenerateMfaSecret will generate a new MFA secret for a user and return it as a string and // as a base64 encoded image QR code. func (c *Client4) GenerateMfaSecret(userId string) (*MfaSecret, *Response, error) { - r, err := c.DoApiPost(c.userRoute(userId)+"/mfa/generate", "") + r, err := c.DoAPIPost(c.userRoute(userId)+"/mfa/generate", "") if err != nil { return nil, BuildResponse(r), err } @@ -1209,7 +1209,7 @@ func (c *Client4) GenerateMfaSecret(userId string) (*MfaSecret, *Response, error // UpdateUserPassword updates a user's password. Must be logged in as the user or be a system administrator. func (c *Client4) UpdateUserPassword(userId, currentPassword, newPassword string) (*Response, error) { requestBody := map[string]string{"current_password": currentPassword, "new_password": newPassword} - r, err := c.DoApiPut(c.userRoute(userId)+"/password", MapToJson(requestBody)) + r, err := c.DoAPIPut(c.userRoute(userId)+"/password", MapToJson(requestBody)) if err != nil { return BuildResponse(r), err } @@ -1220,7 +1220,7 @@ func (c *Client4) UpdateUserPassword(userId, currentPassword, newPassword string // UpdateUserHashedPassword updates a user's password with an already-hashed password. Must be a system administrator. func (c *Client4) UpdateUserHashedPassword(userId, newHashedPassword string) (*Response, error) { requestBody := map[string]string{"already_hashed": "true", "new_password": newHashedPassword} - r, err := c.DoApiPut(c.userRoute(userId)+"/password", MapToJson(requestBody)) + r, err := c.DoAPIPut(c.userRoute(userId)+"/password", MapToJson(requestBody)) if err != nil { return BuildResponse(r), err } @@ -1230,7 +1230,7 @@ func (c *Client4) UpdateUserHashedPassword(userId, newHashedPassword string) (*R // PromoteGuestToUser convert a guest into a regular user func (c *Client4) PromoteGuestToUser(guestId string) (*Response, error) { - r, err := c.DoApiPost(c.userRoute(guestId)+"/promote", "") + r, err := c.DoAPIPost(c.userRoute(guestId)+"/promote", "") if err != nil { return BuildResponse(r), err } @@ -1240,7 +1240,7 @@ func (c *Client4) PromoteGuestToUser(guestId string) (*Response, error) { // DemoteUserToGuest convert a regular user into a guest func (c *Client4) DemoteUserToGuest(guestId string) (*Response, error) { - r, err := c.DoApiPost(c.userRoute(guestId)+"/demote", "") + r, err := c.DoAPIPost(c.userRoute(guestId)+"/demote", "") if err != nil { return BuildResponse(r), err } @@ -1251,7 +1251,7 @@ func (c *Client4) DemoteUserToGuest(guestId string) (*Response, error) { // UpdateUserRoles updates a user's roles in the system. A user can have "system_user" and "system_admin" roles. func (c *Client4) UpdateUserRoles(userId, roles string) (*Response, error) { requestBody := map[string]string{"roles": roles} - r, err := c.DoApiPut(c.userRoute(userId)+"/roles", MapToJson(requestBody)) + r, err := c.DoAPIPut(c.userRoute(userId)+"/roles", MapToJson(requestBody)) if err != nil { return BuildResponse(r), err } @@ -1263,7 +1263,7 @@ func (c *Client4) UpdateUserRoles(userId, roles string) (*Response, error) { func (c *Client4) UpdateUserActive(userId string, active bool) (*Response, error) { requestBody := make(map[string]interface{}) requestBody["active"] = active - r, err := c.DoApiPut(c.userRoute(userId)+"/active", StringInterfaceToJson(requestBody)) + r, err := c.DoAPIPut(c.userRoute(userId)+"/active", StringInterfaceToJson(requestBody)) if err != nil { return BuildResponse(r), err } @@ -1274,7 +1274,7 @@ func (c *Client4) UpdateUserActive(userId string, active bool) (*Response, error // DeleteUser deactivates a user in the system based on the provided user id string. func (c *Client4) DeleteUser(userId string) (*Response, error) { - r, err := c.DoApiDelete(c.userRoute(userId)) + r, err := c.DoAPIDelete(c.userRoute(userId)) if err != nil { return BuildResponse(r), err } @@ -1284,7 +1284,7 @@ func (c *Client4) DeleteUser(userId string) (*Response, error) { // PermanentDeleteUser deletes a user in the system based on the provided user id string. func (c *Client4) PermanentDeleteUser(userId string) (*Response, error) { - r, err := c.DoApiDelete(c.userRoute(userId) + "?permanent=" + c.boolString(true)) + r, err := c.DoAPIDelete(c.userRoute(userId) + "?permanent=" + c.boolString(true)) if err != nil { return BuildResponse(r), err } @@ -1294,7 +1294,7 @@ func (c *Client4) PermanentDeleteUser(userId string) (*Response, error) { // ConvertUserToBot converts a user to a bot user. func (c *Client4) ConvertUserToBot(userId string) (*Bot, *Response, error) { - r, err := c.DoApiPost(c.userRoute(userId)+"/convert_to_bot", "") + r, err := c.DoAPIPost(c.userRoute(userId)+"/convert_to_bot", "") if err != nil { return nil, BuildResponse(r), err } @@ -1317,7 +1317,7 @@ func (c *Client4) ConvertBotToUser(userId string, userPatch *UserPatch, setSyste if err != nil { return nil, nil, NewAppError("ConvertBotToUser", "api.marshal_error", nil, err.Error(), http.StatusInternalServerError) } - r, err := c.doApiPostBytes(c.botRoute(userId)+"/convert_to_user"+query, buf) + r, err := c.DoAPIPostBytes(c.botRoute(userId)+"/convert_to_user"+query, buf) if err != nil { return nil, BuildResponse(r), err } @@ -1327,7 +1327,7 @@ func (c *Client4) ConvertBotToUser(userId string, userPatch *UserPatch, setSyste // PermanentDeleteAll permanently deletes all users in the system. This is a local only endpoint func (c *Client4) PermanentDeleteAllUsers() (*Response, error) { - r, err := c.DoApiDelete(c.usersRoute()) + r, err := c.DoAPIDelete(c.usersRoute()) if err != nil { return BuildResponse(r), err } @@ -1339,7 +1339,7 @@ func (c *Client4) PermanentDeleteAllUsers() (*Response, error) { // provided email. func (c *Client4) SendPasswordResetEmail(email string) (*Response, error) { requestBody := map[string]string{"email": email} - r, err := c.DoApiPost(c.usersRoute()+"/password/reset/send", MapToJson(requestBody)) + r, err := c.DoAPIPost(c.usersRoute()+"/password/reset/send", MapToJson(requestBody)) if err != nil { return BuildResponse(r), err } @@ -1350,7 +1350,7 @@ func (c *Client4) SendPasswordResetEmail(email string) (*Response, error) { // ResetPassword uses a recovery code to update reset a user's password. func (c *Client4) ResetPassword(token, newPassword string) (*Response, error) { requestBody := map[string]string{"token": token, "new_password": newPassword} - r, err := c.DoApiPost(c.usersRoute()+"/password/reset", MapToJson(requestBody)) + r, err := c.DoAPIPost(c.usersRoute()+"/password/reset", MapToJson(requestBody)) if err != nil { return BuildResponse(r), err } @@ -1360,7 +1360,7 @@ func (c *Client4) ResetPassword(token, newPassword string) (*Response, error) { // GetSessions returns a list of sessions based on the provided user id string. func (c *Client4) GetSessions(userId, etag string) ([]*Session, *Response, error) { - r, err := c.DoApiGet(c.userRoute(userId)+"/sessions", etag) + r, err := c.DoAPIGet(c.userRoute(userId)+"/sessions", etag) if err != nil { return nil, BuildResponse(r), err } @@ -1371,7 +1371,7 @@ func (c *Client4) GetSessions(userId, etag string) ([]*Session, *Response, error // RevokeSession revokes a user session based on the provided user id and session id strings. func (c *Client4) RevokeSession(userId, sessionId string) (*Response, error) { requestBody := map[string]string{"session_id": sessionId} - r, err := c.DoApiPost(c.userRoute(userId)+"/sessions/revoke", MapToJson(requestBody)) + r, err := c.DoAPIPost(c.userRoute(userId)+"/sessions/revoke", MapToJson(requestBody)) if err != nil { return BuildResponse(r), err } @@ -1381,7 +1381,7 @@ func (c *Client4) RevokeSession(userId, sessionId string) (*Response, error) { // RevokeAllSessions revokes all sessions for the provided user id string. func (c *Client4) RevokeAllSessions(userId string) (*Response, error) { - r, err := c.DoApiPost(c.userRoute(userId)+"/sessions/revoke/all", "") + r, err := c.DoAPIPost(c.userRoute(userId)+"/sessions/revoke/all", "") if err != nil { return BuildResponse(r), err } @@ -1391,7 +1391,7 @@ func (c *Client4) RevokeAllSessions(userId string) (*Response, error) { // RevokeAllSessions revokes all sessions for all the users. func (c *Client4) RevokeSessionsFromAllUsers() (*Response, error) { - r, err := c.DoApiPost(c.usersRoute()+"/sessions/revoke/all", "") + r, err := c.DoAPIPost(c.usersRoute()+"/sessions/revoke/all", "") if err != nil { return BuildResponse(r), err } @@ -1402,7 +1402,7 @@ func (c *Client4) RevokeSessionsFromAllUsers() (*Response, error) { // AttachDeviceId attaches a mobile device ID to the current session. func (c *Client4) AttachDeviceId(deviceId string) (*Response, error) { requestBody := map[string]string{"device_id": deviceId} - r, err := c.DoApiPut(c.usersRoute()+"/sessions/device", MapToJson(requestBody)) + r, err := c.DoAPIPut(c.usersRoute()+"/sessions/device", MapToJson(requestBody)) if err != nil { return BuildResponse(r), err } @@ -1425,7 +1425,7 @@ func (c *Client4) GetTeamsUnreadForUser(userId, teamIdToExclude string, includeC query.Set("include_collapsed_threads", "true") } - r, err := c.DoApiGet(c.userRoute(userId)+"/teams/unread?"+query.Encode(), "") + r, err := c.DoAPIGet(c.userRoute(userId)+"/teams/unread?"+query.Encode(), "") if err != nil { return nil, BuildResponse(r), err } @@ -1436,7 +1436,7 @@ func (c *Client4) GetTeamsUnreadForUser(userId, teamIdToExclude string, includeC // GetUserAudits returns a list of audit based on the provided user id string. func (c *Client4) GetUserAudits(userId string, page int, perPage int, etag string) (Audits, *Response, error) { query := fmt.Sprintf("?page=%v&per_page=%v", page, perPage) - r, err := c.DoApiGet(c.userRoute(userId)+"/audits"+query, etag) + r, err := c.DoAPIGet(c.userRoute(userId)+"/audits"+query, etag) if err != nil { return nil, BuildResponse(r), err } @@ -1453,7 +1453,7 @@ func (c *Client4) GetUserAudits(userId string, page int, perPage int, etag strin // VerifyUserEmail will verify a user's email using the supplied token. func (c *Client4) VerifyUserEmail(token string) (*Response, error) { requestBody := map[string]string{"token": token} - r, err := c.DoApiPost(c.usersRoute()+"/email/verify", MapToJson(requestBody)) + r, err := c.DoAPIPost(c.usersRoute()+"/email/verify", MapToJson(requestBody)) if err != nil { return BuildResponse(r), err } @@ -1463,7 +1463,7 @@ func (c *Client4) VerifyUserEmail(token string) (*Response, error) { // VerifyUserEmailWithoutToken will verify a user's email by its Id. (Requires manage system role) func (c *Client4) VerifyUserEmailWithoutToken(userId string) (*User, *Response, error) { - r, err := c.DoApiPost(c.userRoute(userId)+"/email/verify/member", "") + r, err := c.DoAPIPost(c.userRoute(userId)+"/email/verify/member", "") if err != nil { return nil, BuildResponse(r), err } @@ -1476,7 +1476,7 @@ func (c *Client4) VerifyUserEmailWithoutToken(userId string) (*User, *Response, // email address. func (c *Client4) SendVerificationEmail(email string) (*Response, error) { requestBody := map[string]string{"email": email} - r, err := c.DoApiPost(c.usersRoute()+"/email/verify/send", MapToJson(requestBody)) + r, err := c.DoAPIPost(c.usersRoute()+"/email/verify/send", MapToJson(requestBody)) if err != nil { return BuildResponse(r), err } @@ -1486,7 +1486,7 @@ func (c *Client4) SendVerificationEmail(email string) (*Response, error) { // SetDefaultProfileImage resets the profile image to a default generated one. func (c *Client4) SetDefaultProfileImage(userId string) (*Response, error) { - r, err := c.DoApiDelete(c.userRoute(userId) + "/image") + r, err := c.DoAPIDelete(c.userRoute(userId) + "/image") if err != nil { return BuildResponse(r), err } @@ -1511,7 +1511,7 @@ func (c *Client4) SetProfileImage(userId string, data []byte) (*Response, error) return nil, NewAppError("SetProfileImage", "model.client.set_profile_user.writer.app_error", nil, err.Error(), http.StatusBadRequest) } - rq, err := http.NewRequest("POST", c.ApiUrl+c.userRoute(userId)+"/image", bytes.NewReader(body.Bytes())) + rq, err := http.NewRequest("POST", c.APIURL+c.userRoute(userId)+"/image", bytes.NewReader(body.Bytes())) if err != nil { return nil, err } @@ -1540,7 +1540,7 @@ func (c *Client4) SetProfileImage(userId string, data []byte) (*Response, error) // permission. A non-blank description is required. func (c *Client4) CreateUserAccessToken(userId, description string) (*UserAccessToken, *Response, error) { requestBody := map[string]string{"description": description} - r, err := c.DoApiPost(c.userRoute(userId)+"/tokens", MapToJson(requestBody)) + r, err := c.DoAPIPost(c.userRoute(userId)+"/tokens", MapToJson(requestBody)) if err != nil { return nil, BuildResponse(r), err } @@ -1553,7 +1553,7 @@ func (c *Client4) CreateUserAccessToken(userId, description string) (*UserAccess // the 'manage_system' permission. func (c *Client4) GetUserAccessTokens(page int, perPage int) ([]*UserAccessToken, *Response, error) { query := fmt.Sprintf("?page=%v&per_page=%v", page, perPage) - r, err := c.DoApiGet(c.userAccessTokensRoute()+query, "") + r, err := c.DoAPIGet(c.userAccessTokensRoute()+query, "") if err != nil { return nil, BuildResponse(r), err } @@ -1566,7 +1566,7 @@ func (c *Client4) GetUserAccessTokens(page int, perPage int) ([]*UserAccessToken // Must have the 'read_user_access_token' permission and if getting for another // user, must have the 'edit_other_users' permission. func (c *Client4) GetUserAccessToken(tokenId string) (*UserAccessToken, *Response, error) { - r, err := c.DoApiGet(c.userAccessTokenRoute(tokenId), "") + r, err := c.DoAPIGet(c.userAccessTokenRoute(tokenId), "") if err != nil { return nil, BuildResponse(r), err } @@ -1580,7 +1580,7 @@ func (c *Client4) GetUserAccessToken(tokenId string) (*UserAccessToken, *Respons // 'edit_other_users' permission. func (c *Client4) GetUserAccessTokensForUser(userId string, page, perPage int) ([]*UserAccessToken, *Response, error) { query := fmt.Sprintf("?page=%v&per_page=%v", page, perPage) - r, err := c.DoApiGet(c.userRoute(userId)+"/tokens"+query, "") + r, err := c.DoAPIGet(c.userRoute(userId)+"/tokens"+query, "") if err != nil { return nil, BuildResponse(r), err } @@ -1593,7 +1593,7 @@ func (c *Client4) GetUserAccessTokensForUser(userId string, page, perPage int) ( // 'edit_other_users' permission. func (c *Client4) RevokeUserAccessToken(tokenId string) (*Response, error) { requestBody := map[string]string{"token_id": tokenId} - r, err := c.DoApiPost(c.usersRoute()+"/tokens/revoke", MapToJson(requestBody)) + r, err := c.DoAPIPost(c.usersRoute()+"/tokens/revoke", MapToJson(requestBody)) if err != nil { return BuildResponse(r), err } @@ -1607,7 +1607,7 @@ func (c *Client4) SearchUserAccessTokens(search *UserAccessTokenSearch) ([]*User if err != nil { return nil, nil, NewAppError("SearchUserAccessTokens", "api.marshal_error", nil, err.Error(), http.StatusInternalServerError) } - r, err := c.doApiPostBytes(c.usersRoute()+"/tokens/search", buf) + r, err := c.DoAPIPostBytes(c.usersRoute()+"/tokens/search", buf) if err != nil { return nil, BuildResponse(r), err } @@ -1620,7 +1620,7 @@ func (c *Client4) SearchUserAccessTokens(search *UserAccessTokenSearch) ([]*User // 'edit_other_users' permission. func (c *Client4) DisableUserAccessToken(tokenId string) (*Response, error) { requestBody := map[string]string{"token_id": tokenId} - r, err := c.DoApiPost(c.usersRoute()+"/tokens/disable", MapToJson(requestBody)) + r, err := c.DoAPIPost(c.usersRoute()+"/tokens/disable", MapToJson(requestBody)) if err != nil { return BuildResponse(r), err } @@ -1633,7 +1633,7 @@ func (c *Client4) DisableUserAccessToken(tokenId string) (*Response, error) { // 'edit_other_users' permission. func (c *Client4) EnableUserAccessToken(tokenId string) (*Response, error) { requestBody := map[string]string{"token_id": tokenId} - r, err := c.DoApiPost(c.usersRoute()+"/tokens/enable", MapToJson(requestBody)) + r, err := c.DoAPIPost(c.usersRoute()+"/tokens/enable", MapToJson(requestBody)) if err != nil { return BuildResponse(r), err } @@ -1645,7 +1645,7 @@ func (c *Client4) EnableUserAccessToken(tokenId string) (*Response, error) { // CreateBot creates a bot in the system based on the provided bot struct. func (c *Client4) CreateBot(bot *Bot) (*Bot, *Response, error) { - r, err := c.doApiPostBytes(c.botsRoute(), bot.ToJson()) + r, err := c.DoAPIPostBytes(c.botsRoute(), bot.ToJson()) if err != nil { return nil, BuildResponse(r), err } @@ -1662,7 +1662,7 @@ func (c *Client4) CreateBot(bot *Bot) (*Bot, *Response, error) { // PatchBot partially updates a bot. Any missing fields are not updated. func (c *Client4) PatchBot(userId string, patch *BotPatch) (*Bot, *Response, error) { - r, err := c.doApiPutBytes(c.botRoute(userId), patch.ToJson()) + r, err := c.DoAPIPutBytes(c.botRoute(userId), patch.ToJson()) if err != nil { return nil, BuildResponse(r), err } @@ -1679,7 +1679,7 @@ func (c *Client4) PatchBot(userId string, patch *BotPatch) (*Bot, *Response, err // GetBot fetches the given, undeleted bot. func (c *Client4) GetBot(userId string, etag string) (*Bot, *Response, error) { - r, err := c.DoApiGet(c.botRoute(userId), etag) + r, err := c.DoAPIGet(c.botRoute(userId), etag) if err != nil { return nil, BuildResponse(r), err } @@ -1696,7 +1696,7 @@ func (c *Client4) GetBot(userId string, etag string) (*Bot, *Response, error) { // GetBotIncludeDeleted fetches the given bot, even if it is deleted. func (c *Client4) GetBotIncludeDeleted(userId string, etag string) (*Bot, *Response, error) { - r, err := c.DoApiGet(c.botRoute(userId)+"?include_deleted="+c.boolString(true), etag) + r, err := c.DoAPIGet(c.botRoute(userId)+"?include_deleted="+c.boolString(true), etag) if err != nil { return nil, BuildResponse(r), err } @@ -1714,7 +1714,7 @@ func (c *Client4) GetBotIncludeDeleted(userId string, etag string) (*Bot, *Respo // GetBots fetches the given page of bots, excluding deleted. func (c *Client4) GetBots(page, perPage int, etag string) ([]*Bot, *Response, error) { query := fmt.Sprintf("?page=%v&per_page=%v", page, perPage) - r, err := c.DoApiGet(c.botsRoute()+query, etag) + r, err := c.DoAPIGet(c.botsRoute()+query, etag) if err != nil { return nil, BuildResponse(r), err } @@ -1731,7 +1731,7 @@ func (c *Client4) GetBots(page, perPage int, etag string) ([]*Bot, *Response, er // GetBotsIncludeDeleted fetches the given page of bots, including deleted. func (c *Client4) GetBotsIncludeDeleted(page, perPage int, etag string) ([]*Bot, *Response, error) { query := fmt.Sprintf("?page=%v&per_page=%v&include_deleted="+c.boolString(true), page, perPage) - r, err := c.DoApiGet(c.botsRoute()+query, etag) + r, err := c.DoAPIGet(c.botsRoute()+query, etag) if err != nil { return nil, BuildResponse(r), err } @@ -1748,7 +1748,7 @@ func (c *Client4) GetBotsIncludeDeleted(page, perPage int, etag string) ([]*Bot, // GetBotsOrphaned fetches the given page of bots, only including orphanded bots. func (c *Client4) GetBotsOrphaned(page, perPage int, etag string) ([]*Bot, *Response, error) { query := fmt.Sprintf("?page=%v&per_page=%v&only_orphaned="+c.boolString(true), page, perPage) - r, err := c.DoApiGet(c.botsRoute()+query, etag) + r, err := c.DoAPIGet(c.botsRoute()+query, etag) if err != nil { return nil, BuildResponse(r), err } @@ -1764,7 +1764,7 @@ func (c *Client4) GetBotsOrphaned(page, perPage int, etag string) ([]*Bot, *Resp // DisableBot disables the given bot in the system. func (c *Client4) DisableBot(botUserId string) (*Bot, *Response, error) { - r, err := c.doApiPostBytes(c.botRoute(botUserId)+"/disable", nil) + r, err := c.DoAPIPostBytes(c.botRoute(botUserId)+"/disable", nil) if err != nil { return nil, BuildResponse(r), err } @@ -1781,7 +1781,7 @@ func (c *Client4) DisableBot(botUserId string) (*Bot, *Response, error) { // EnableBot disables the given bot in the system. func (c *Client4) EnableBot(botUserId string) (*Bot, *Response, error) { - r, err := c.doApiPostBytes(c.botRoute(botUserId)+"/enable", nil) + r, err := c.DoAPIPostBytes(c.botRoute(botUserId)+"/enable", nil) if err != nil { return nil, BuildResponse(r), err } @@ -1798,7 +1798,7 @@ func (c *Client4) EnableBot(botUserId string) (*Bot, *Response, error) { // AssignBot assigns the given bot to the given user func (c *Client4) AssignBot(botUserId, newOwnerId string) (*Bot, *Response, error) { - r, err := c.doApiPostBytes(c.botRoute(botUserId)+"/assign/"+newOwnerId, nil) + r, err := c.DoAPIPostBytes(c.botRoute(botUserId)+"/assign/"+newOwnerId, nil) if err != nil { return nil, BuildResponse(r), err } @@ -1821,7 +1821,7 @@ func (c *Client4) CreateTeam(team *Team) (*Team, *Response, error) { if err != nil { return nil, nil, NewAppError("CreateTeam", "api.marshal_error", nil, err.Error(), http.StatusInternalServerError) } - r, err := c.doApiPostBytes(c.teamsRoute(), buf) + r, err := c.DoAPIPostBytes(c.teamsRoute(), buf) if err != nil { return nil, BuildResponse(r), err } @@ -1831,7 +1831,7 @@ func (c *Client4) CreateTeam(team *Team) (*Team, *Response, error) { // GetTeam returns a team based on the provided team id string. func (c *Client4) GetTeam(teamId, etag string) (*Team, *Response, error) { - r, err := c.DoApiGet(c.teamRoute(teamId), etag) + r, err := c.DoAPIGet(c.teamRoute(teamId), etag) if err != nil { return nil, BuildResponse(r), err } @@ -1842,7 +1842,7 @@ func (c *Client4) GetTeam(teamId, etag string) (*Team, *Response, error) { // GetAllTeams returns all teams based on permissions. func (c *Client4) GetAllTeams(etag string, page int, perPage int) ([]*Team, *Response, error) { query := fmt.Sprintf("?page=%v&per_page=%v", page, perPage) - r, err := c.DoApiGet(c.teamsRoute()+query, etag) + r, err := c.DoAPIGet(c.teamsRoute()+query, etag) if err != nil { return nil, BuildResponse(r), err } @@ -1853,7 +1853,7 @@ func (c *Client4) GetAllTeams(etag string, page int, perPage int) ([]*Team, *Res // GetAllTeamsWithTotalCount returns all teams based on permissions. func (c *Client4) GetAllTeamsWithTotalCount(etag string, page int, perPage int) ([]*Team, int64, *Response, error) { query := fmt.Sprintf("?page=%v&per_page=%v&include_total_count="+c.boolString(true), page, perPage) - r, err := c.DoApiGet(c.teamsRoute()+query, etag) + r, err := c.DoAPIGet(c.teamsRoute()+query, etag) if err != nil { return nil, 0, BuildResponse(r), err } @@ -1866,7 +1866,7 @@ func (c *Client4) GetAllTeamsWithTotalCount(etag string, page int, perPage int) // Must be a system administrator. func (c *Client4) GetAllTeamsExcludePolicyConstrained(etag string, page int, perPage int) ([]*Team, *Response, error) { query := fmt.Sprintf("?page=%v&per_page=%v&exclude_policy_constrained=%v", page, perPage, true) - r, err := c.DoApiGet(c.teamsRoute()+query, etag) + r, err := c.DoAPIGet(c.teamsRoute()+query, etag) if err != nil { return nil, BuildResponse(r), err } @@ -1876,7 +1876,7 @@ func (c *Client4) GetAllTeamsExcludePolicyConstrained(etag string, page int, per // GetTeamByName returns a team based on the provided team name string. func (c *Client4) GetTeamByName(name, etag string) (*Team, *Response, error) { - r, err := c.DoApiGet(c.teamByNameRoute(name), etag) + r, err := c.DoAPIGet(c.teamByNameRoute(name), etag) if err != nil { return nil, BuildResponse(r), err } @@ -1890,7 +1890,7 @@ func (c *Client4) SearchTeams(search *TeamSearch) ([]*Team, *Response, error) { if err != nil { return nil, nil, NewAppError("SearchTeams", "api.marshal_error", nil, err.Error(), http.StatusInternalServerError) } - r, err := c.doApiPostBytes(c.teamsRoute()+"/search", buf) + r, err := c.DoAPIPostBytes(c.teamsRoute()+"/search", buf) if err != nil { return nil, BuildResponse(r), err } @@ -1910,7 +1910,7 @@ func (c *Client4) SearchTeamsPaged(search *TeamSearch) ([]*Team, int64, *Respons if err != nil { return nil, 0, BuildResponse(nil), NewAppError("SearchTeamsPaged", "api.marshal_error", nil, err.Error(), http.StatusInternalServerError) } - r, err := c.doApiPostBytes(c.teamsRoute()+"/search", buf) + r, err := c.DoAPIPostBytes(c.teamsRoute()+"/search", buf) if err != nil { return nil, 0, BuildResponse(r), err } @@ -1921,7 +1921,7 @@ func (c *Client4) SearchTeamsPaged(search *TeamSearch) ([]*Team, int64, *Respons // TeamExists returns true or false if the team exist or not. func (c *Client4) TeamExists(name, etag string) (bool, *Response, error) { - r, err := c.DoApiGet(c.teamByNameRoute(name)+"/exists", etag) + r, err := c.DoAPIGet(c.teamByNameRoute(name)+"/exists", etag) if err != nil { return false, BuildResponse(r), err } @@ -1932,7 +1932,7 @@ func (c *Client4) TeamExists(name, etag string) (bool, *Response, error) { // GetTeamsForUser returns a list of teams a user is on. Must be logged in as the user // or be a system administrator. func (c *Client4) GetTeamsForUser(userId, etag string) ([]*Team, *Response, error) { - r, err := c.DoApiGet(c.userRoute(userId)+"/teams", etag) + r, err := c.DoAPIGet(c.userRoute(userId)+"/teams", etag) if err != nil { return nil, BuildResponse(r), err } @@ -1942,7 +1942,7 @@ func (c *Client4) GetTeamsForUser(userId, etag string) ([]*Team, *Response, erro // GetTeamMember returns a team member based on the provided team and user id strings. func (c *Client4) GetTeamMember(teamId, userId, etag string) (*TeamMember, *Response, error) { - r, err := c.DoApiGet(c.teamMemberRoute(teamId, userId), etag) + r, err := c.DoAPIGet(c.teamMemberRoute(teamId, userId), etag) if err != nil { return nil, BuildResponse(r), err } @@ -1953,7 +1953,7 @@ func (c *Client4) GetTeamMember(teamId, userId, etag string) (*TeamMember, *Resp // UpdateTeamMemberRoles will update the roles on a team for a user. func (c *Client4) UpdateTeamMemberRoles(teamId, userId, newRoles string) (*Response, error) { requestBody := map[string]string{"roles": newRoles} - r, err := c.DoApiPut(c.teamMemberRoute(teamId, userId)+"/roles", MapToJson(requestBody)) + r, err := c.DoAPIPut(c.teamMemberRoute(teamId, userId)+"/roles", MapToJson(requestBody)) if err != nil { return BuildResponse(r), err } @@ -1967,7 +1967,7 @@ func (c *Client4) UpdateTeamMemberSchemeRoles(teamId string, userId string, sche if err != nil { return nil, NewAppError("UpdateTeamMemberSchemeRoles", "api.marshal_error", nil, err.Error(), http.StatusInternalServerError) } - r, err := c.doApiPutBytes(c.teamMemberRoute(teamId, userId)+"/schemeRoles", buf) + r, err := c.DoAPIPutBytes(c.teamMemberRoute(teamId, userId)+"/schemeRoles", buf) if err != nil { return BuildResponse(r), err } @@ -1981,7 +1981,7 @@ func (c *Client4) UpdateTeam(team *Team) (*Team, *Response, error) { if err != nil { return nil, nil, NewAppError("UpdateTeam", "api.marshal_error", nil, err.Error(), http.StatusInternalServerError) } - r, err := c.doApiPutBytes(c.teamRoute(team.Id), buf) + r, err := c.DoAPIPutBytes(c.teamRoute(team.Id), buf) if err != nil { return nil, BuildResponse(r), err } @@ -1995,7 +1995,7 @@ func (c *Client4) PatchTeam(teamId string, patch *TeamPatch) (*Team, *Response, if err != nil { return nil, nil, NewAppError("PatchTeam", "api.marshal_error", nil, err.Error(), http.StatusInternalServerError) } - r, err := c.doApiPutBytes(c.teamRoute(teamId)+"/patch", buf) + r, err := c.DoAPIPutBytes(c.teamRoute(teamId)+"/patch", buf) if err != nil { return nil, BuildResponse(r), err } @@ -2005,7 +2005,7 @@ func (c *Client4) PatchTeam(teamId string, patch *TeamPatch) (*Team, *Response, // RestoreTeam restores a previously deleted team. func (c *Client4) RestoreTeam(teamId string) (*Team, *Response, error) { - r, err := c.DoApiPost(c.teamRoute(teamId)+"/restore", "") + r, err := c.DoAPIPost(c.teamRoute(teamId)+"/restore", "") if err != nil { return nil, BuildResponse(r), err } @@ -2015,7 +2015,7 @@ func (c *Client4) RestoreTeam(teamId string) (*Team, *Response, error) { // RegenerateTeamInviteId requests a new invite ID to be generated. func (c *Client4) RegenerateTeamInviteId(teamId string) (*Team, *Response, error) { - r, err := c.DoApiPost(c.teamRoute(teamId)+"/regenerate_invite_id", "") + r, err := c.DoAPIPost(c.teamRoute(teamId)+"/regenerate_invite_id", "") if err != nil { return nil, BuildResponse(r), err } @@ -2025,7 +2025,7 @@ func (c *Client4) RegenerateTeamInviteId(teamId string) (*Team, *Response, error // SoftDeleteTeam deletes the team softly (archive only, not permanent delete). func (c *Client4) SoftDeleteTeam(teamId string) (*Response, error) { - r, err := c.DoApiDelete(c.teamRoute(teamId)) + r, err := c.DoAPIDelete(c.teamRoute(teamId)) if err != nil { return BuildResponse(r), err } @@ -2036,7 +2036,7 @@ func (c *Client4) SoftDeleteTeam(teamId string) (*Response, error) { // PermanentDeleteTeam deletes the team, should only be used when needed for // compliance and the like. func (c *Client4) PermanentDeleteTeam(teamId string) (*Response, error) { - r, err := c.DoApiDelete(c.teamRoute(teamId) + "?permanent=" + c.boolString(true)) + r, err := c.DoAPIDelete(c.teamRoute(teamId) + "?permanent=" + c.boolString(true)) if err != nil { return BuildResponse(r), err } @@ -2048,7 +2048,7 @@ func (c *Client4) PermanentDeleteTeam(teamId string) (*Response, error) { // the corresponding AllowOpenInvite appropriately. func (c *Client4) UpdateTeamPrivacy(teamId string, privacy string) (*Team, *Response, error) { requestBody := map[string]string{"privacy": privacy} - r, err := c.DoApiPut(c.teamRoute(teamId)+"/privacy", MapToJson(requestBody)) + r, err := c.DoAPIPut(c.teamRoute(teamId)+"/privacy", MapToJson(requestBody)) if err != nil { return nil, BuildResponse(r), err } @@ -2059,7 +2059,7 @@ func (c *Client4) UpdateTeamPrivacy(teamId string, privacy string) (*Team, *Resp // GetTeamMembers returns team members based on the provided team id string. func (c *Client4) GetTeamMembers(teamId string, page int, perPage int, etag string) ([]*TeamMember, *Response, error) { query := fmt.Sprintf("?page=%v&per_page=%v", page, perPage) - r, err := c.DoApiGet(c.teamMembersRoute(teamId)+query, etag) + r, err := c.DoAPIGet(c.teamMembersRoute(teamId)+query, etag) if err != nil { return nil, BuildResponse(r), err } @@ -2071,7 +2071,7 @@ func (c *Client4) GetTeamMembers(teamId string, page int, perPage int, etag stri // Could not add it to above function due to it be a breaking change. func (c *Client4) GetTeamMembersSortAndWithoutDeletedUsers(teamId string, page int, perPage int, sort string, excludeDeletedUsers bool, etag string) ([]*TeamMember, *Response, error) { query := fmt.Sprintf("?page=%v&per_page=%v&sort=%v&exclude_deleted_users=%v", page, perPage, sort, excludeDeletedUsers) - r, err := c.DoApiGet(c.teamMembersRoute(teamId)+query, etag) + r, err := c.DoAPIGet(c.teamMembersRoute(teamId)+query, etag) if err != nil { return nil, BuildResponse(r), err } @@ -2081,7 +2081,7 @@ func (c *Client4) GetTeamMembersSortAndWithoutDeletedUsers(teamId string, page i // GetTeamMembersForUser returns the team members for a user. func (c *Client4) GetTeamMembersForUser(userId string, etag string) ([]*TeamMember, *Response, error) { - r, err := c.DoApiGet(c.userRoute(userId)+"/teams/members", etag) + r, err := c.DoAPIGet(c.userRoute(userId)+"/teams/members", etag) if err != nil { return nil, BuildResponse(r), err } @@ -2092,7 +2092,7 @@ func (c *Client4) GetTeamMembersForUser(userId string, etag string) ([]*TeamMemb // GetTeamMembersByIds will return an array of team members based on the // team id and a list of user ids provided. Must be authenticated. func (c *Client4) GetTeamMembersByIds(teamId string, userIds []string) ([]*TeamMember, *Response, error) { - r, err := c.DoApiPost(fmt.Sprintf("/teams/%v/members/ids", teamId), ArrayToJson(userIds)) + r, err := c.DoAPIPost(fmt.Sprintf("/teams/%v/members/ids", teamId), ArrayToJson(userIds)) if err != nil { return nil, BuildResponse(r), err } @@ -2107,7 +2107,7 @@ func (c *Client4) AddTeamMember(teamId, userId string) (*TeamMember, *Response, if err != nil { return nil, nil, NewAppError("AddTeamMember", "api.marshal_error", nil, err.Error(), http.StatusInternalServerError) } - r, err := c.doApiPostBytes(c.teamMembersRoute(teamId), buf) + r, err := c.DoAPIPostBytes(c.teamMembersRoute(teamId), buf) if err != nil { return nil, BuildResponse(r), err } @@ -2128,7 +2128,7 @@ func (c *Client4) AddTeamMemberFromInvite(token, inviteId string) (*TeamMember, query += fmt.Sprintf("?token=%v", token) } - r, err := c.DoApiPost(c.teamsRoute()+"/members/invite"+query, "") + r, err := c.DoAPIPost(c.teamsRoute()+"/members/invite"+query, "") if err != nil { return nil, BuildResponse(r), err } @@ -2144,7 +2144,7 @@ func (c *Client4) AddTeamMembers(teamId string, userIds []string) ([]*TeamMember members = append(members, member) } - r, err := c.DoApiPost(c.teamMembersRoute(teamId)+"/batch", TeamMembersToJson(members)) + r, err := c.DoAPIPost(c.teamMembersRoute(teamId)+"/batch", TeamMembersToJson(members)) if err != nil { return nil, BuildResponse(r), err } @@ -2160,7 +2160,7 @@ func (c *Client4) AddTeamMembersGracefully(teamId string, userIds []string) ([]* members = append(members, member) } - r, err := c.DoApiPost(c.teamMembersRoute(teamId)+"/batch?graceful="+c.boolString(true), TeamMembersToJson(members)) + r, err := c.DoAPIPost(c.teamMembersRoute(teamId)+"/batch?graceful="+c.boolString(true), TeamMembersToJson(members)) if err != nil { return nil, BuildResponse(r), err } @@ -2170,7 +2170,7 @@ func (c *Client4) AddTeamMembersGracefully(teamId string, userIds []string) ([]* // RemoveTeamMember will remove a user from a team. func (c *Client4) RemoveTeamMember(teamId, userId string) (*Response, error) { - r, err := c.DoApiDelete(c.teamMemberRoute(teamId, userId)) + r, err := c.DoAPIDelete(c.teamMemberRoute(teamId, userId)) if err != nil { return BuildResponse(r), err } @@ -2181,7 +2181,7 @@ func (c *Client4) RemoveTeamMember(teamId, userId string) (*Response, error) { // GetTeamStats returns a team stats based on the team id string. // Must be authenticated. func (c *Client4) GetTeamStats(teamId, etag string) (*TeamStats, *Response, error) { - r, err := c.DoApiGet(c.teamStatsRoute(teamId), etag) + r, err := c.DoAPIGet(c.teamStatsRoute(teamId), etag) if err != nil { return nil, BuildResponse(r), err } @@ -2192,7 +2192,7 @@ func (c *Client4) GetTeamStats(teamId, etag string) (*TeamStats, *Response, erro // GetTotalUsersStats returns a total system user stats. // Must be authenticated. func (c *Client4) GetTotalUsersStats(etag string) (*UsersStats, *Response, error) { - r, err := c.DoApiGet(c.totalUsersStatsRoute(), etag) + r, err := c.DoAPIGet(c.totalUsersStatsRoute(), etag) if err != nil { return nil, BuildResponse(r), err } @@ -2204,7 +2204,7 @@ func (c *Client4) GetTotalUsersStats(etag string) (*UsersStats, *Response, error // unread messages and mentions the user has for the specified team. // Must be authenticated. func (c *Client4) GetTeamUnread(teamId, userId string) (*TeamUnread, *Response, error) { - r, err := c.DoApiGet(c.userRoute(userId)+c.teamRoute(teamId)+"/unread", "") + r, err := c.DoAPIGet(c.userRoute(userId)+c.teamRoute(teamId)+"/unread", "") if err != nil { return nil, BuildResponse(r), err } @@ -2253,7 +2253,7 @@ func (c *Client4) ImportTeam(data []byte, filesize int, importFrom, filename, te // InviteUsersToTeam invite users by email to the team. func (c *Client4) InviteUsersToTeam(teamId string, userEmails []string) (*Response, error) { - r, err := c.DoApiPost(c.teamRoute(teamId)+"/invite/email", ArrayToJson(userEmails)) + r, err := c.DoAPIPost(c.teamRoute(teamId)+"/invite/email", ArrayToJson(userEmails)) if err != nil { return BuildResponse(r), err } @@ -2272,7 +2272,7 @@ func (c *Client4) InviteGuestsToTeam(teamId string, userEmails []string, channel if err != nil { return nil, NewAppError("InviteGuestsToTeam", "api.marshal_error", nil, err.Error(), http.StatusInternalServerError) } - r, err := c.doApiPostBytes(c.teamRoute(teamId)+"/invite-guests/email", buf) + r, err := c.DoAPIPostBytes(c.teamRoute(teamId)+"/invite-guests/email", buf) if err != nil { return BuildResponse(r), err } @@ -2282,7 +2282,7 @@ func (c *Client4) InviteGuestsToTeam(teamId string, userEmails []string, channel // InviteUsersToTeam invite users by email to the team. func (c *Client4) InviteUsersToTeamGracefully(teamId string, userEmails []string) ([]*EmailInviteWithError, *Response, error) { - r, err := c.DoApiPost(c.teamRoute(teamId)+"/invite/email?graceful="+c.boolString(true), ArrayToJson(userEmails)) + r, err := c.DoAPIPost(c.teamRoute(teamId)+"/invite/email?graceful="+c.boolString(true), ArrayToJson(userEmails)) if err != nil { return nil, BuildResponse(r), err } @@ -2301,7 +2301,7 @@ func (c *Client4) InviteGuestsToTeamGracefully(teamId string, userEmails []strin if err != nil { return nil, nil, NewAppError("InviteGuestsToTeamGracefully", "api.marshal_error", nil, err.Error(), http.StatusInternalServerError) } - r, err := c.doApiPostBytes(c.teamRoute(teamId)+"/invite-guests/email?graceful="+c.boolString(true), buf) + r, err := c.DoAPIPostBytes(c.teamRoute(teamId)+"/invite-guests/email?graceful="+c.boolString(true), buf) if err != nil { return nil, BuildResponse(r), err } @@ -2311,7 +2311,7 @@ func (c *Client4) InviteGuestsToTeamGracefully(teamId string, userEmails []strin // InvalidateEmailInvites will invalidate active email invitations that have not been accepted by the user. func (c *Client4) InvalidateEmailInvites() (*Response, error) { - r, err := c.DoApiDelete(c.teamsRoute() + "/invites/email") + r, err := c.DoAPIDelete(c.teamsRoute() + "/invites/email") if err != nil { return BuildResponse(r), err } @@ -2321,7 +2321,7 @@ func (c *Client4) InvalidateEmailInvites() (*Response, error) { // GetTeamInviteInfo returns a team object from an invite id containing sanitized information. func (c *Client4) GetTeamInviteInfo(inviteId string) (*Team, *Response, error) { - r, err := c.DoApiGet(c.teamsRoute()+"/invite/"+inviteId, "") + r, err := c.DoAPIGet(c.teamsRoute()+"/invite/"+inviteId, "") if err != nil { return nil, BuildResponse(r), err } @@ -2347,7 +2347,7 @@ func (c *Client4) SetTeamIcon(teamId string, data []byte) (*Response, error) { return nil, NewAppError("SetTeamIcon", "model.client.set_team_icon.writer.app_error", nil, err.Error(), http.StatusBadRequest) } - rq, err := http.NewRequest("POST", c.ApiUrl+c.teamRoute(teamId)+"/image", bytes.NewReader(body.Bytes())) + rq, err := http.NewRequest("POST", c.APIURL+c.teamRoute(teamId)+"/image", bytes.NewReader(body.Bytes())) if err != nil { return nil, err } @@ -2372,7 +2372,7 @@ func (c *Client4) SetTeamIcon(teamId string, data []byte) (*Response, error) { // GetTeamIcon gets the team icon of the team. func (c *Client4) GetTeamIcon(teamId, etag string) ([]byte, *Response, error) { - r, err := c.DoApiGet(c.teamRoute(teamId)+"/image", etag) + r, err := c.DoAPIGet(c.teamRoute(teamId)+"/image", etag) if err != nil { return nil, BuildResponse(r), err } @@ -2387,7 +2387,7 @@ func (c *Client4) GetTeamIcon(teamId, etag string) ([]byte, *Response, error) { // RemoveTeamIcon updates LastTeamIconUpdate to 0 which indicates team icon is removed. func (c *Client4) RemoveTeamIcon(teamId string) (*Response, error) { - r, err := c.DoApiDelete(c.teamRoute(teamId) + "/image") + r, err := c.DoAPIDelete(c.teamRoute(teamId) + "/image") if err != nil { return BuildResponse(r), err } @@ -2416,7 +2416,7 @@ func (c *Client4) GetAllChannelsExcludePolicyConstrained(page, perPage int, etag func (c *Client4) getAllChannels(page int, perPage int, etag string, opts ChannelSearchOpts) (*ChannelListWithTeamData, *Response, error) { query := fmt.Sprintf("?page=%v&per_page=%v&include_deleted=%v&exclude_policy_constrained=%v", page, perPage, opts.IncludeDeleted, opts.ExcludePolicyConstrained) - r, err := c.DoApiGet(c.channelsRoute()+query, etag) + r, err := c.DoAPIGet(c.channelsRoute()+query, etag) if err != nil { return nil, BuildResponse(r), err } @@ -2433,7 +2433,7 @@ func (c *Client4) getAllChannels(page int, perPage int, etag string, opts Channe // GetAllChannelsWithCount get all the channels including the total count. Must be a system administrator. func (c *Client4) GetAllChannelsWithCount(page int, perPage int, etag string) (*ChannelListWithTeamData, int64, *Response, error) { query := fmt.Sprintf("?page=%v&per_page=%v&include_total_count="+c.boolString(true), page, perPage) - r, err := c.DoApiGet(c.channelsRoute()+query, etag) + r, err := c.DoAPIGet(c.channelsRoute()+query, etag) if err != nil { return nil, 0, BuildResponse(r), err } @@ -2449,7 +2449,7 @@ func (c *Client4) GetAllChannelsWithCount(page int, perPage int, etag string) (* // CreateChannel creates a channel based on the provided channel struct. func (c *Client4) CreateChannel(channel *Channel) (*Channel, *Response, error) { - r, err := c.DoApiPost(c.channelsRoute(), channel.ToJson()) + r, err := c.DoAPIPost(c.channelsRoute(), channel.ToJson()) if err != nil { return nil, BuildResponse(r), err } @@ -2465,7 +2465,7 @@ func (c *Client4) CreateChannel(channel *Channel) (*Channel, *Response, error) { // UpdateChannel updates a channel based on the provided channel struct. func (c *Client4) UpdateChannel(channel *Channel) (*Channel, *Response, error) { - r, err := c.DoApiPut(c.channelRoute(channel.Id), channel.ToJson()) + r, err := c.DoAPIPut(c.channelRoute(channel.Id), channel.ToJson()) if err != nil { return nil, BuildResponse(r), err } @@ -2485,7 +2485,7 @@ func (c *Client4) PatchChannel(channelId string, patch *ChannelPatch) (*Channel, if err != nil { return nil, nil, NewAppError("PatchChannel", "api.marshal_error", nil, err.Error(), http.StatusInternalServerError) } - r, err := c.doApiPutBytes(c.channelRoute(channelId)+"/patch", buf) + r, err := c.DoAPIPutBytes(c.channelRoute(channelId)+"/patch", buf) if err != nil { return nil, BuildResponse(r), err } @@ -2502,7 +2502,7 @@ func (c *Client4) PatchChannel(channelId string, patch *ChannelPatch) (*Channel, // UpdateChannelPrivacy updates channel privacy func (c *Client4) UpdateChannelPrivacy(channelId string, privacy ChannelType) (*Channel, *Response, error) { requestBody := map[string]string{"privacy": string(privacy)} - r, err := c.DoApiPut(c.channelRoute(channelId)+"/privacy", MapToJson(requestBody)) + r, err := c.DoAPIPut(c.channelRoute(channelId)+"/privacy", MapToJson(requestBody)) if err != nil { return nil, BuildResponse(r), err } @@ -2518,7 +2518,7 @@ func (c *Client4) UpdateChannelPrivacy(channelId string, privacy ChannelType) (* // RestoreChannel restores a previously deleted channel. Any missing fields are not updated. func (c *Client4) RestoreChannel(channelId string) (*Channel, *Response, error) { - r, err := c.DoApiPost(c.channelRoute(channelId)+"/restore", "") + r, err := c.DoAPIPost(c.channelRoute(channelId)+"/restore", "") if err != nil { return nil, BuildResponse(r), err } @@ -2536,7 +2536,7 @@ func (c *Client4) RestoreChannel(channelId string) (*Channel, *Response, error) // ids provided. func (c *Client4) CreateDirectChannel(userId1, userId2 string) (*Channel, *Response, error) { requestBody := []string{userId1, userId2} - r, err := c.DoApiPost(c.channelsRoute()+"/direct", ArrayToJson(requestBody)) + r, err := c.DoAPIPost(c.channelsRoute()+"/direct", ArrayToJson(requestBody)) if err != nil { return nil, BuildResponse(r), err } @@ -2552,7 +2552,7 @@ func (c *Client4) CreateDirectChannel(userId1, userId2 string) (*Channel, *Respo // CreateGroupChannel creates a group message channel based on userIds provided. func (c *Client4) CreateGroupChannel(userIds []string) (*Channel, *Response, error) { - r, err := c.DoApiPost(c.channelsRoute()+"/group", ArrayToJson(userIds)) + r, err := c.DoAPIPost(c.channelsRoute()+"/group", ArrayToJson(userIds)) if err != nil { return nil, BuildResponse(r), err } @@ -2568,7 +2568,7 @@ func (c *Client4) CreateGroupChannel(userIds []string) (*Channel, *Response, err // GetChannel returns a channel based on the provided channel id string. func (c *Client4) GetChannel(channelId, etag string) (*Channel, *Response, error) { - r, err := c.DoApiGet(c.channelRoute(channelId), etag) + r, err := c.DoAPIGet(c.channelRoute(channelId), etag) if err != nil { return nil, BuildResponse(r), err } @@ -2584,7 +2584,7 @@ func (c *Client4) GetChannel(channelId, etag string) (*Channel, *Response, error // GetChannelStats returns statistics for a channel. func (c *Client4) GetChannelStats(channelId string, etag string) (*ChannelStats, *Response, error) { - r, err := c.DoApiGet(c.channelRoute(channelId)+"/stats", etag) + r, err := c.DoAPIGet(c.channelRoute(channelId)+"/stats", etag) if err != nil { return nil, BuildResponse(r), err } @@ -2594,7 +2594,7 @@ func (c *Client4) GetChannelStats(channelId string, etag string) (*ChannelStats, // GetChannelMembersTimezones gets a list of timezones for a channel. func (c *Client4) GetChannelMembersTimezones(channelId string) ([]string, *Response, error) { - r, err := c.DoApiGet(c.channelRoute(channelId)+"/timezones", "") + r, err := c.DoAPIGet(c.channelRoute(channelId)+"/timezones", "") if err != nil { return nil, BuildResponse(r), err } @@ -2604,7 +2604,7 @@ func (c *Client4) GetChannelMembersTimezones(channelId string) ([]string, *Respo // GetPinnedPosts gets a list of pinned posts. func (c *Client4) GetPinnedPosts(channelId string, etag string) (*PostList, *Response, error) { - r, err := c.DoApiGet(c.channelRoute(channelId)+"/pinned", etag) + r, err := c.DoAPIGet(c.channelRoute(channelId)+"/pinned", etag) if err != nil { return nil, BuildResponse(r), err } @@ -2615,7 +2615,7 @@ func (c *Client4) GetPinnedPosts(channelId string, etag string) (*PostList, *Res // GetPrivateChannelsForTeam returns a list of private channels based on the provided team id string. func (c *Client4) GetPrivateChannelsForTeam(teamId string, page int, perPage int, etag string) ([]*Channel, *Response, error) { query := fmt.Sprintf("/private?page=%v&per_page=%v", page, perPage) - r, err := c.DoApiGet(c.channelsForTeamRoute(teamId)+query, etag) + r, err := c.DoAPIGet(c.channelsForTeamRoute(teamId)+query, etag) if err != nil { return nil, BuildResponse(r), err } @@ -2632,7 +2632,7 @@ func (c *Client4) GetPrivateChannelsForTeam(teamId string, page int, perPage int // GetPublicChannelsForTeam returns a list of public channels based on the provided team id string. func (c *Client4) GetPublicChannelsForTeam(teamId string, page int, perPage int, etag string) ([]*Channel, *Response, error) { query := fmt.Sprintf("?page=%v&per_page=%v", page, perPage) - r, err := c.DoApiGet(c.channelsForTeamRoute(teamId)+query, etag) + r, err := c.DoAPIGet(c.channelsForTeamRoute(teamId)+query, etag) if err != nil { return nil, BuildResponse(r), err } @@ -2649,7 +2649,7 @@ func (c *Client4) GetPublicChannelsForTeam(teamId string, page int, perPage int, // GetDeletedChannelsForTeam returns a list of public channels based on the provided team id string. func (c *Client4) GetDeletedChannelsForTeam(teamId string, page int, perPage int, etag string) ([]*Channel, *Response, error) { query := fmt.Sprintf("/deleted?page=%v&per_page=%v", page, perPage) - r, err := c.DoApiGet(c.channelsForTeamRoute(teamId)+query, etag) + r, err := c.DoAPIGet(c.channelsForTeamRoute(teamId)+query, etag) if err != nil { return nil, BuildResponse(r), err } @@ -2665,7 +2665,7 @@ func (c *Client4) GetDeletedChannelsForTeam(teamId string, page int, perPage int // GetPublicChannelsByIdsForTeam returns a list of public channels based on provided team id string. func (c *Client4) GetPublicChannelsByIdsForTeam(teamId string, channelIds []string) ([]*Channel, *Response, error) { - r, err := c.DoApiPost(c.channelsForTeamRoute(teamId)+"/ids", ArrayToJson(channelIds)) + r, err := c.DoAPIPost(c.channelsForTeamRoute(teamId)+"/ids", ArrayToJson(channelIds)) if err != nil { return nil, BuildResponse(r), err } @@ -2681,7 +2681,7 @@ func (c *Client4) GetPublicChannelsByIdsForTeam(teamId string, channelIds []stri // GetChannelsForTeamForUser returns a list channels of on a team for a user. func (c *Client4) GetChannelsForTeamForUser(teamId, userId string, includeDeleted bool, etag string) ([]*Channel, *Response, error) { - r, err := c.DoApiGet(c.channelsForTeamForUserRoute(teamId, userId, includeDeleted), etag) + r, err := c.DoAPIGet(c.channelsForTeamForUserRoute(teamId, userId, includeDeleted), etag) if err != nil { return nil, BuildResponse(r), err } @@ -2699,7 +2699,7 @@ func (c *Client4) GetChannelsForTeamForUser(teamId, userId string, includeDelete func (c *Client4) GetChannelsForTeamAndUserWithLastDeleteAt(teamId, userId string, includeDeleted bool, lastDeleteAt int, etag string) ([]*Channel, *Response, error) { route := fmt.Sprintf(c.userRoute(userId) + c.teamRoute(teamId) + "/channels") route += fmt.Sprintf("?include_deleted=%v&last_delete_at=%d", includeDeleted, lastDeleteAt) - r, err := c.DoApiGet(route, etag) + r, err := c.DoAPIGet(route, etag) if err != nil { return nil, BuildResponse(r), err } @@ -2715,7 +2715,7 @@ func (c *Client4) GetChannelsForTeamAndUserWithLastDeleteAt(teamId, userId strin // SearchChannels returns the channels on a team matching the provided search term. func (c *Client4) SearchChannels(teamId string, search *ChannelSearch) ([]*Channel, *Response, error) { - r, err := c.DoApiPost(c.channelsForTeamRoute(teamId)+"/search", search.ToJson()) + r, err := c.DoAPIPost(c.channelsForTeamRoute(teamId)+"/search", search.ToJson()) if err != nil { return nil, BuildResponse(r), err } @@ -2731,7 +2731,7 @@ func (c *Client4) SearchChannels(teamId string, search *ChannelSearch) ([]*Chann // SearchArchivedChannels returns the archived channels on a team matching the provided search term. func (c *Client4) SearchArchivedChannels(teamId string, search *ChannelSearch) ([]*Channel, *Response, error) { - r, err := c.DoApiPost(c.channelsForTeamRoute(teamId)+"/search_archived", search.ToJson()) + r, err := c.DoAPIPost(c.channelsForTeamRoute(teamId)+"/search_archived", search.ToJson()) if err != nil { return nil, BuildResponse(r), err } @@ -2747,7 +2747,7 @@ func (c *Client4) SearchArchivedChannels(teamId string, search *ChannelSearch) ( // SearchAllChannels search in all the channels. Must be a system administrator. func (c *Client4) SearchAllChannels(search *ChannelSearch) (*ChannelListWithTeamData, *Response, error) { - r, err := c.DoApiPost(c.channelsRoute()+"/search", search.ToJson()) + r, err := c.DoAPIPost(c.channelsRoute()+"/search", search.ToJson()) if err != nil { return nil, BuildResponse(r), err } @@ -2763,7 +2763,7 @@ func (c *Client4) SearchAllChannels(search *ChannelSearch) (*ChannelListWithTeam // SearchAllChannelsPaged searches all the channels and returns the results paged with the total count. func (c *Client4) SearchAllChannelsPaged(search *ChannelSearch) (*ChannelsWithCount, *Response, error) { - r, err := c.DoApiPost(c.channelsRoute()+"/search", search.ToJson()) + r, err := c.DoAPIPost(c.channelsRoute()+"/search", search.ToJson()) if err != nil { return nil, BuildResponse(r), err } @@ -2779,7 +2779,7 @@ func (c *Client4) SearchAllChannelsPaged(search *ChannelSearch) (*ChannelsWithCo // SearchGroupChannels returns the group channels of the user whose members' usernames match the search term. func (c *Client4) SearchGroupChannels(search *ChannelSearch) ([]*Channel, *Response, error) { - r, err := c.DoApiPost(c.channelsRoute()+"/group/search", search.ToJson()) + r, err := c.DoAPIPost(c.channelsRoute()+"/group/search", search.ToJson()) if err != nil { return nil, BuildResponse(r), err } @@ -2795,7 +2795,7 @@ func (c *Client4) SearchGroupChannels(search *ChannelSearch) ([]*Channel, *Respo // DeleteChannel deletes channel based on the provided channel id string. func (c *Client4) DeleteChannel(channelId string) (*Response, error) { - r, err := c.DoApiDelete(c.channelRoute(channelId)) + r, err := c.DoAPIDelete(c.channelRoute(channelId)) if err != nil { return BuildResponse(r), err } @@ -2805,7 +2805,7 @@ func (c *Client4) DeleteChannel(channelId string) (*Response, error) { // PermanentDeleteChannel deletes a channel based on the provided channel id string. func (c *Client4) PermanentDeleteChannel(channelId string) (*Response, error) { - r, err := c.DoApiDelete(c.channelRoute(channelId) + "?permanent=" + c.boolString(true)) + r, err := c.DoAPIDelete(c.channelRoute(channelId) + "?permanent=" + c.boolString(true)) if err != nil { return BuildResponse(r), err } @@ -2819,7 +2819,7 @@ func (c *Client4) MoveChannel(channelId, teamId string, force bool) (*Channel, * "team_id": teamId, "force": force, } - r, err := c.DoApiPost(c.channelRoute(channelId)+"/move", StringInterfaceToJson(requestBody)) + r, err := c.DoAPIPost(c.channelRoute(channelId)+"/move", StringInterfaceToJson(requestBody)) if err != nil { return nil, BuildResponse(r), err } @@ -2835,7 +2835,7 @@ func (c *Client4) MoveChannel(channelId, teamId string, force bool) (*Channel, * // GetChannelByName returns a channel based on the provided channel name and team id strings. func (c *Client4) GetChannelByName(channelName, teamId string, etag string) (*Channel, *Response, error) { - r, err := c.DoApiGet(c.channelByNameRoute(channelName, teamId), etag) + r, err := c.DoAPIGet(c.channelByNameRoute(channelName, teamId), etag) if err != nil { return nil, BuildResponse(r), err } @@ -2851,7 +2851,7 @@ func (c *Client4) GetChannelByName(channelName, teamId string, etag string) (*Ch // GetChannelByNameIncludeDeleted returns a channel based on the provided channel name and team id strings. Other then GetChannelByName it will also return deleted channels. func (c *Client4) GetChannelByNameIncludeDeleted(channelName, teamId string, etag string) (*Channel, *Response, error) { - r, err := c.DoApiGet(c.channelByNameRoute(channelName, teamId)+"?include_deleted="+c.boolString(true), etag) + r, err := c.DoAPIGet(c.channelByNameRoute(channelName, teamId)+"?include_deleted="+c.boolString(true), etag) if err != nil { return nil, BuildResponse(r), err } @@ -2867,7 +2867,7 @@ func (c *Client4) GetChannelByNameIncludeDeleted(channelName, teamId string, eta // GetChannelByNameForTeamName returns a channel based on the provided channel name and team name strings. func (c *Client4) GetChannelByNameForTeamName(channelName, teamName string, etag string) (*Channel, *Response, error) { - r, err := c.DoApiGet(c.channelByNameForTeamNameRoute(channelName, teamName), etag) + r, err := c.DoAPIGet(c.channelByNameForTeamNameRoute(channelName, teamName), etag) if err != nil { return nil, BuildResponse(r), err } @@ -2883,7 +2883,7 @@ func (c *Client4) GetChannelByNameForTeamName(channelName, teamName string, etag // GetChannelByNameForTeamNameIncludeDeleted returns a channel based on the provided channel name and team name strings. Other then GetChannelByNameForTeamName it will also return deleted channels. func (c *Client4) GetChannelByNameForTeamNameIncludeDeleted(channelName, teamName string, etag string) (*Channel, *Response, error) { - r, err := c.DoApiGet(c.channelByNameForTeamNameRoute(channelName, teamName)+"?include_deleted="+c.boolString(true), etag) + r, err := c.DoAPIGet(c.channelByNameForTeamNameRoute(channelName, teamName)+"?include_deleted="+c.boolString(true), etag) if err != nil { return nil, BuildResponse(r), err } @@ -2900,7 +2900,7 @@ func (c *Client4) GetChannelByNameForTeamNameIncludeDeleted(channelName, teamNam // GetChannelMembers gets a page of channel members. func (c *Client4) GetChannelMembers(channelId string, page, perPage int, etag string) (*ChannelMembers, *Response, error) { query := fmt.Sprintf("?page=%v&per_page=%v", page, perPage) - r, err := c.DoApiGet(c.channelMembersRoute(channelId)+query, etag) + r, err := c.DoAPIGet(c.channelMembersRoute(channelId)+query, etag) if err != nil { return nil, BuildResponse(r), err } @@ -2916,7 +2916,7 @@ func (c *Client4) GetChannelMembers(channelId string, page, perPage int, etag st // GetChannelMembersByIds gets the channel members in a channel for a list of user ids. func (c *Client4) GetChannelMembersByIds(channelId string, userIds []string) (*ChannelMembers, *Response, error) { - r, err := c.DoApiPost(c.channelMembersRoute(channelId)+"/ids", ArrayToJson(userIds)) + r, err := c.DoAPIPost(c.channelMembersRoute(channelId)+"/ids", ArrayToJson(userIds)) if err != nil { return nil, BuildResponse(r), err } @@ -2932,7 +2932,7 @@ func (c *Client4) GetChannelMembersByIds(channelId string, userIds []string) (*C // GetChannelMember gets a channel member. func (c *Client4) GetChannelMember(channelId, userId, etag string) (*ChannelMember, *Response, error) { - r, err := c.DoApiGet(c.channelMemberRoute(channelId, userId), etag) + r, err := c.DoAPIGet(c.channelMemberRoute(channelId, userId), etag) if err != nil { return nil, BuildResponse(r), err } @@ -2948,7 +2948,7 @@ func (c *Client4) GetChannelMember(channelId, userId, etag string) (*ChannelMemb // GetChannelMembersForUser gets all the channel members for a user on a team. func (c *Client4) GetChannelMembersForUser(userId, teamId, etag string) (*ChannelMembers, *Response, error) { - r, err := c.DoApiGet(fmt.Sprintf(c.userRoute(userId)+"/teams/%v/channels/members", teamId), etag) + r, err := c.DoAPIGet(fmt.Sprintf(c.userRoute(userId)+"/teams/%v/channels/members", teamId), etag) if err != nil { return nil, BuildResponse(r), err } @@ -2969,7 +2969,7 @@ func (c *Client4) ViewChannel(userId string, view *ChannelView) (*ChannelViewRes if err != nil { return nil, nil, NewAppError("ViewChannel", "api.marshal_error", nil, err.Error(), http.StatusInternalServerError) } - r, err := c.doApiPostBytes(url, buf) + r, err := c.DoAPIPostBytes(url, buf) if err != nil { return nil, BuildResponse(r), err } @@ -2986,7 +2986,7 @@ func (c *Client4) ViewChannel(userId string, view *ChannelView) (*ChannelViewRes // GetChannelUnread will return a ChannelUnread object that contains the number of // unread messages and mentions for a user. func (c *Client4) GetChannelUnread(channelId, userId string) (*ChannelUnread, *Response, error) { - r, err := c.DoApiGet(c.userRoute(userId)+c.channelRoute(channelId)+"/unread", "") + r, err := c.DoAPIGet(c.userRoute(userId)+c.channelRoute(channelId)+"/unread", "") if err != nil { return nil, BuildResponse(r), err } @@ -3003,7 +3003,7 @@ func (c *Client4) GetChannelUnread(channelId, userId string) (*ChannelUnread, *R // UpdateChannelRoles will update the roles on a channel for a user. func (c *Client4) UpdateChannelRoles(channelId, userId, roles string) (*Response, error) { requestBody := map[string]string{"roles": roles} - r, err := c.DoApiPut(c.channelMemberRoute(channelId, userId)+"/roles", MapToJson(requestBody)) + r, err := c.DoAPIPut(c.channelMemberRoute(channelId, userId)+"/roles", MapToJson(requestBody)) if err != nil { return BuildResponse(r), err } @@ -3017,7 +3017,7 @@ func (c *Client4) UpdateChannelMemberSchemeRoles(channelId string, userId string if err != nil { return nil, NewAppError("UpdateChannelMemberSchemeRoles", "api.marshal_error", nil, err.Error(), http.StatusInternalServerError) } - r, err := c.doApiPutBytes(c.channelMemberRoute(channelId, userId)+"/schemeRoles", buf) + r, err := c.DoAPIPutBytes(c.channelMemberRoute(channelId, userId)+"/schemeRoles", buf) if err != nil { return BuildResponse(r), err } @@ -3027,7 +3027,7 @@ func (c *Client4) UpdateChannelMemberSchemeRoles(channelId string, userId string // UpdateChannelNotifyProps will update the notification properties on a channel for a user. func (c *Client4) UpdateChannelNotifyProps(channelId, userId string, props map[string]string) (*Response, error) { - r, err := c.DoApiPut(c.channelMemberRoute(channelId, userId)+"/notify_props", MapToJson(props)) + r, err := c.DoAPIPut(c.channelMemberRoute(channelId, userId)+"/notify_props", MapToJson(props)) if err != nil { return BuildResponse(r), err } @@ -3038,7 +3038,7 @@ func (c *Client4) UpdateChannelNotifyProps(channelId, userId string, props map[s // AddChannelMember adds user to channel and return a channel member. func (c *Client4) AddChannelMember(channelId, userId string) (*ChannelMember, *Response, error) { requestBody := map[string]string{"user_id": userId} - r, err := c.DoApiPost(c.channelMembersRoute(channelId)+"", MapToJson(requestBody)) + r, err := c.DoAPIPost(c.channelMembersRoute(channelId)+"", MapToJson(requestBody)) if err != nil { return nil, BuildResponse(r), err } @@ -3055,7 +3055,7 @@ func (c *Client4) AddChannelMember(channelId, userId string) (*ChannelMember, *R // AddChannelMemberWithRootId adds user to channel and return a channel member. Post add to channel message has the postRootId. func (c *Client4) AddChannelMemberWithRootId(channelId, userId, postRootId string) (*ChannelMember, *Response, error) { requestBody := map[string]string{"user_id": userId, "post_root_id": postRootId} - r, err := c.DoApiPost(c.channelMembersRoute(channelId)+"", MapToJson(requestBody)) + r, err := c.DoAPIPost(c.channelMembersRoute(channelId)+"", MapToJson(requestBody)) if err != nil { return nil, BuildResponse(r), err } @@ -3071,7 +3071,7 @@ func (c *Client4) AddChannelMemberWithRootId(channelId, userId, postRootId strin // RemoveUserFromChannel will delete the channel member object for a user, effectively removing the user from a channel. func (c *Client4) RemoveUserFromChannel(channelId, userId string) (*Response, error) { - r, err := c.DoApiDelete(c.channelMemberRoute(channelId, userId)) + r, err := c.DoAPIDelete(c.channelMemberRoute(channelId, userId)) if err != nil { return BuildResponse(r), err } @@ -3082,7 +3082,7 @@ func (c *Client4) RemoveUserFromChannel(channelId, userId string) (*Response, er // AutocompleteChannelsForTeam will return an ordered list of channels autocomplete suggestions. func (c *Client4) AutocompleteChannelsForTeam(teamId, name string) (*ChannelList, *Response, error) { query := fmt.Sprintf("?name=%v", name) - r, err := c.DoApiGet(c.channelsForTeamRoute(teamId)+"/autocomplete"+query, "") + r, err := c.DoAPIGet(c.channelsForTeamRoute(teamId)+"/autocomplete"+query, "") if err != nil { return nil, BuildResponse(r), err } @@ -3099,7 +3099,7 @@ func (c *Client4) AutocompleteChannelsForTeam(teamId, name string) (*ChannelList // AutocompleteChannelsForTeamForSearch will return an ordered list of your channels autocomplete suggestions. func (c *Client4) AutocompleteChannelsForTeamForSearch(teamId, name string) (*ChannelList, *Response, error) { query := fmt.Sprintf("?name=%v", name) - r, err := c.DoApiGet(c.channelsForTeamRoute(teamId)+"/search_autocomplete"+query, "") + r, err := c.DoAPIGet(c.channelsForTeamRoute(teamId)+"/search_autocomplete"+query, "") if err != nil { return nil, BuildResponse(r), err } @@ -3117,7 +3117,7 @@ func (c *Client4) AutocompleteChannelsForTeamForSearch(teamId, name string) (*Ch // CreatePost creates a post based on the provided post struct. func (c *Client4) CreatePost(post *Post) (*Post, *Response, error) { - r, err := c.DoApiPost(c.postsRoute(), post.ToUnsanitizedJson()) + r, err := c.DoAPIPost(c.postsRoute(), post.ToUnsanitizedJson()) if err != nil { return nil, BuildResponse(r), err } @@ -3127,7 +3127,7 @@ func (c *Client4) CreatePost(post *Post) (*Post, *Response, error) { // CreatePostEphemeral creates a ephemeral post based on the provided post struct which is send to the given user id. func (c *Client4) CreatePostEphemeral(post *PostEphemeral) (*Post, *Response, error) { - r, err := c.DoApiPost(c.postsEphemeralRoute(), post.ToUnsanitizedJson()) + r, err := c.DoAPIPost(c.postsEphemeralRoute(), post.ToUnsanitizedJson()) if err != nil { return nil, BuildResponse(r), err } @@ -3137,7 +3137,7 @@ func (c *Client4) CreatePostEphemeral(post *PostEphemeral) (*Post, *Response, er // UpdatePost updates a post based on the provided post struct. func (c *Client4) UpdatePost(postId string, post *Post) (*Post, *Response, error) { - r, err := c.DoApiPut(c.postRoute(postId), post.ToUnsanitizedJson()) + r, err := c.DoAPIPut(c.postRoute(postId), post.ToUnsanitizedJson()) if err != nil { return nil, BuildResponse(r), err } @@ -3151,7 +3151,7 @@ func (c *Client4) PatchPost(postId string, patch *PostPatch) (*Post, *Response, if err != nil { return nil, nil, NewAppError("PatchPost", "api.marshal_error", nil, err.Error(), http.StatusInternalServerError) } - r, err := c.doApiPutBytes(c.postRoute(postId)+"/patch", buf) + r, err := c.DoAPIPutBytes(c.postRoute(postId)+"/patch", buf) if err != nil { return nil, BuildResponse(r), err } @@ -3165,7 +3165,7 @@ func (c *Client4) SetPostUnread(userId string, postId string, collapsedThreadsSu if err != nil { return nil, NewAppError("SetPostUnread", "api.marshal_error", nil, err.Error(), http.StatusInternalServerError) } - r, err := c.doApiPostBytes(c.userRoute(userId)+c.postRoute(postId)+"/set_unread", b) + r, err := c.DoAPIPostBytes(c.userRoute(userId)+c.postRoute(postId)+"/set_unread", b) if err != nil { return BuildResponse(r), err } @@ -3175,7 +3175,7 @@ func (c *Client4) SetPostUnread(userId string, postId string, collapsedThreadsSu // PinPost pin a post based on provided post id string. func (c *Client4) PinPost(postId string) (*Response, error) { - r, err := c.DoApiPost(c.postRoute(postId)+"/pin", "") + r, err := c.DoAPIPost(c.postRoute(postId)+"/pin", "") if err != nil { return BuildResponse(r), err } @@ -3185,7 +3185,7 @@ func (c *Client4) PinPost(postId string) (*Response, error) { // UnpinPost unpin a post based on provided post id string. func (c *Client4) UnpinPost(postId string) (*Response, error) { - r, err := c.DoApiPost(c.postRoute(postId)+"/unpin", "") + r, err := c.DoAPIPost(c.postRoute(postId)+"/unpin", "") if err != nil { return BuildResponse(r), err } @@ -3195,7 +3195,7 @@ func (c *Client4) UnpinPost(postId string) (*Response, error) { // GetPost gets a single post. func (c *Client4) GetPost(postId string, etag string) (*Post, *Response, error) { - r, err := c.DoApiGet(c.postRoute(postId), etag) + r, err := c.DoAPIGet(c.postRoute(postId), etag) if err != nil { return nil, BuildResponse(r), err } @@ -3205,7 +3205,7 @@ func (c *Client4) GetPost(postId string, etag string) (*Post, *Response, error) // DeletePost deletes a post from the provided post id string. func (c *Client4) DeletePost(postId string) (*Response, error) { - r, err := c.DoApiDelete(c.postRoute(postId)) + r, err := c.DoAPIDelete(c.postRoute(postId)) if err != nil { return BuildResponse(r), err } @@ -3219,7 +3219,7 @@ func (c *Client4) GetPostThread(postId string, etag string, collapsedThreads boo if collapsedThreads { url += "?collapsedThreads=true" } - r, err := c.DoApiGet(url, etag) + r, err := c.DoAPIGet(url, etag) if err != nil { return nil, BuildResponse(r), err } @@ -3233,7 +3233,7 @@ func (c *Client4) GetPostsForChannel(channelId string, page, perPage int, etag s if collapsedThreads { query += "&collapsedThreads=true" } - r, err := c.DoApiGet(c.channelRoute(channelId)+"/posts"+query, etag) + r, err := c.DoAPIGet(c.channelRoute(channelId)+"/posts"+query, etag) if err != nil { return nil, BuildResponse(r), err } @@ -3244,7 +3244,7 @@ func (c *Client4) GetPostsForChannel(channelId string, page, perPage int, etag s // GetFlaggedPostsForUser returns flagged posts of a user based on user id string. func (c *Client4) GetFlaggedPostsForUser(userId string, page int, perPage int) (*PostList, *Response, error) { query := fmt.Sprintf("?page=%v&per_page=%v", page, perPage) - r, err := c.DoApiGet(c.userRoute(userId)+"/posts/flagged"+query, "") + r, err := c.DoAPIGet(c.userRoute(userId)+"/posts/flagged"+query, "") if err != nil { return nil, BuildResponse(r), err } @@ -3259,7 +3259,7 @@ func (c *Client4) GetFlaggedPostsForUserInTeam(userId string, teamId string, pag } query := fmt.Sprintf("?team_id=%v&page=%v&per_page=%v", teamId, page, perPage) - r, err := c.DoApiGet(c.userRoute(userId)+"/posts/flagged"+query, "") + r, err := c.DoAPIGet(c.userRoute(userId)+"/posts/flagged"+query, "") if err != nil { return nil, BuildResponse(r), err } @@ -3274,7 +3274,7 @@ func (c *Client4) GetFlaggedPostsForUserInChannel(userId string, channelId strin } query := fmt.Sprintf("?channel_id=%v&page=%v&per_page=%v", channelId, page, perPage) - r, err := c.DoApiGet(c.userRoute(userId)+"/posts/flagged"+query, "") + r, err := c.DoAPIGet(c.userRoute(userId)+"/posts/flagged"+query, "") if err != nil { return nil, BuildResponse(r), err } @@ -3288,7 +3288,7 @@ func (c *Client4) GetPostsSince(channelId string, time int64, collapsedThreads b if collapsedThreads { query += "&collapsedThreads=true" } - r, err := c.DoApiGet(c.channelRoute(channelId)+"/posts"+query, "") + r, err := c.DoAPIGet(c.channelRoute(channelId)+"/posts"+query, "") if err != nil { return nil, BuildResponse(r), err } @@ -3302,7 +3302,7 @@ func (c *Client4) GetPostsAfter(channelId, postId string, page, perPage int, eta if collapsedThreads { query += "&collapsedThreads=true" } - r, err := c.DoApiGet(c.channelRoute(channelId)+"/posts"+query, etag) + r, err := c.DoAPIGet(c.channelRoute(channelId)+"/posts"+query, etag) if err != nil { return nil, BuildResponse(r), err } @@ -3316,7 +3316,7 @@ func (c *Client4) GetPostsBefore(channelId, postId string, page, perPage int, et if collapsedThreads { query += "&collapsedThreads=true" } - r, err := c.DoApiGet(c.channelRoute(channelId)+"/posts"+query, etag) + r, err := c.DoAPIGet(c.channelRoute(channelId)+"/posts"+query, etag) if err != nil { return nil, BuildResponse(r), err } @@ -3330,7 +3330,7 @@ func (c *Client4) GetPostsAroundLastUnread(userId, channelId string, limitBefore if collapsedThreads { query += "&collapsedThreads=true" } - r, err := c.DoApiGet(c.userRoute(userId)+c.channelRoute(channelId)+"/posts/unread"+query, "") + r, err := c.DoAPIGet(c.userRoute(userId)+c.channelRoute(channelId)+"/posts/unread"+query, "") if err != nil { return nil, BuildResponse(r), err } @@ -3349,7 +3349,7 @@ func (c *Client4) SearchFiles(teamId string, terms string, isOrSearch bool) (*Fi // SearchFilesWithParams returns any posts with matching terms string. func (c *Client4) SearchFilesWithParams(teamId string, params *SearchParameter) (*FileInfoList, *Response, error) { - r, err := c.DoApiPost(c.teamRoute(teamId)+"/files/search", params.SearchParameterToJson()) + r, err := c.DoAPIPost(c.teamRoute(teamId)+"/files/search", params.SearchParameterToJson()) if err != nil { return nil, BuildResponse(r), err } @@ -3368,7 +3368,7 @@ func (c *Client4) SearchPosts(teamId string, terms string, isOrSearch bool) (*Po // SearchPostsWithParams returns any posts with matching terms string. func (c *Client4) SearchPostsWithParams(teamId string, params *SearchParameter) (*PostList, *Response, error) { - r, err := c.DoApiPost(c.teamRoute(teamId)+"/posts/search", params.SearchParameterToJson()) + r, err := c.DoAPIPost(c.teamRoute(teamId)+"/posts/search", params.SearchParameterToJson()) if err != nil { return nil, BuildResponse(r), err } @@ -3379,7 +3379,7 @@ func (c *Client4) SearchPostsWithParams(teamId string, params *SearchParameter) // SearchPostsWithMatches returns any posts with matching terms string, including. func (c *Client4) SearchPostsWithMatches(teamId string, terms string, isOrSearch bool) (*PostSearchResults, *Response, error) { requestBody := map[string]interface{}{"terms": terms, "is_or_search": isOrSearch} - r, err := c.DoApiPost(c.teamRoute(teamId)+"/posts/search", StringInterfaceToJson(requestBody)) + r, err := c.DoAPIPost(c.teamRoute(teamId)+"/posts/search", StringInterfaceToJson(requestBody)) if err != nil { return nil, BuildResponse(r), err } @@ -3389,7 +3389,7 @@ func (c *Client4) SearchPostsWithMatches(teamId string, terms string, isOrSearch // DoPostAction performs a post action. func (c *Client4) DoPostAction(postId, actionId string) (*Response, error) { - r, err := c.DoApiPost(c.postRoute(postId)+"/actions/"+actionId, "") + r, err := c.DoAPIPost(c.postRoute(postId)+"/actions/"+actionId, "") if err != nil { return BuildResponse(r), err } @@ -3406,7 +3406,7 @@ func (c *Client4) DoPostActionWithCookie(postId, actionId, selected, cookieStr s Cookie: cookieStr, }) } - r, err := c.DoApiPost(c.postRoute(postId)+"/actions/"+actionId, string(body)) + r, err := c.DoAPIPost(c.postRoute(postId)+"/actions/"+actionId, string(body)) if err != nil { return BuildResponse(r), err } @@ -3420,7 +3420,7 @@ func (c *Client4) DoPostActionWithCookie(postId, actionId, selected, cookieStr s // slash commands. func (c *Client4) OpenInteractiveDialog(request OpenDialogRequest) (*Response, error) { b, _ := json.Marshal(request) - r, err := c.DoApiPost("/actions/dialogs/open", string(b)) + r, err := c.DoAPIPost("/actions/dialogs/open", string(b)) if err != nil { return BuildResponse(r), err } @@ -3432,7 +3432,7 @@ func (c *Client4) OpenInteractiveDialog(request OpenDialogRequest) (*Response, e // configured by the URL. Used with the interactive dialogs integration feature. func (c *Client4) SubmitInteractiveDialog(request SubmitDialogRequest) (*SubmitDialogResponse, *Response, error) { b, _ := json.Marshal(request) - r, err := c.DoApiPost("/actions/dialogs/submit", string(b)) + r, err := c.DoAPIPost("/actions/dialogs/submit", string(b)) if err != nil { return nil, BuildResponse(r), err } @@ -3484,7 +3484,7 @@ func (c *Client4) UploadFileAsRequestBody(data []byte, channelId string, filenam // GetFile gets the bytes for a file by id. func (c *Client4) GetFile(fileId string) ([]byte, *Response, error) { - r, err := c.DoApiGet(c.fileRoute(fileId), "") + r, err := c.DoAPIGet(c.fileRoute(fileId), "") if err != nil { return nil, BuildResponse(r), err } @@ -3499,7 +3499,7 @@ func (c *Client4) GetFile(fileId string) ([]byte, *Response, error) { // DownloadFile gets the bytes for a file by id, optionally adding headers to force the browser to download it. func (c *Client4) DownloadFile(fileId string, download bool) ([]byte, *Response, error) { - r, err := c.DoApiGet(c.fileRoute(fileId)+fmt.Sprintf("?download=%v", download), "") + r, err := c.DoAPIGet(c.fileRoute(fileId)+fmt.Sprintf("?download=%v", download), "") if err != nil { return nil, BuildResponse(r), err } @@ -3514,7 +3514,7 @@ func (c *Client4) DownloadFile(fileId string, download bool) ([]byte, *Response, // GetFileThumbnail gets the bytes for a file by id. func (c *Client4) GetFileThumbnail(fileId string) ([]byte, *Response, error) { - r, err := c.DoApiGet(c.fileRoute(fileId)+"/thumbnail", "") + r, err := c.DoAPIGet(c.fileRoute(fileId)+"/thumbnail", "") if err != nil { return nil, BuildResponse(r), err } @@ -3529,7 +3529,7 @@ func (c *Client4) GetFileThumbnail(fileId string) ([]byte, *Response, error) { // DownloadFileThumbnail gets the bytes for a file by id, optionally adding headers to force the browser to download it. func (c *Client4) DownloadFileThumbnail(fileId string, download bool) ([]byte, *Response, error) { - r, err := c.DoApiGet(c.fileRoute(fileId)+fmt.Sprintf("/thumbnail?download=%v", download), "") + r, err := c.DoAPIGet(c.fileRoute(fileId)+fmt.Sprintf("/thumbnail?download=%v", download), "") if err != nil { return nil, BuildResponse(r), err } @@ -3544,7 +3544,7 @@ func (c *Client4) DownloadFileThumbnail(fileId string, download bool) ([]byte, * // GetFileLink gets the public link of a file by id. func (c *Client4) GetFileLink(fileId string) (string, *Response, error) { - r, err := c.DoApiGet(c.fileRoute(fileId)+"/link", "") + r, err := c.DoAPIGet(c.fileRoute(fileId)+"/link", "") if err != nil { return "", BuildResponse(r), err } @@ -3554,7 +3554,7 @@ func (c *Client4) GetFileLink(fileId string) (string, *Response, error) { // GetFilePreview gets the bytes for a file by id. func (c *Client4) GetFilePreview(fileId string) ([]byte, *Response, error) { - r, err := c.DoApiGet(c.fileRoute(fileId)+"/preview", "") + r, err := c.DoAPIGet(c.fileRoute(fileId)+"/preview", "") if err != nil { return nil, BuildResponse(r), err } @@ -3569,7 +3569,7 @@ func (c *Client4) GetFilePreview(fileId string) ([]byte, *Response, error) { // DownloadFilePreview gets the bytes for a file by id. func (c *Client4) DownloadFilePreview(fileId string, download bool) ([]byte, *Response, error) { - r, err := c.DoApiGet(c.fileRoute(fileId)+fmt.Sprintf("/preview?download=%v", download), "") + r, err := c.DoAPIGet(c.fileRoute(fileId)+fmt.Sprintf("/preview?download=%v", download), "") if err != nil { return nil, BuildResponse(r), err } @@ -3584,7 +3584,7 @@ func (c *Client4) DownloadFilePreview(fileId string, download bool) ([]byte, *Re // GetFileInfo gets all the file info objects. func (c *Client4) GetFileInfo(fileId string) (*FileInfo, *Response, error) { - r, err := c.DoApiGet(c.fileRoute(fileId)+"/info", "") + r, err := c.DoAPIGet(c.fileRoute(fileId)+"/info", "") if err != nil { return nil, BuildResponse(r), err } @@ -3594,7 +3594,7 @@ func (c *Client4) GetFileInfo(fileId string) (*FileInfo, *Response, error) { // GetFileInfosForPost gets all the file info objects attached to a post. func (c *Client4) GetFileInfosForPost(postId string, etag string) ([]*FileInfo, *Response, error) { - r, err := c.DoApiGet(c.postRoute(postId)+"/files/info", etag) + r, err := c.DoAPIGet(c.postRoute(postId)+"/files/info", etag) if err != nil { return nil, BuildResponse(r), err } @@ -3606,7 +3606,7 @@ func (c *Client4) GetFileInfosForPost(postId string, etag string) ([]*FileInfo, // GenerateSupportPacket downloads the generated support packet func (c *Client4) GenerateSupportPacket() ([]byte, *Response, error) { - r, err := c.DoApiGet(c.systemRoute()+"/support_packet", "") + r, err := c.DoAPIGet(c.systemRoute()+"/support_packet", "") if err != nil { return nil, BuildResponse(r), err } @@ -3621,7 +3621,7 @@ func (c *Client4) GenerateSupportPacket() ([]byte, *Response, error) { // GetPing will return ok if the running goRoutines are below the threshold and unhealthy for above. func (c *Client4) GetPing() (string, *Response, error) { - r, err := c.DoApiGet(c.systemRoute()+"/ping", "") + r, err := c.DoAPIGet(c.systemRoute()+"/ping", "") if r != nil && r.StatusCode == 500 { defer r.Body.Close() return StatusUnhealthy, BuildResponse(r), err @@ -3636,7 +3636,7 @@ func (c *Client4) GetPing() (string, *Response, error) { // GetPingWithServerStatus will return ok if several basic server health checks // all pass successfully. func (c *Client4) GetPingWithServerStatus() (string, *Response, error) { - r, err := c.DoApiGet(c.systemRoute()+"/ping?get_server_status="+c.boolString(true), "") + r, err := c.DoAPIGet(c.systemRoute()+"/ping?get_server_status="+c.boolString(true), "") if r != nil && r.StatusCode == 500 { defer r.Body.Close() return StatusUnhealthy, BuildResponse(r), err @@ -3651,7 +3651,7 @@ func (c *Client4) GetPingWithServerStatus() (string, *Response, error) { // GetPingWithFullServerStatus will return the full status if several basic server // health checks all pass successfully. func (c *Client4) GetPingWithFullServerStatus() (map[string]string, *Response, error) { - r, err := c.DoApiGet(c.systemRoute()+"/ping?get_server_status="+c.boolString(true), "") + r, err := c.DoAPIGet(c.systemRoute()+"/ping?get_server_status="+c.boolString(true), "") if r != nil && r.StatusCode == 500 { defer r.Body.Close() return map[string]string{"status": StatusUnhealthy}, BuildResponse(r), err @@ -3669,7 +3669,7 @@ func (c *Client4) TestEmail(config *Config) (*Response, error) { if err != nil { return nil, NewAppError("TestEmail", "api.marshal_error", nil, err.Error(), http.StatusInternalServerError) } - r, err := c.doApiPostBytes(c.testEmailRoute(), buf) + r, err := c.DoAPIPostBytes(c.testEmailRoute(), buf) if err != nil { return BuildResponse(r), err } @@ -3681,7 +3681,7 @@ func (c *Client4) TestEmail(config *Config) (*Response, error) { func (c *Client4) TestSiteURL(siteURL string) (*Response, error) { requestBody := make(map[string]string) requestBody["site_url"] = siteURL - r, err := c.DoApiPost(c.testSiteURLRoute(), MapToJson(requestBody)) + r, err := c.DoAPIPost(c.testSiteURLRoute(), MapToJson(requestBody)) if err != nil { return BuildResponse(r), err } @@ -3695,7 +3695,7 @@ func (c *Client4) TestS3Connection(config *Config) (*Response, error) { if err != nil { return nil, NewAppError("TestS3Connection", "api.marshal_error", nil, err.Error(), http.StatusInternalServerError) } - r, err := c.doApiPostBytes(c.testS3Route(), buf) + r, err := c.DoAPIPostBytes(c.testS3Route(), buf) if err != nil { return BuildResponse(r), err } @@ -3705,7 +3705,7 @@ func (c *Client4) TestS3Connection(config *Config) (*Response, error) { // GetConfig will retrieve the server config with some sanitized items. func (c *Client4) GetConfig() (*Config, *Response, error) { - r, err := c.DoApiGet(c.configRoute(), "") + r, err := c.DoAPIGet(c.configRoute(), "") if err != nil { return nil, BuildResponse(r), err } @@ -3715,7 +3715,7 @@ func (c *Client4) GetConfig() (*Config, *Response, error) { // ReloadConfig will reload the server configuration. func (c *Client4) ReloadConfig() (*Response, error) { - r, err := c.DoApiPost(c.configRoute()+"/reload", "") + r, err := c.DoAPIPost(c.configRoute()+"/reload", "") if err != nil { return BuildResponse(r), err } @@ -3726,7 +3726,7 @@ func (c *Client4) ReloadConfig() (*Response, error) { // GetOldClientConfig will retrieve the parts of the server configuration needed by the // client, formatted in the old format. func (c *Client4) GetOldClientConfig(etag string) (map[string]string, *Response, error) { - r, err := c.DoApiGet(c.configRoute()+"/client?format=old", etag) + r, err := c.DoAPIGet(c.configRoute()+"/client?format=old", etag) if err != nil { return nil, BuildResponse(r), err } @@ -3738,7 +3738,7 @@ func (c *Client4) GetOldClientConfig(etag string) (map[string]string, *Response, // are set to true if the corresponding config setting is set through an environment variable. // Settings that haven't been set through environment variables will be missing from the map. func (c *Client4) GetEnvironmentConfig() (map[string]interface{}, *Response, error) { - r, err := c.DoApiGet(c.configRoute()+"/environment", "") + r, err := c.DoAPIGet(c.configRoute()+"/environment", "") if err != nil { return nil, BuildResponse(r), err } @@ -3749,7 +3749,7 @@ func (c *Client4) GetEnvironmentConfig() (map[string]interface{}, *Response, err // GetOldClientLicense will retrieve the parts of the server license needed by the // client, formatted in the old format. func (c *Client4) GetOldClientLicense(etag string) (map[string]string, *Response, error) { - r, err := c.DoApiGet(c.licenseRoute()+"/client?format=old", etag) + r, err := c.DoAPIGet(c.licenseRoute()+"/client?format=old", etag) if err != nil { return nil, BuildResponse(r), err } @@ -3759,7 +3759,7 @@ func (c *Client4) GetOldClientLicense(etag string) (map[string]string, *Response // DatabaseRecycle will recycle the connections. Discard current connection and get new one. func (c *Client4) DatabaseRecycle() (*Response, error) { - r, err := c.DoApiPost(c.databaseRoute()+"/recycle", "") + r, err := c.DoAPIPost(c.databaseRoute()+"/recycle", "") if err != nil { return BuildResponse(r), err } @@ -3769,7 +3769,7 @@ func (c *Client4) DatabaseRecycle() (*Response, error) { // InvalidateCaches will purge the cache and can affect the performance while is cleaning. func (c *Client4) InvalidateCaches() (*Response, error) { - r, err := c.DoApiPost(c.cacheRoute()+"/invalidate", "") + r, err := c.DoAPIPost(c.cacheRoute()+"/invalidate", "") if err != nil { return BuildResponse(r), err } @@ -3783,7 +3783,7 @@ func (c *Client4) UpdateConfig(config *Config) (*Config, *Response, error) { if err != nil { return nil, nil, NewAppError("UpdateConfig", "api.marshal_error", nil, err.Error(), http.StatusInternalServerError) } - r, err := c.doApiPutBytes(c.configRoute(), buf) + r, err := c.DoAPIPutBytes(c.configRoute(), buf) if err != nil { return nil, BuildResponse(r), err } @@ -3796,7 +3796,7 @@ func (c *Client4) MigrateConfig(from, to string) (*Response, error) { m := make(map[string]string, 2) m["from"] = from m["to"] = to - r, err := c.DoApiPost(c.configRoute()+"/migrate", MapToJson(m)) + r, err := c.DoAPIPost(c.configRoute()+"/migrate", MapToJson(m)) if err != nil { return BuildResponse(r), err } @@ -3822,7 +3822,7 @@ func (c *Client4) UploadLicenseFile(data []byte) (*Response, error) { return nil, NewAppError("UploadLicenseFile", "model.client.set_profile_user.writer.app_error", nil, err.Error(), http.StatusBadRequest) } - rq, err := http.NewRequest("POST", c.ApiUrl+c.licenseRoute(), bytes.NewReader(body.Bytes())) + rq, err := http.NewRequest("POST", c.APIURL+c.licenseRoute(), bytes.NewReader(body.Bytes())) if err != nil { return nil, err } @@ -3848,7 +3848,7 @@ func (c *Client4) UploadLicenseFile(data []byte) (*Response, error) { // RemoveLicenseFile will remove the server license it exists. Note that this will // disable all enterprise features. func (c *Client4) RemoveLicenseFile() (*Response, error) { - r, err := c.DoApiDelete(c.licenseRoute()) + r, err := c.DoAPIDelete(c.licenseRoute()) if err != nil { return BuildResponse(r), err } @@ -3862,7 +3862,7 @@ func (c *Client4) RemoveLicenseFile() (*Response, error) { // to a specific team. func (c *Client4) GetAnalyticsOld(name, teamId string) (AnalyticsRows, *Response, error) { query := fmt.Sprintf("?name=%v&team_id=%v", name, teamId) - r, err := c.DoApiGet(c.analyticsRoute()+"/old"+query, "") + r, err := c.DoAPIGet(c.analyticsRoute()+"/old"+query, "") if err != nil { return nil, BuildResponse(r), err } @@ -3884,7 +3884,7 @@ func (c *Client4) CreateIncomingWebhook(hook *IncomingWebhook) (*IncomingWebhook if err != nil { return nil, nil, NewAppError("CreateIncomingWebhook", "api.marshal_error", nil, err.Error(), http.StatusInternalServerError) } - r, err := c.doApiPostBytes(c.incomingWebhooksRoute(), buf) + r, err := c.DoAPIPostBytes(c.incomingWebhooksRoute(), buf) if err != nil { return nil, BuildResponse(r), err } @@ -3898,7 +3898,7 @@ func (c *Client4) UpdateIncomingWebhook(hook *IncomingWebhook) (*IncomingWebhook if err != nil { return nil, nil, NewAppError("UpdateIncomingWebhook", "api.marshal_error", nil, err.Error(), http.StatusInternalServerError) } - r, err := c.doApiPutBytes(c.incomingWebhookRoute(hook.Id), buf) + r, err := c.DoAPIPutBytes(c.incomingWebhookRoute(hook.Id), buf) if err != nil { return nil, BuildResponse(r), err } @@ -3909,7 +3909,7 @@ func (c *Client4) UpdateIncomingWebhook(hook *IncomingWebhook) (*IncomingWebhook // GetIncomingWebhooks returns a page of incoming webhooks on the system. Page counting starts at 0. func (c *Client4) GetIncomingWebhooks(page int, perPage int, etag string) ([]*IncomingWebhook, *Response, error) { query := fmt.Sprintf("?page=%v&per_page=%v", page, perPage) - r, err := c.DoApiGet(c.incomingWebhooksRoute()+query, etag) + r, err := c.DoAPIGet(c.incomingWebhooksRoute()+query, etag) if err != nil { return nil, BuildResponse(r), err } @@ -3920,7 +3920,7 @@ func (c *Client4) GetIncomingWebhooks(page int, perPage int, etag string) ([]*In // GetIncomingWebhooksForTeam returns a page of incoming webhooks for a team. Page counting starts at 0. func (c *Client4) GetIncomingWebhooksForTeam(teamId string, page int, perPage int, etag string) ([]*IncomingWebhook, *Response, error) { query := fmt.Sprintf("?page=%v&per_page=%v&team_id=%v", page, perPage, teamId) - r, err := c.DoApiGet(c.incomingWebhooksRoute()+query, etag) + r, err := c.DoAPIGet(c.incomingWebhooksRoute()+query, etag) if err != nil { return nil, BuildResponse(r), err } @@ -3930,7 +3930,7 @@ func (c *Client4) GetIncomingWebhooksForTeam(teamId string, page int, perPage in // GetIncomingWebhook returns an Incoming webhook given the hook ID. func (c *Client4) GetIncomingWebhook(hookID string, etag string) (*IncomingWebhook, *Response, error) { - r, err := c.DoApiGet(c.incomingWebhookRoute(hookID), etag) + r, err := c.DoAPIGet(c.incomingWebhookRoute(hookID), etag) if err != nil { return nil, BuildResponse(r), err } @@ -3940,7 +3940,7 @@ func (c *Client4) GetIncomingWebhook(hookID string, etag string) (*IncomingWebho // DeleteIncomingWebhook deletes and Incoming Webhook given the hook ID. func (c *Client4) DeleteIncomingWebhook(hookID string) (*Response, error) { - r, err := c.DoApiDelete(c.incomingWebhookRoute(hookID)) + r, err := c.DoAPIDelete(c.incomingWebhookRoute(hookID)) if err != nil { return BuildResponse(r), err } @@ -3954,7 +3954,7 @@ func (c *Client4) CreateOutgoingWebhook(hook *OutgoingWebhook) (*OutgoingWebhook if err != nil { return nil, nil, NewAppError("CreateOutgoingWebhook", "api.marshal_error", nil, err.Error(), http.StatusInternalServerError) } - r, err := c.doApiPostBytes(c.outgoingWebhooksRoute(), buf) + r, err := c.DoAPIPostBytes(c.outgoingWebhooksRoute(), buf) if err != nil { return nil, BuildResponse(r), err } @@ -3968,7 +3968,7 @@ func (c *Client4) UpdateOutgoingWebhook(hook *OutgoingWebhook) (*OutgoingWebhook if err != nil { return nil, nil, NewAppError("UpdateOutgoingWebhook", "api.marshal_error", nil, err.Error(), http.StatusInternalServerError) } - r, err := c.doApiPutBytes(c.outgoingWebhookRoute(hook.Id), buf) + r, err := c.DoAPIPutBytes(c.outgoingWebhookRoute(hook.Id), buf) if err != nil { return nil, BuildResponse(r), err } @@ -3979,7 +3979,7 @@ func (c *Client4) UpdateOutgoingWebhook(hook *OutgoingWebhook) (*OutgoingWebhook // GetOutgoingWebhooks returns a page of outgoing webhooks on the system. Page counting starts at 0. func (c *Client4) GetOutgoingWebhooks(page int, perPage int, etag string) ([]*OutgoingWebhook, *Response, error) { query := fmt.Sprintf("?page=%v&per_page=%v", page, perPage) - r, err := c.DoApiGet(c.outgoingWebhooksRoute()+query, etag) + r, err := c.DoAPIGet(c.outgoingWebhooksRoute()+query, etag) if err != nil { return nil, BuildResponse(r), err } @@ -3989,7 +3989,7 @@ func (c *Client4) GetOutgoingWebhooks(page int, perPage int, etag string) ([]*Ou // GetOutgoingWebhook outgoing webhooks on the system requested by Hook Id. func (c *Client4) GetOutgoingWebhook(hookId string) (*OutgoingWebhook, *Response, error) { - r, err := c.DoApiGet(c.outgoingWebhookRoute(hookId), "") + r, err := c.DoAPIGet(c.outgoingWebhookRoute(hookId), "") if err != nil { return nil, BuildResponse(r), err } @@ -4000,7 +4000,7 @@ func (c *Client4) GetOutgoingWebhook(hookId string) (*OutgoingWebhook, *Response // GetOutgoingWebhooksForChannel returns a page of outgoing webhooks for a channel. Page counting starts at 0. func (c *Client4) GetOutgoingWebhooksForChannel(channelId string, page int, perPage int, etag string) ([]*OutgoingWebhook, *Response, error) { query := fmt.Sprintf("?page=%v&per_page=%v&channel_id=%v", page, perPage, channelId) - r, err := c.DoApiGet(c.outgoingWebhooksRoute()+query, etag) + r, err := c.DoAPIGet(c.outgoingWebhooksRoute()+query, etag) if err != nil { return nil, BuildResponse(r), err } @@ -4011,7 +4011,7 @@ func (c *Client4) GetOutgoingWebhooksForChannel(channelId string, page int, perP // GetOutgoingWebhooksForTeam returns a page of outgoing webhooks for a team. Page counting starts at 0. func (c *Client4) GetOutgoingWebhooksForTeam(teamId string, page int, perPage int, etag string) ([]*OutgoingWebhook, *Response, error) { query := fmt.Sprintf("?page=%v&per_page=%v&team_id=%v", page, perPage, teamId) - r, err := c.DoApiGet(c.outgoingWebhooksRoute()+query, etag) + r, err := c.DoAPIGet(c.outgoingWebhooksRoute()+query, etag) if err != nil { return nil, BuildResponse(r), err } @@ -4021,7 +4021,7 @@ func (c *Client4) GetOutgoingWebhooksForTeam(teamId string, page int, perPage in // RegenOutgoingHookToken regenerate the outgoing webhook token. func (c *Client4) RegenOutgoingHookToken(hookId string) (*OutgoingWebhook, *Response, error) { - r, err := c.DoApiPost(c.outgoingWebhookRoute(hookId)+"/regen_token", "") + r, err := c.DoAPIPost(c.outgoingWebhookRoute(hookId)+"/regen_token", "") if err != nil { return nil, BuildResponse(r), err } @@ -4031,7 +4031,7 @@ func (c *Client4) RegenOutgoingHookToken(hookId string) (*OutgoingWebhook, *Resp // DeleteOutgoingWebhook delete the outgoing webhook on the system requested by Hook Id. func (c *Client4) DeleteOutgoingWebhook(hookId string) (*Response, error) { - r, err := c.DoApiDelete(c.outgoingWebhookRoute(hookId)) + r, err := c.DoAPIDelete(c.outgoingWebhookRoute(hookId)) if err != nil { return BuildResponse(r), err } @@ -4043,7 +4043,7 @@ func (c *Client4) DeleteOutgoingWebhook(hookId string) (*Response, error) { // GetPreferences returns the user's preferences. func (c *Client4) GetPreferences(userId string) (Preferences, *Response, error) { - r, err := c.DoApiGet(c.preferencesRoute(userId), "") + r, err := c.DoAPIGet(c.preferencesRoute(userId), "") if err != nil { return nil, BuildResponse(r), err } @@ -4058,7 +4058,7 @@ func (c *Client4) UpdatePreferences(userId string, preferences *Preferences) (*R if err != nil { return nil, NewAppError("UpdatePreferences", "api.marshal_error", nil, err.Error(), http.StatusInternalServerError) } - r, err := c.doApiPutBytes(c.preferencesRoute(userId), buf) + r, err := c.DoAPIPutBytes(c.preferencesRoute(userId), buf) if err != nil { return BuildResponse(r), err } @@ -4072,7 +4072,7 @@ func (c *Client4) DeletePreferences(userId string, preferences *Preferences) (*R if err != nil { return nil, NewAppError("DeletePreferences", "api.marshal_error", nil, err.Error(), http.StatusInternalServerError) } - r, err := c.doApiPostBytes(c.preferencesRoute(userId)+"/delete", buf) + r, err := c.DoAPIPostBytes(c.preferencesRoute(userId)+"/delete", buf) if err != nil { return BuildResponse(r), err } @@ -4083,7 +4083,7 @@ func (c *Client4) DeletePreferences(userId string, preferences *Preferences) (*R // GetPreferencesByCategory returns the user's preferences from the provided category string. func (c *Client4) GetPreferencesByCategory(userId string, category string) (Preferences, *Response, error) { url := fmt.Sprintf(c.preferencesRoute(userId)+"/%s", category) - r, err := c.DoApiGet(url, "") + r, err := c.DoAPIGet(url, "") if err != nil { return nil, BuildResponse(r), err } @@ -4095,7 +4095,7 @@ func (c *Client4) GetPreferencesByCategory(userId string, category string) (Pref // GetPreferenceByCategoryAndName returns the user's preferences from the provided category and preference name string. func (c *Client4) GetPreferenceByCategoryAndName(userId string, category string, preferenceName string) (*Preference, *Response, error) { url := fmt.Sprintf(c.preferencesRoute(userId)+"/%s/name/%v", category, preferenceName) - r, err := c.DoApiGet(url, "") + r, err := c.DoAPIGet(url, "") if err != nil { return nil, BuildResponse(r), err } @@ -4107,7 +4107,7 @@ func (c *Client4) GetPreferenceByCategoryAndName(userId string, category string, // GetSamlMetadata returns metadata for the SAML configuration. func (c *Client4) GetSamlMetadata() (string, *Response, error) { - r, err := c.DoApiGet(c.samlRoute()+"/metadata", "") + r, err := c.DoAPIGet(c.samlRoute()+"/metadata", "") if err != nil { return "", BuildResponse(r), err } @@ -4180,7 +4180,7 @@ func (c *Client4) UploadSamlPrivateCertificate(data []byte, filename string) (*R // DeleteSamlIdpCertificate deletes the SAML IDP certificate from the server and updates the config to not use it and disable SAML. func (c *Client4) DeleteSamlIdpCertificate() (*Response, error) { - r, err := c.DoApiDelete(c.samlRoute() + "/certificate/idp") + r, err := c.DoAPIDelete(c.samlRoute() + "/certificate/idp") if err != nil { return BuildResponse(r), err } @@ -4190,7 +4190,7 @@ func (c *Client4) DeleteSamlIdpCertificate() (*Response, error) { // DeleteSamlPublicCertificate deletes the SAML IDP certificate from the server and updates the config to not use it and disable SAML. func (c *Client4) DeleteSamlPublicCertificate() (*Response, error) { - r, err := c.DoApiDelete(c.samlRoute() + "/certificate/public") + r, err := c.DoAPIDelete(c.samlRoute() + "/certificate/public") if err != nil { return BuildResponse(r), err } @@ -4200,7 +4200,7 @@ func (c *Client4) DeleteSamlPublicCertificate() (*Response, error) { // DeleteSamlPrivateCertificate deletes the SAML IDP certificate from the server and updates the config to not use it and disable SAML. func (c *Client4) DeleteSamlPrivateCertificate() (*Response, error) { - r, err := c.DoApiDelete(c.samlRoute() + "/certificate/private") + r, err := c.DoAPIDelete(c.samlRoute() + "/certificate/private") if err != nil { return BuildResponse(r), err } @@ -4210,7 +4210,7 @@ func (c *Client4) DeleteSamlPrivateCertificate() (*Response, error) { // GetSamlCertificateStatus returns metadata for the SAML configuration. func (c *Client4) GetSamlCertificateStatus() (*SamlCertificateStatus, *Response, error) { - r, err := c.DoApiGet(c.samlRoute()+"/certificate/status", "") + r, err := c.DoAPIGet(c.samlRoute()+"/certificate/status", "") if err != nil { return nil, BuildResponse(r), err } @@ -4221,7 +4221,7 @@ func (c *Client4) GetSamlCertificateStatus() (*SamlCertificateStatus, *Response, func (c *Client4) GetSamlMetadataFromIdp(samlMetadataURL string) (*SamlMetadataResponse, *Response, error) { requestBody := make(map[string]string) requestBody["saml_metadata_url"] = samlMetadataURL - r, err := c.DoApiPost(c.samlRoute()+"/metadatafromidp", MapToJson(requestBody)) + r, err := c.DoAPIPost(c.samlRoute()+"/metadatafromidp", MapToJson(requestBody)) if err != nil { return nil, BuildResponse(r), err } @@ -4238,7 +4238,7 @@ func (c *Client4) ResetSamlAuthDataToEmail(includeDeleted bool, dryRun bool, use "user_ids": userIDs, } b, _ := json.Marshal(params) - r, err := c.doApiPostBytes(c.samlRoute()+"/reset_auth_data", b) + r, err := c.DoAPIPostBytes(c.samlRoute()+"/reset_auth_data", b) if err != nil { return 0, BuildResponse(r), err } @@ -4259,7 +4259,7 @@ func (c *Client4) CreateComplianceReport(report *Compliance) (*Compliance, *Resp if err != nil { return nil, nil, NewAppError("CreateComplianceReport", "api.marshal_error", nil, err.Error(), http.StatusInternalServerError) } - r, err := c.doApiPostBytes(c.complianceReportsRoute(), buf) + r, err := c.DoAPIPostBytes(c.complianceReportsRoute(), buf) if err != nil { return nil, BuildResponse(r), err } @@ -4270,7 +4270,7 @@ func (c *Client4) CreateComplianceReport(report *Compliance) (*Compliance, *Resp // GetComplianceReports returns list of compliance reports. func (c *Client4) GetComplianceReports(page, perPage int) (Compliances, *Response, error) { query := fmt.Sprintf("?page=%v&per_page=%v", page, perPage) - r, err := c.DoApiGet(c.complianceReportsRoute()+query, "") + r, err := c.DoAPIGet(c.complianceReportsRoute()+query, "") if err != nil { return nil, BuildResponse(r), err } @@ -4280,7 +4280,7 @@ func (c *Client4) GetComplianceReports(page, perPage int) (Compliances, *Respons // GetComplianceReport returns a compliance report. func (c *Client4) GetComplianceReport(reportId string) (*Compliance, *Response, error) { - r, err := c.DoApiGet(c.complianceReportRoute(reportId), "") + r, err := c.DoAPIGet(c.complianceReportRoute(reportId), "") if err != nil { return nil, BuildResponse(r), err } @@ -4290,7 +4290,7 @@ func (c *Client4) GetComplianceReport(reportId string) (*Compliance, *Response, // DownloadComplianceReport returns a full compliance report as a file. func (c *Client4) DownloadComplianceReport(reportId string) ([]byte, *Response, error) { - rq, err := http.NewRequest("GET", c.ApiUrl+c.complianceReportDownloadRoute(reportId), nil) + rq, err := http.NewRequest("GET", c.APIURL+c.complianceReportDownloadRoute(reportId), nil) if err != nil { return nil, nil, err } @@ -4321,7 +4321,7 @@ func (c *Client4) DownloadComplianceReport(reportId string) ([]byte, *Response, // GetClusterStatus returns the status of all the configured cluster nodes. func (c *Client4) GetClusterStatus() ([]*ClusterInfo, *Response, error) { - r, err := c.DoApiGet(c.clusterRoute()+"/status", "") + r, err := c.DoAPIGet(c.clusterRoute()+"/status", "") if err != nil { return nil, BuildResponse(r), err } @@ -4338,7 +4338,7 @@ func (c *Client4) SyncLdap(includeRemovedMembers bool) (*Response, error) { reqBody, _ := json.Marshal(map[string]interface{}{ "include_removed_members": includeRemovedMembers, }) - r, err := c.doApiPostBytes(c.ldapRoute()+"/sync", reqBody) + r, err := c.DoAPIPostBytes(c.ldapRoute()+"/sync", reqBody) if err != nil { return BuildResponse(r), err } @@ -4349,7 +4349,7 @@ func (c *Client4) SyncLdap(includeRemovedMembers bool) (*Response, error) { // TestLdap will attempt to connect to the configured LDAP server and return OK if configured // correctly. func (c *Client4) TestLdap() (*Response, error) { - r, err := c.DoApiPost(c.ldapRoute()+"/test", "") + r, err := c.DoAPIPost(c.ldapRoute()+"/test", "") if err != nil { return BuildResponse(r), err } @@ -4361,7 +4361,7 @@ func (c *Client4) TestLdap() (*Response, error) { func (c *Client4) GetLdapGroups() ([]*Group, *Response, error) { path := fmt.Sprintf("%s/groups", c.ldapRoute()) - r, err := c.DoApiGet(path, "") + r, err := c.DoAPIGet(path, "") if err != nil { return nil, BuildResponse(r), err } @@ -4385,7 +4385,7 @@ func (c *Client4) GetLdapGroups() ([]*Group, *Response, error) { func (c *Client4) LinkLdapGroup(dn string) (*Group, *Response, error) { path := fmt.Sprintf("%s/groups/%s/link", c.ldapRoute(), dn) - r, err := c.DoApiPost(path, "") + r, err := c.DoAPIPost(path, "") if err != nil { return nil, BuildResponse(r), err } @@ -4398,7 +4398,7 @@ func (c *Client4) LinkLdapGroup(dn string) (*Group, *Response, error) { func (c *Client4) UnlinkLdapGroup(dn string) (*Group, *Response, error) { path := fmt.Sprintf("%s/groups/%s/link", c.ldapRoute(), dn) - r, err := c.DoApiDelete(path) + r, err := c.DoAPIDelete(path) if err != nil { return nil, BuildResponse(r), err } @@ -4409,7 +4409,7 @@ func (c *Client4) UnlinkLdapGroup(dn string) (*Group, *Response, error) { // MigrateIdLdap migrates the LDAP enabled users to given attribute func (c *Client4) MigrateIdLdap(toAttribute string) (*Response, error) { - r, err := c.DoApiPost(c.ldapRoute()+"/migrateid", MapToJson(map[string]string{ + r, err := c.DoAPIPost(c.ldapRoute()+"/migrateid", MapToJson(map[string]string{ "toAttribute": toAttribute, })) if err != nil { @@ -4425,7 +4425,7 @@ func (c *Client4) GetGroupsByChannel(channelId string, opts GroupSearchOpts) ([] if opts.PageOpts != nil { path = fmt.Sprintf("%s&page=%v&per_page=%v", path, opts.PageOpts.Page, opts.PageOpts.PerPage) } - r, err := c.DoApiGet(path, "") + r, err := c.DoAPIGet(path, "") if err != nil { return nil, 0, BuildResponse(r), err } @@ -4448,7 +4448,7 @@ func (c *Client4) GetGroupsByTeam(teamId string, opts GroupSearchOpts) ([]*Group if opts.PageOpts != nil { path = fmt.Sprintf("%s&page=%v&per_page=%v", path, opts.PageOpts.Page, opts.PageOpts.PerPage) } - r, err := c.DoApiGet(path, "") + r, err := c.DoAPIGet(path, "") if err != nil { return nil, 0, BuildResponse(r), err } @@ -4471,7 +4471,7 @@ func (c *Client4) GetGroupsAssociatedToChannelsByTeam(teamId string, opts GroupS if opts.PageOpts != nil { path = fmt.Sprintf("%s&page=%v&per_page=%v", path, opts.PageOpts.Page, opts.PageOpts.PerPage) } - r, err := c.DoApiGet(path, "") + r, err := c.DoAPIGet(path, "") if err != nil { return nil, BuildResponse(r), err } @@ -4505,7 +4505,7 @@ func (c *Client4) GetGroups(opts GroupSearchOpts) ([]*Group, *Response, error) { if opts.PageOpts != nil { path = fmt.Sprintf("%s&page=%v&per_page=%v", path, opts.PageOpts.Page, opts.PageOpts.PerPage) } - r, err := c.DoApiGet(path, "") + r, err := c.DoAPIGet(path, "") if err != nil { return nil, BuildResponse(r), err } @@ -4522,7 +4522,7 @@ func (c *Client4) GetGroupsByUserId(userId string) ([]*Group, *Response, error) userId, ) - r, err := c.DoApiGet(path, "") + r, err := c.DoAPIGet(path, "") if err != nil { return nil, BuildResponse(r), err } @@ -4531,7 +4531,7 @@ func (c *Client4) GetGroupsByUserId(userId string) ([]*Group, *Response, error) } func (c *Client4) MigrateAuthToLdap(fromAuthService string, matchField string, force bool) (*Response, error) { - r, err := c.DoApiPost(c.usersRoute()+"/migrate_auth/ldap", StringInterfaceToJson(map[string]interface{}{ + r, err := c.DoAPIPost(c.usersRoute()+"/migrate_auth/ldap", StringInterfaceToJson(map[string]interface{}{ "from": fromAuthService, "force": force, "match_field": matchField, @@ -4544,7 +4544,7 @@ func (c *Client4) MigrateAuthToLdap(fromAuthService string, matchField string, f } func (c *Client4) MigrateAuthToSaml(fromAuthService string, usersMap map[string]string, auto bool) (*Response, error) { - r, err := c.DoApiPost(c.usersRoute()+"/migrate_auth/saml", StringInterfaceToJson(map[string]interface{}{ + r, err := c.DoAPIPost(c.usersRoute()+"/migrate_auth/saml", StringInterfaceToJson(map[string]interface{}{ "from": fromAuthService, "auto": auto, "matches": usersMap, @@ -4580,7 +4580,7 @@ func (c *Client4) UploadLdapPrivateCertificate(data []byte) (*Response, error) { // DeleteLdapPublicCertificate deletes the LDAP IDP certificate from the server and updates the config to not use it and disable LDAP. func (c *Client4) DeleteLdapPublicCertificate() (*Response, error) { - r, err := c.DoApiDelete(c.ldapRoute() + "/certificate/public") + r, err := c.DoAPIDelete(c.ldapRoute() + "/certificate/public") if err != nil { return BuildResponse(r), err } @@ -4590,7 +4590,7 @@ func (c *Client4) DeleteLdapPublicCertificate() (*Response, error) { // DeleteLDAPPrivateCertificate deletes the LDAP IDP certificate from the server and updates the config to not use it and disable LDAP. func (c *Client4) DeleteLdapPrivateCertificate() (*Response, error) { - r, err := c.DoApiDelete(c.ldapRoute() + "/certificate/private") + r, err := c.DoAPIDelete(c.ldapRoute() + "/certificate/private") if err != nil { return BuildResponse(r), err } @@ -4603,7 +4603,7 @@ func (c *Client4) DeleteLdapPrivateCertificate() (*Response, error) { // GetAudits returns a list of audits for the whole system. func (c *Client4) GetAudits(page int, perPage int, etag string) (Audits, *Response, error) { query := fmt.Sprintf("?page=%v&per_page=%v", page, perPage) - r, err := c.DoApiGet("/audits"+query, etag) + r, err := c.DoAPIGet("/audits"+query, etag) if err != nil { return nil, BuildResponse(r), err } @@ -4621,7 +4621,7 @@ func (c *Client4) GetAudits(page int, perPage int, etag string) (Audits, *Respon // GetBrandImage retrieves the previously uploaded brand image. func (c *Client4) GetBrandImage() ([]byte, *Response, error) { - r, err := c.DoApiGet(c.brandRoute()+"/image", "") + r, err := c.DoAPIGet(c.brandRoute()+"/image", "") if err != nil { return nil, BuildResponse(r), err } @@ -4641,7 +4641,7 @@ func (c *Client4) GetBrandImage() ([]byte, *Response, error) { // DeleteBrandImage deletes the brand image for the system. func (c *Client4) DeleteBrandImage() (*Response, error) { - r, err := c.DoApiDelete(c.brandRoute() + "/image") + r, err := c.DoAPIDelete(c.brandRoute() + "/image") if err != nil { return BuildResponse(r), err } @@ -4666,7 +4666,7 @@ func (c *Client4) UploadBrandImage(data []byte) (*Response, error) { return nil, NewAppError("UploadBrandImage", "model.client.set_profile_user.writer.app_error", nil, err.Error(), http.StatusBadRequest) } - rq, err := http.NewRequest("POST", c.ApiUrl+c.brandRoute()+"/image", bytes.NewReader(body.Bytes())) + rq, err := http.NewRequest("POST", c.APIURL+c.brandRoute()+"/image", bytes.NewReader(body.Bytes())) if err != nil { return nil, err } @@ -4694,7 +4694,7 @@ func (c *Client4) UploadBrandImage(data []byte) (*Response, error) { // GetLogs page of logs as a string array. func (c *Client4) GetLogs(page, perPage int) ([]string, *Response, error) { query := fmt.Sprintf("?page=%v&logs_per_page=%v", page, perPage) - r, err := c.DoApiGet("/logs"+query, "") + r, err := c.DoAPIGet("/logs"+query, "") if err != nil { return nil, BuildResponse(r), err } @@ -4706,7 +4706,7 @@ func (c *Client4) GetLogs(page, perPage int) ([]string, *Response, error) { // the server-side logs. For example we typically log javascript error messages // into the server-side. It returns the log message if the logging was successful. func (c *Client4) PostLog(message map[string]string) (map[string]string, *Response, error) { - r, err := c.DoApiPost("/logs", MapToJson(message)) + r, err := c.DoAPIPost("/logs", MapToJson(message)) if err != nil { return nil, BuildResponse(r), err } @@ -4722,7 +4722,7 @@ func (c *Client4) CreateOAuthApp(app *OAuthApp) (*OAuthApp, *Response, error) { if err != nil { return nil, nil, NewAppError("CreateOAuthApp", "api.marshal_error", nil, err.Error(), http.StatusInternalServerError) } - r, err := c.doApiPostBytes(c.oAuthAppsRoute(), buf) + r, err := c.DoAPIPostBytes(c.oAuthAppsRoute(), buf) if err != nil { return nil, BuildResponse(r), err } @@ -4736,7 +4736,7 @@ func (c *Client4) UpdateOAuthApp(app *OAuthApp) (*OAuthApp, *Response, error) { if err != nil { return nil, nil, NewAppError("UpdateOAuthApp", "api.marshal_error", nil, err.Error(), http.StatusInternalServerError) } - r, err := c.doApiPutBytes(c.oAuthAppRoute(app.Id), buf) + r, err := c.DoAPIPutBytes(c.oAuthAppRoute(app.Id), buf) if err != nil { return nil, BuildResponse(r), err } @@ -4747,7 +4747,7 @@ func (c *Client4) UpdateOAuthApp(app *OAuthApp) (*OAuthApp, *Response, error) { // GetOAuthApps gets a page of registered OAuth 2.0 client applications with Mattermost acting as an OAuth 2.0 service provider. func (c *Client4) GetOAuthApps(page, perPage int) ([]*OAuthApp, *Response, error) { query := fmt.Sprintf("?page=%v&per_page=%v", page, perPage) - r, err := c.DoApiGet(c.oAuthAppsRoute()+query, "") + r, err := c.DoAPIGet(c.oAuthAppsRoute()+query, "") if err != nil { return nil, BuildResponse(r), err } @@ -4757,7 +4757,7 @@ func (c *Client4) GetOAuthApps(page, perPage int) ([]*OAuthApp, *Response, error // GetOAuthApp gets a registered OAuth 2.0 client application with Mattermost acting as an OAuth 2.0 service provider. func (c *Client4) GetOAuthApp(appId string) (*OAuthApp, *Response, error) { - r, err := c.DoApiGet(c.oAuthAppRoute(appId), "") + r, err := c.DoAPIGet(c.oAuthAppRoute(appId), "") if err != nil { return nil, BuildResponse(r), err } @@ -4767,7 +4767,7 @@ func (c *Client4) GetOAuthApp(appId string) (*OAuthApp, *Response, error) { // GetOAuthAppInfo gets a sanitized version of a registered OAuth 2.0 client application with Mattermost acting as an OAuth 2.0 service provider. func (c *Client4) GetOAuthAppInfo(appId string) (*OAuthApp, *Response, error) { - r, err := c.DoApiGet(c.oAuthAppRoute(appId)+"/info", "") + r, err := c.DoAPIGet(c.oAuthAppRoute(appId)+"/info", "") if err != nil { return nil, BuildResponse(r), err } @@ -4777,7 +4777,7 @@ func (c *Client4) GetOAuthAppInfo(appId string) (*OAuthApp, *Response, error) { // DeleteOAuthApp deletes a registered OAuth 2.0 client application. func (c *Client4) DeleteOAuthApp(appId string) (*Response, error) { - r, err := c.DoApiDelete(c.oAuthAppRoute(appId)) + r, err := c.DoAPIDelete(c.oAuthAppRoute(appId)) if err != nil { return BuildResponse(r), err } @@ -4787,7 +4787,7 @@ func (c *Client4) DeleteOAuthApp(appId string) (*Response, error) { // RegenerateOAuthAppSecret regenerates the client secret for a registered OAuth 2.0 client application. func (c *Client4) RegenerateOAuthAppSecret(appId string) (*OAuthApp, *Response, error) { - r, err := c.DoApiPost(c.oAuthAppRoute(appId)+"/regen_secret", "") + r, err := c.DoAPIPost(c.oAuthAppRoute(appId)+"/regen_secret", "") if err != nil { return nil, BuildResponse(r), err } @@ -4798,7 +4798,7 @@ func (c *Client4) RegenerateOAuthAppSecret(appId string) (*OAuthApp, *Response, // GetAuthorizedOAuthAppsForUser gets a page of OAuth 2.0 client applications the user has authorized to use access their account. func (c *Client4) GetAuthorizedOAuthAppsForUser(userId string, page, perPage int) ([]*OAuthApp, *Response, error) { query := fmt.Sprintf("?page=%v&per_page=%v", page, perPage) - r, err := c.DoApiGet(c.userRoute(userId)+"/oauth/apps/authorized"+query, "") + r, err := c.DoAPIGet(c.userRoute(userId)+"/oauth/apps/authorized"+query, "") if err != nil { return nil, BuildResponse(r), err } @@ -4812,7 +4812,7 @@ func (c *Client4) AuthorizeOAuthApp(authRequest *AuthorizeRequest) (string, *Res if err != nil { return "", BuildResponse(nil), NewAppError("AuthorizeOAuthApp", "api.marshal_error", nil, err.Error(), http.StatusInternalServerError) } - r, err := c.doApiRequestBytes(http.MethodPost, c.Url+"/oauth/authorize", buf, "") + r, err := c.DoAPIRequestBytes(http.MethodPost, c.URL+"/oauth/authorize", buf, "") if err != nil { return "", BuildResponse(r), err } @@ -4823,7 +4823,7 @@ func (c *Client4) AuthorizeOAuthApp(authRequest *AuthorizeRequest) (string, *Res // DeauthorizeOAuthApp will deauthorize an OAuth 2.0 client application from accessing a user's account. func (c *Client4) DeauthorizeOAuthApp(appId string) (*Response, error) { requestData := map[string]string{"client_id": appId} - r, err := c.DoApiRequest(http.MethodPost, c.Url+"/oauth/deauthorize", MapToJson(requestData), "") + r, err := c.DoAPIRequest(http.MethodPost, c.URL+"/oauth/deauthorize", MapToJson(requestData), "") if err != nil { return BuildResponse(r), err } @@ -4833,7 +4833,7 @@ func (c *Client4) DeauthorizeOAuthApp(appId string) (*Response, error) { // GetOAuthAccessToken is a test helper function for the OAuth access token endpoint. func (c *Client4) GetOAuthAccessToken(data url.Values) (*AccessResponse, *Response, error) { - url := c.Url + "/oauth/access_token" + url := c.URL + "/oauth/access_token" rq, err := http.NewRequest(http.MethodPost, url, strings.NewReader(data.Encode())) if err != nil { return nil, nil, err @@ -4868,7 +4868,7 @@ func (c *Client4) GetOAuthAccessToken(data url.Values) (*AccessResponse, *Respon // TestElasticsearch will attempt to connect to the configured Elasticsearch server and return OK if configured. // correctly. func (c *Client4) TestElasticsearch() (*Response, error) { - r, err := c.DoApiPost(c.elasticsearchRoute()+"/test", "") + r, err := c.DoAPIPost(c.elasticsearchRoute()+"/test", "") if err != nil { return BuildResponse(r), err } @@ -4878,7 +4878,7 @@ func (c *Client4) TestElasticsearch() (*Response, error) { // PurgeElasticsearchIndexes immediately deletes all Elasticsearch indexes. func (c *Client4) PurgeElasticsearchIndexes() (*Response, error) { - r, err := c.DoApiPost(c.elasticsearchRoute()+"/purge_indexes", "") + r, err := c.DoAPIPost(c.elasticsearchRoute()+"/purge_indexes", "") if err != nil { return BuildResponse(r), err } @@ -4890,7 +4890,7 @@ func (c *Client4) PurgeElasticsearchIndexes() (*Response, error) { // PurgeBleveIndexes immediately deletes all Bleve indexes. func (c *Client4) PurgeBleveIndexes() (*Response, error) { - r, err := c.DoApiPost(c.bleveRoute()+"/purge_indexes", "") + r, err := c.DoAPIPost(c.bleveRoute()+"/purge_indexes", "") if err != nil { return BuildResponse(r), err } @@ -4902,7 +4902,7 @@ func (c *Client4) PurgeBleveIndexes() (*Response, error) { // GetDataRetentionPolicy will get the current global data retention policy details. func (c *Client4) GetDataRetentionPolicy() (*GlobalRetentionPolicy, *Response, error) { - r, err := c.DoApiGet(c.dataRetentionRoute()+"/policy", "") + r, err := c.DoAPIGet(c.dataRetentionRoute()+"/policy", "") if err != nil { return nil, BuildResponse(r), err } @@ -4912,7 +4912,7 @@ func (c *Client4) GetDataRetentionPolicy() (*GlobalRetentionPolicy, *Response, e // GetDataRetentionPolicyByID will get the details for the granular data retention policy with the specified ID. func (c *Client4) GetDataRetentionPolicyByID(policyID string) (*RetentionPolicyWithTeamAndChannelCounts, *Response, error) { - r, err := c.DoApiGet(c.dataRetentionPolicyRoute(policyID), "") + r, err := c.DoAPIGet(c.dataRetentionPolicyRoute(policyID), "") if err != nil { return nil, BuildResponse(r), err } @@ -4929,7 +4929,7 @@ func (c *Client4) GetDataRetentionPoliciesCount() (int64, *Response, error) { type CountBody struct { TotalCount int64 `json:"total_count"` } - r, err := c.DoApiGet(c.dataRetentionRoute()+"/policies_count", "") + r, err := c.DoAPIGet(c.dataRetentionRoute()+"/policies_count", "") if err != nil { return 0, BuildResponse(r), err } @@ -4944,7 +4944,7 @@ func (c *Client4) GetDataRetentionPoliciesCount() (int64, *Response, error) { // GetDataRetentionPolicies will get the current granular data retention policies' details. func (c *Client4) GetDataRetentionPolicies(page, perPage int) (*RetentionPolicyWithTeamAndChannelCountsList, *Response, error) { query := fmt.Sprintf("?page=%d&per_page=%d", page, perPage) - r, err := c.DoApiGet(c.dataRetentionRoute()+"/policies"+query, "") + r, err := c.DoAPIGet(c.dataRetentionRoute()+"/policies"+query, "") if err != nil { return nil, BuildResponse(r), err } @@ -4959,7 +4959,7 @@ func (c *Client4) GetDataRetentionPolicies(page, perPage int) (*RetentionPolicyW // CreateDataRetentionPolicy will create a new granular data retention policy which will be applied to // the specified teams and channels. The Id field of `policy` must be empty. func (c *Client4) CreateDataRetentionPolicy(policy *RetentionPolicyWithTeamAndChannelIDs) (*RetentionPolicyWithTeamAndChannelCounts, *Response, error) { - r, err := c.doApiPostBytes(c.dataRetentionRoute()+"/policies", policy.ToJson()) + r, err := c.DoAPIPostBytes(c.dataRetentionRoute()+"/policies", policy.ToJson()) if err != nil { return nil, BuildResponse(r), err } @@ -4973,7 +4973,7 @@ func (c *Client4) CreateDataRetentionPolicy(policy *RetentionPolicyWithTeamAndCh // DeleteDataRetentionPolicy will delete the granular data retention policy with the specified ID. func (c *Client4) DeleteDataRetentionPolicy(policyID string) (*Response, error) { - r, err := c.DoApiDelete(c.dataRetentionPolicyRoute(policyID)) + r, err := c.DoAPIDelete(c.dataRetentionPolicyRoute(policyID)) if err != nil { return BuildResponse(r), err } @@ -4984,7 +4984,7 @@ func (c *Client4) DeleteDataRetentionPolicy(policyID string) (*Response, error) // PatchDataRetentionPolicy will patch the granular data retention policy with the specified ID. // The Id field of `patch` must be non-empty. func (c *Client4) PatchDataRetentionPolicy(patch *RetentionPolicyWithTeamAndChannelIDs) (*RetentionPolicyWithTeamAndChannelCounts, *Response, error) { - r, err := c.doApiPatchBytes(c.dataRetentionPolicyRoute(patch.ID), patch.ToJson()) + r, err := c.DoAPIPatchBytes(c.dataRetentionPolicyRoute(patch.ID), patch.ToJson()) if err != nil { return nil, BuildResponse(r), err } @@ -4999,7 +4999,7 @@ func (c *Client4) PatchDataRetentionPolicy(patch *RetentionPolicyWithTeamAndChan // GetTeamsForRetentionPolicy will get the teams to which the specified policy is currently applied. func (c *Client4) GetTeamsForRetentionPolicy(policyID string, page, perPage int) (*TeamsWithCount, *Response, error) { query := fmt.Sprintf("?page=%d&per_page=%d", page, perPage) - r, err := c.DoApiGet(c.dataRetentionPolicyRoute(policyID)+"/teams"+query, "") + r, err := c.DoAPIGet(c.dataRetentionPolicyRoute(policyID)+"/teams"+query, "") if err != nil { return nil, BuildResponse(r), err } @@ -5014,7 +5014,7 @@ func (c *Client4) GetTeamsForRetentionPolicy(policyID string, page, perPage int) // SearchTeamsForRetentionPolicy will search the teams to which the specified policy is currently applied. func (c *Client4) SearchTeamsForRetentionPolicy(policyID string, term string) ([]*Team, *Response, error) { body, _ := json.Marshal(map[string]interface{}{"term": term}) - r, err := c.doApiPostBytes(c.dataRetentionPolicyRoute(policyID)+"/teams/search", body) + r, err := c.DoAPIPostBytes(c.dataRetentionPolicyRoute(policyID)+"/teams/search", body) if err != nil { return nil, BuildResponse(r), err } @@ -5030,7 +5030,7 @@ func (c *Client4) SearchTeamsForRetentionPolicy(policyID string, term string) ([ // with the specified ID. func (c *Client4) AddTeamsToRetentionPolicy(policyID string, teamIDs []string) (*Response, error) { body, _ := json.Marshal(teamIDs) - r, err := c.doApiPostBytes(c.dataRetentionPolicyRoute(policyID)+"/teams", body) + r, err := c.DoAPIPostBytes(c.dataRetentionPolicyRoute(policyID)+"/teams", body) if err != nil { return BuildResponse(r), err } @@ -5042,7 +5042,7 @@ func (c *Client4) AddTeamsToRetentionPolicy(policyID string, teamIDs []string) ( // with the specified ID. func (c *Client4) RemoveTeamsFromRetentionPolicy(policyID string, teamIDs []string) (*Response, error) { body, _ := json.Marshal(teamIDs) - r, err := c.doApiDeleteBytes(c.dataRetentionPolicyRoute(policyID)+"/teams", body) + r, err := c.DoAPIDeleteBytes(c.dataRetentionPolicyRoute(policyID)+"/teams", body) if err != nil { return BuildResponse(r), err } @@ -5053,7 +5053,7 @@ func (c *Client4) RemoveTeamsFromRetentionPolicy(policyID string, teamIDs []stri // GetChannelsForRetentionPolicy will get the channels to which the specified policy is currently applied. func (c *Client4) GetChannelsForRetentionPolicy(policyID string, page, perPage int) (*ChannelsWithCount, *Response, error) { query := fmt.Sprintf("?page=%d&per_page=%d", page, perPage) - r, err := c.DoApiGet(c.dataRetentionPolicyRoute(policyID)+"/channels"+query, "") + r, err := c.DoAPIGet(c.dataRetentionPolicyRoute(policyID)+"/channels"+query, "") if err != nil { return nil, BuildResponse(r), err } @@ -5068,7 +5068,7 @@ func (c *Client4) GetChannelsForRetentionPolicy(policyID string, page, perPage i // SearchChannelsForRetentionPolicy will search the channels to which the specified policy is currently applied. func (c *Client4) SearchChannelsForRetentionPolicy(policyID string, term string) (ChannelListWithTeamData, *Response, error) { body, _ := json.Marshal(map[string]interface{}{"term": term}) - r, err := c.doApiPostBytes(c.dataRetentionPolicyRoute(policyID)+"/channels/search", body) + r, err := c.DoAPIPostBytes(c.dataRetentionPolicyRoute(policyID)+"/channels/search", body) if err != nil { return nil, BuildResponse(r), err } @@ -5084,7 +5084,7 @@ func (c *Client4) SearchChannelsForRetentionPolicy(policyID string, term string) // with the specified ID. func (c *Client4) AddChannelsToRetentionPolicy(policyID string, channelIDs []string) (*Response, error) { body, _ := json.Marshal(channelIDs) - r, err := c.doApiPostBytes(c.dataRetentionPolicyRoute(policyID)+"/channels", body) + r, err := c.DoAPIPostBytes(c.dataRetentionPolicyRoute(policyID)+"/channels", body) if err != nil { return BuildResponse(r), err } @@ -5096,7 +5096,7 @@ func (c *Client4) AddChannelsToRetentionPolicy(policyID string, channelIDs []str // with the specified ID. func (c *Client4) RemoveChannelsFromRetentionPolicy(policyID string, channelIDs []string) (*Response, error) { body, _ := json.Marshal(channelIDs) - r, err := c.doApiDeleteBytes(c.dataRetentionPolicyRoute(policyID)+"/channels", body) + r, err := c.DoAPIDeleteBytes(c.dataRetentionPolicyRoute(policyID)+"/channels", body) if err != nil { return BuildResponse(r), err } @@ -5106,7 +5106,7 @@ func (c *Client4) RemoveChannelsFromRetentionPolicy(policyID string, channelIDs // GetTeamPoliciesForUser will get the data retention policies for the teams to which a user belongs. func (c *Client4) GetTeamPoliciesForUser(userID string, offset, limit int) (*RetentionPolicyForTeamList, *Response, error) { - r, err := c.DoApiGet(c.userRoute(userID)+"/data_retention/team_policies", "") + r, err := c.DoAPIGet(c.userRoute(userID)+"/data_retention/team_policies", "") if err != nil { return nil, BuildResponse(r), err } @@ -5120,7 +5120,7 @@ func (c *Client4) GetTeamPoliciesForUser(userID string, offset, limit int) (*Ret // GetChannelPoliciesForUser will get the data retention policies for the channels to which a user belongs. func (c *Client4) GetChannelPoliciesForUser(userID string, offset, limit int) (*RetentionPolicyForChannelList, *Response, error) { - r, err := c.DoApiGet(c.userRoute(userID)+"/data_retention/channel_policies", "") + r, err := c.DoAPIGet(c.userRoute(userID)+"/data_retention/channel_policies", "") if err != nil { return nil, BuildResponse(r), err } @@ -5140,7 +5140,7 @@ func (c *Client4) CreateCommand(cmd *Command) (*Command, *Response, error) { if err != nil { return nil, nil, NewAppError("CreateCommand", "api.marshal_error", nil, err.Error(), http.StatusInternalServerError) } - r, err := c.doApiPostBytes(c.commandsRoute(), buf) + r, err := c.DoAPIPostBytes(c.commandsRoute(), buf) if err != nil { return nil, BuildResponse(r), err } @@ -5154,7 +5154,7 @@ func (c *Client4) UpdateCommand(cmd *Command) (*Command, *Response, error) { if err != nil { return nil, nil, NewAppError("UpdateCommand", "api.marshal_error", nil, err.Error(), http.StatusInternalServerError) } - r, err := c.doApiPutBytes(c.commandRoute(cmd.Id), buf) + r, err := c.DoAPIPutBytes(c.commandRoute(cmd.Id), buf) if err != nil { return nil, BuildResponse(r), err } @@ -5169,7 +5169,7 @@ func (c *Client4) MoveCommand(teamId string, commandId string) (*Response, error if err != nil { return nil, NewAppError("MoveCommand", "api.marshal_error", nil, err.Error(), http.StatusInternalServerError) } - r, err := c.doApiPutBytes(c.commandMoveRoute(commandId), buf) + r, err := c.DoAPIPutBytes(c.commandMoveRoute(commandId), buf) if err != nil { return BuildResponse(r), err } @@ -5179,7 +5179,7 @@ func (c *Client4) MoveCommand(teamId string, commandId string) (*Response, error // DeleteCommand deletes a command based on the provided command id string. func (c *Client4) DeleteCommand(commandId string) (*Response, error) { - r, err := c.DoApiDelete(c.commandRoute(commandId)) + r, err := c.DoAPIDelete(c.commandRoute(commandId)) if err != nil { return BuildResponse(r), err } @@ -5190,7 +5190,7 @@ func (c *Client4) DeleteCommand(commandId string) (*Response, error) { // ListCommands will retrieve a list of commands available in the team. func (c *Client4) ListCommands(teamId string, customOnly bool) ([]*Command, *Response, error) { query := fmt.Sprintf("?team_id=%v&custom_only=%v", teamId, customOnly) - r, err := c.DoApiGet(c.commandsRoute()+query, "") + r, err := c.DoAPIGet(c.commandsRoute()+query, "") if err != nil { return nil, BuildResponse(r), err } @@ -5201,7 +5201,7 @@ func (c *Client4) ListCommands(teamId string, customOnly bool) ([]*Command, *Res // ListCommandAutocompleteSuggestions will retrieve a list of suggestions for a userInput. func (c *Client4) ListCommandAutocompleteSuggestions(userInput, teamId string) ([]AutocompleteSuggestion, *Response, error) { query := fmt.Sprintf("/commands/autocomplete_suggestions?user_input=%v", userInput) - r, err := c.DoApiGet(c.teamRoute(teamId)+query, "") + r, err := c.DoAPIGet(c.teamRoute(teamId)+query, "") if err != nil { return nil, BuildResponse(r), err } @@ -5212,7 +5212,7 @@ func (c *Client4) ListCommandAutocompleteSuggestions(userInput, teamId string) ( // GetCommandById will retrieve a command by id. func (c *Client4) GetCommandById(cmdId string) (*Command, *Response, error) { url := fmt.Sprintf("%s/%s", c.commandsRoute(), cmdId) - r, err := c.DoApiGet(url, "") + r, err := c.DoAPIGet(url, "") if err != nil { return nil, BuildResponse(r), err } @@ -5230,7 +5230,7 @@ func (c *Client4) ExecuteCommand(channelId, command string) (*CommandResponse, * if err != nil { return nil, nil, NewAppError("ExecuteCommand", "api.marshal_error", nil, err.Error(), http.StatusInternalServerError) } - r, err := c.doApiPostBytes(c.commandsRoute()+"/execute", buf) + r, err := c.DoAPIPostBytes(c.commandsRoute()+"/execute", buf) if err != nil { return nil, BuildResponse(r), err } @@ -5255,7 +5255,7 @@ func (c *Client4) ExecuteCommandWithTeam(channelId, teamId, command string) (*Co if err != nil { return nil, nil, NewAppError("ExecuteCommandWithTeam", "api.marshal_error", nil, err.Error(), http.StatusInternalServerError) } - r, err := c.doApiPostBytes(c.commandsRoute()+"/execute", buf) + r, err := c.DoAPIPostBytes(c.commandsRoute()+"/execute", buf) if err != nil { return nil, BuildResponse(r), err } @@ -5270,7 +5270,7 @@ func (c *Client4) ExecuteCommandWithTeam(channelId, teamId, command string) (*Co // ListAutocompleteCommands will retrieve a list of commands available in the team. func (c *Client4) ListAutocompleteCommands(teamId string) ([]*Command, *Response, error) { - r, err := c.DoApiGet(c.teamAutoCompleteCommandsRoute(teamId), "") + r, err := c.DoAPIGet(c.teamAutoCompleteCommandsRoute(teamId), "") if err != nil { return nil, BuildResponse(r), err } @@ -5280,7 +5280,7 @@ func (c *Client4) ListAutocompleteCommands(teamId string) ([]*Command, *Response // RegenCommandToken will create a new token if the user have the right permissions. func (c *Client4) RegenCommandToken(commandId string) (string, *Response, error) { - r, err := c.DoApiPut(c.commandRoute(commandId)+"/regen_token", "") + r, err := c.DoAPIPut(c.commandRoute(commandId)+"/regen_token", "") if err != nil { return "", BuildResponse(r), err } @@ -5292,7 +5292,7 @@ func (c *Client4) RegenCommandToken(commandId string) (string, *Response, error) // GetUserStatus returns a user based on the provided user id string. func (c *Client4) GetUserStatus(userId, etag string) (*Status, *Response, error) { - r, err := c.DoApiGet(c.userStatusRoute(userId), etag) + r, err := c.DoAPIGet(c.userStatusRoute(userId), etag) if err != nil { return nil, BuildResponse(r), err } @@ -5302,7 +5302,7 @@ func (c *Client4) GetUserStatus(userId, etag string) (*Status, *Response, error) // GetUsersStatusesByIds returns a list of users status based on the provided user ids. func (c *Client4) GetUsersStatusesByIds(userIds []string) ([]*Status, *Response, error) { - r, err := c.DoApiPost(c.userStatusesRoute()+"/ids", ArrayToJson(userIds)) + r, err := c.DoAPIPost(c.userStatusesRoute()+"/ids", ArrayToJson(userIds)) if err != nil { return nil, BuildResponse(r), err } @@ -5316,7 +5316,7 @@ func (c *Client4) UpdateUserStatus(userId string, userStatus *Status) (*Status, if err != nil { return nil, nil, NewAppError("UpdateUserStatus", "api.marshal_error", nil, err.Error(), http.StatusInternalServerError) } - r, err := c.doApiPutBytes(c.userStatusRoute(userId), buf) + r, err := c.DoAPIPutBytes(c.userStatusRoute(userId), buf) if err != nil { return nil, BuildResponse(r), err } @@ -5356,7 +5356,7 @@ func (c *Client4) CreateEmoji(emoji *Emoji, image []byte, filename string) (*Emo // GetEmojiList returns a page of custom emoji on the system. func (c *Client4) GetEmojiList(page, perPage int) ([]*Emoji, *Response, error) { query := fmt.Sprintf("?page=%v&per_page=%v", page, perPage) - r, err := c.DoApiGet(c.emojisRoute()+query, "") + r, err := c.DoAPIGet(c.emojisRoute()+query, "") if err != nil { return nil, BuildResponse(r), err } @@ -5368,7 +5368,7 @@ func (c *Client4) GetEmojiList(page, perPage int) ([]*Emoji, *Response, error) { // parameter, blank for no sorting and "name" to sort by emoji names. func (c *Client4) GetSortedEmojiList(page, perPage int, sort string) ([]*Emoji, *Response, error) { query := fmt.Sprintf("?page=%v&per_page=%v&sort=%v", page, perPage, sort) - r, err := c.DoApiGet(c.emojisRoute()+query, "") + r, err := c.DoAPIGet(c.emojisRoute()+query, "") if err != nil { return nil, BuildResponse(r), err } @@ -5378,7 +5378,7 @@ func (c *Client4) GetSortedEmojiList(page, perPage int, sort string) ([]*Emoji, // DeleteEmoji delete an custom emoji on the provided emoji id string. func (c *Client4) DeleteEmoji(emojiId string) (*Response, error) { - r, err := c.DoApiDelete(c.emojiRoute(emojiId)) + r, err := c.DoAPIDelete(c.emojiRoute(emojiId)) if err != nil { return BuildResponse(r), err } @@ -5388,7 +5388,7 @@ func (c *Client4) DeleteEmoji(emojiId string) (*Response, error) { // GetEmoji returns a custom emoji based on the emojiId string. func (c *Client4) GetEmoji(emojiId string) (*Emoji, *Response, error) { - r, err := c.DoApiGet(c.emojiRoute(emojiId), "") + r, err := c.DoAPIGet(c.emojiRoute(emojiId), "") if err != nil { return nil, BuildResponse(r), err } @@ -5398,7 +5398,7 @@ func (c *Client4) GetEmoji(emojiId string) (*Emoji, *Response, error) { // GetEmojiByName returns a custom emoji based on the name string. func (c *Client4) GetEmojiByName(name string) (*Emoji, *Response, error) { - r, err := c.DoApiGet(c.emojiByNameRoute(name), "") + r, err := c.DoAPIGet(c.emojiByNameRoute(name), "") if err != nil { return nil, BuildResponse(r), err } @@ -5408,7 +5408,7 @@ func (c *Client4) GetEmojiByName(name string) (*Emoji, *Response, error) { // GetEmojiImage returns the emoji image. func (c *Client4) GetEmojiImage(emojiId string) ([]byte, *Response, error) { - r, err := c.DoApiGet(c.emojiRoute(emojiId)+"/image", "") + r, err := c.DoAPIGet(c.emojiRoute(emojiId)+"/image", "") if err != nil { return nil, BuildResponse(r), err } @@ -5428,7 +5428,7 @@ func (c *Client4) SearchEmoji(search *EmojiSearch) ([]*Emoji, *Response, error) if err != nil { return nil, nil, NewAppError("SearchEmoji", "api.marshal_error", nil, err.Error(), http.StatusInternalServerError) } - r, err := c.doApiPostBytes(c.emojisRoute()+"/search", buf) + r, err := c.DoAPIPostBytes(c.emojisRoute()+"/search", buf) if err != nil { return nil, BuildResponse(r), err } @@ -5439,7 +5439,7 @@ func (c *Client4) SearchEmoji(search *EmojiSearch) ([]*Emoji, *Response, error) // AutocompleteEmoji returns a list of emoji starting with or matching name. func (c *Client4) AutocompleteEmoji(name string, etag string) ([]*Emoji, *Response, error) { query := fmt.Sprintf("?name=%v", name) - r, err := c.DoApiGet(c.emojisRoute()+"/autocomplete"+query, "") + r, err := c.DoAPIGet(c.emojisRoute()+"/autocomplete"+query, "") if err != nil { return nil, BuildResponse(r), err } @@ -5455,7 +5455,7 @@ func (c *Client4) SaveReaction(reaction *Reaction) (*Reaction, *Response, error) if err != nil { return nil, nil, NewAppError("SaveReaction", "api.marshal_error", nil, err.Error(), http.StatusInternalServerError) } - r, err := c.doApiPostBytes(c.reactionsRoute(), buf) + r, err := c.DoAPIPostBytes(c.reactionsRoute(), buf) if err != nil { return nil, BuildResponse(r), err } @@ -5465,7 +5465,7 @@ func (c *Client4) SaveReaction(reaction *Reaction) (*Reaction, *Response, error) // GetReactions returns a list of reactions to a post. func (c *Client4) GetReactions(postId string) ([]*Reaction, *Response, error) { - r, err := c.DoApiGet(c.postRoute(postId)+"/reactions", "") + r, err := c.DoAPIGet(c.postRoute(postId)+"/reactions", "") if err != nil { return nil, BuildResponse(r), err } @@ -5475,7 +5475,7 @@ func (c *Client4) GetReactions(postId string) ([]*Reaction, *Response, error) { // DeleteReaction deletes reaction of a user in a post. func (c *Client4) DeleteReaction(reaction *Reaction) (*Response, error) { - r, err := c.DoApiDelete(c.userRoute(reaction.UserId) + c.postRoute(reaction.PostId) + fmt.Sprintf("/reactions/%v", reaction.EmojiName)) + r, err := c.DoAPIDelete(c.userRoute(reaction.UserId) + c.postRoute(reaction.PostId) + fmt.Sprintf("/reactions/%v", reaction.EmojiName)) if err != nil { return BuildResponse(r), err } @@ -5485,7 +5485,7 @@ func (c *Client4) DeleteReaction(reaction *Reaction) (*Response, error) { // FetchBulkReactions returns a map of postIds and corresponding reactions func (c *Client4) GetBulkReactions(postIds []string) (map[string][]*Reaction, *Response, error) { - r, err := c.DoApiPost(c.postsRoute()+"/ids/reactions", ArrayToJson(postIds)) + r, err := c.DoAPIPost(c.postsRoute()+"/ids/reactions", ArrayToJson(postIds)) if err != nil { return nil, BuildResponse(r), err } @@ -5497,7 +5497,7 @@ func (c *Client4) GetBulkReactions(postIds []string) (map[string][]*Reaction, *R // GetSupportedTimezone returns a page of supported timezones on the system. func (c *Client4) GetSupportedTimezone() ([]string, *Response, error) { - r, err := c.DoApiGet(c.timezonesRoute(), "") + r, err := c.DoAPIGet(c.timezonesRoute(), "") if err != nil { return nil, BuildResponse(r), err } @@ -5514,7 +5514,7 @@ func (c *Client4) OpenGraph(url string) (map[string]string, *Response, error) { requestBody := make(map[string]string) requestBody["url"] = url - r, err := c.DoApiPost(c.openGraphRoute(), MapToJson(requestBody)) + r, err := c.DoAPIPost(c.openGraphRoute(), MapToJson(requestBody)) if err != nil { return nil, BuildResponse(r), err } @@ -5526,7 +5526,7 @@ func (c *Client4) OpenGraph(url string) (map[string]string, *Response, error) { // GetJob gets a single job. func (c *Client4) GetJob(id string) (*Job, *Response, error) { - r, err := c.DoApiGet(c.jobsRoute()+fmt.Sprintf("/%v", id), "") + r, err := c.DoAPIGet(c.jobsRoute()+fmt.Sprintf("/%v", id), "") if err != nil { return nil, BuildResponse(r), err } @@ -5536,7 +5536,7 @@ func (c *Client4) GetJob(id string) (*Job, *Response, error) { // GetJobs gets all jobs, sorted with the job that was created most recently first. func (c *Client4) GetJobs(page int, perPage int) ([]*Job, *Response, error) { - r, err := c.DoApiGet(c.jobsRoute()+fmt.Sprintf("?page=%v&per_page=%v", page, perPage), "") + r, err := c.DoAPIGet(c.jobsRoute()+fmt.Sprintf("?page=%v&per_page=%v", page, perPage), "") if err != nil { return nil, BuildResponse(r), err } @@ -5546,7 +5546,7 @@ func (c *Client4) GetJobs(page int, perPage int) ([]*Job, *Response, error) { // GetJobsByType gets all jobs of a given type, sorted with the job that was created most recently first. func (c *Client4) GetJobsByType(jobType string, page int, perPage int) ([]*Job, *Response, error) { - r, err := c.DoApiGet(c.jobsRoute()+fmt.Sprintf("/type/%v?page=%v&per_page=%v", jobType, page, perPage), "") + r, err := c.DoAPIGet(c.jobsRoute()+fmt.Sprintf("/type/%v?page=%v&per_page=%v", jobType, page, perPage), "") if err != nil { return nil, BuildResponse(r), err } @@ -5560,7 +5560,7 @@ func (c *Client4) CreateJob(job *Job) (*Job, *Response, error) { if err != nil { return nil, nil, NewAppError("CreateJob", "api.marshal_error", nil, err.Error(), http.StatusInternalServerError) } - r, err := c.doApiPostBytes(c.jobsRoute(), buf) + r, err := c.DoAPIPostBytes(c.jobsRoute(), buf) if err != nil { return nil, BuildResponse(r), err } @@ -5570,7 +5570,7 @@ func (c *Client4) CreateJob(job *Job) (*Job, *Response, error) { // CancelJob requests the cancellation of the job with the provided Id. func (c *Client4) CancelJob(jobId string) (*Response, error) { - r, err := c.DoApiPost(c.jobsRoute()+fmt.Sprintf("/%v/cancel", jobId), "") + r, err := c.DoAPIPost(c.jobsRoute()+fmt.Sprintf("/%v/cancel", jobId), "") if err != nil { return BuildResponse(r), err } @@ -5580,7 +5580,7 @@ func (c *Client4) CancelJob(jobId string) (*Response, error) { // DownloadJob downloads the results of the job func (c *Client4) DownloadJob(jobId string) ([]byte, *Response, error) { - r, err := c.DoApiGet(c.jobsRoute()+fmt.Sprintf("/%v/download", jobId), "") + r, err := c.DoAPIGet(c.jobsRoute()+fmt.Sprintf("/%v/download", jobId), "") if err != nil { return nil, BuildResponse(r), err } @@ -5597,7 +5597,7 @@ func (c *Client4) DownloadJob(jobId string) ([]byte, *Response, error) { // GetRole gets a single role by ID. func (c *Client4) GetRole(id string) (*Role, *Response, error) { - r, err := c.DoApiGet(c.rolesRoute()+fmt.Sprintf("/%v", id), "") + r, err := c.DoAPIGet(c.rolesRoute()+fmt.Sprintf("/%v", id), "") if err != nil { return nil, BuildResponse(r), err } @@ -5607,7 +5607,7 @@ func (c *Client4) GetRole(id string) (*Role, *Response, error) { // GetRoleByName gets a single role by Name. func (c *Client4) GetRoleByName(name string) (*Role, *Response, error) { - r, err := c.DoApiGet(c.rolesRoute()+fmt.Sprintf("/name/%v", name), "") + r, err := c.DoAPIGet(c.rolesRoute()+fmt.Sprintf("/name/%v", name), "") if err != nil { return nil, BuildResponse(r), err } @@ -5617,7 +5617,7 @@ func (c *Client4) GetRoleByName(name string) (*Role, *Response, error) { // GetRolesByNames returns a list of roles based on the provided role names. func (c *Client4) GetRolesByNames(roleNames []string) ([]*Role, *Response, error) { - r, err := c.DoApiPost(c.rolesRoute()+"/names", ArrayToJson(roleNames)) + r, err := c.DoAPIPost(c.rolesRoute()+"/names", ArrayToJson(roleNames)) if err != nil { return nil, BuildResponse(r), err } @@ -5631,7 +5631,7 @@ func (c *Client4) PatchRole(roleId string, patch *RolePatch) (*Role, *Response, if err != nil { return nil, nil, NewAppError("PatchRole", "api.marshal_error", nil, err.Error(), http.StatusInternalServerError) } - r, err := c.doApiPutBytes(c.rolesRoute()+fmt.Sprintf("/%v/patch", roleId), buf) + r, err := c.DoAPIPutBytes(c.rolesRoute()+fmt.Sprintf("/%v/patch", roleId), buf) if err != nil { return nil, BuildResponse(r), err } @@ -5647,7 +5647,7 @@ func (c *Client4) CreateScheme(scheme *Scheme) (*Scheme, *Response, error) { if err != nil { return nil, nil, NewAppError("CreateScheme", "api.marshal_error", nil, err.Error(), http.StatusInternalServerError) } - r, err := c.doApiPostBytes(c.schemesRoute(), buf) + r, err := c.DoAPIPostBytes(c.schemesRoute(), buf) if err != nil { return nil, BuildResponse(r), err } @@ -5657,7 +5657,7 @@ func (c *Client4) CreateScheme(scheme *Scheme) (*Scheme, *Response, error) { // GetScheme gets a single scheme by ID. func (c *Client4) GetScheme(id string) (*Scheme, *Response, error) { - r, err := c.DoApiGet(c.schemeRoute(id), "") + r, err := c.DoAPIGet(c.schemeRoute(id), "") if err != nil { return nil, BuildResponse(r), err } @@ -5667,7 +5667,7 @@ func (c *Client4) GetScheme(id string) (*Scheme, *Response, error) { // GetSchemes gets all schemes, sorted with the most recently created first, optionally filtered by scope. func (c *Client4) GetSchemes(scope string, page int, perPage int) ([]*Scheme, *Response, error) { - r, err := c.DoApiGet(c.schemesRoute()+fmt.Sprintf("?scope=%v&page=%v&per_page=%v", scope, page, perPage), "") + r, err := c.DoAPIGet(c.schemesRoute()+fmt.Sprintf("?scope=%v&page=%v&per_page=%v", scope, page, perPage), "") if err != nil { return nil, BuildResponse(r), err } @@ -5677,7 +5677,7 @@ func (c *Client4) GetSchemes(scope string, page int, perPage int) ([]*Scheme, *R // DeleteScheme deletes a single scheme by ID. func (c *Client4) DeleteScheme(id string) (*Response, error) { - r, err := c.DoApiDelete(c.schemeRoute(id)) + r, err := c.DoAPIDelete(c.schemeRoute(id)) if err != nil { return BuildResponse(r), err } @@ -5691,7 +5691,7 @@ func (c *Client4) PatchScheme(id string, patch *SchemePatch) (*Scheme, *Response if err != nil { return nil, nil, NewAppError("PatchScheme", "api.marshal_error", nil, err.Error(), http.StatusInternalServerError) } - r, err := c.doApiPutBytes(c.schemeRoute(id)+"/patch", buf) + r, err := c.DoAPIPutBytes(c.schemeRoute(id)+"/patch", buf) if err != nil { return nil, BuildResponse(r), err } @@ -5701,7 +5701,7 @@ func (c *Client4) PatchScheme(id string, patch *SchemePatch) (*Scheme, *Response // GetTeamsForScheme gets the teams using this scheme, sorted alphabetically by display name. func (c *Client4) GetTeamsForScheme(schemeId string, page int, perPage int) ([]*Team, *Response, error) { - r, err := c.DoApiGet(c.schemeRoute(schemeId)+fmt.Sprintf("/teams?page=%v&per_page=%v", page, perPage), "") + r, err := c.DoAPIGet(c.schemeRoute(schemeId)+fmt.Sprintf("/teams?page=%v&per_page=%v", page, perPage), "") if err != nil { return nil, BuildResponse(r), err } @@ -5711,7 +5711,7 @@ func (c *Client4) GetTeamsForScheme(schemeId string, page int, perPage int) ([]* // GetChannelsForScheme gets the channels using this scheme, sorted alphabetically by display name. func (c *Client4) GetChannelsForScheme(schemeId string, page int, perPage int) (ChannelList, *Response, error) { - r, err := c.DoApiGet(c.schemeRoute(schemeId)+fmt.Sprintf("/channels?page=%v&per_page=%v", page, perPage), "") + r, err := c.DoAPIGet(c.schemeRoute(schemeId)+fmt.Sprintf("/channels?page=%v&per_page=%v", page, perPage), "") if err != nil { return nil, BuildResponse(r), err } @@ -5760,7 +5760,7 @@ func (c *Client4) uploadPlugin(file io.Reader, force bool) (*Manifest, *Response return nil, nil, err } - rq, err := http.NewRequest("POST", c.ApiUrl+c.pluginsRoute(), body) + rq, err := http.NewRequest("POST", c.APIURL+c.pluginsRoute(), body) if err != nil { return nil, nil, err } @@ -5783,11 +5783,11 @@ func (c *Client4) uploadPlugin(file io.Reader, force bool) (*Manifest, *Response return ManifestFromJson(rp.Body), BuildResponse(rp), nil } -func (c *Client4) InstallPluginFromUrl(downloadUrl string, force bool) (*Manifest, *Response, error) { +func (c *Client4) InstallPluginFromURL(downloadURL string, force bool) (*Manifest, *Response, error) { forceStr := c.boolString(force) - url := fmt.Sprintf("%s?plugin_download_url=%s&force=%s", c.pluginsRoute()+"/install_from_url", url.QueryEscape(downloadUrl), forceStr) - r, err := c.DoApiPost(url, "") + url := fmt.Sprintf("%s?plugin_download_url=%s&force=%s", c.pluginsRoute()+"/install_from_url", url.QueryEscape(downloadURL), forceStr) + r, err := c.DoAPIPost(url, "") if err != nil { return nil, BuildResponse(r), err } @@ -5801,7 +5801,7 @@ func (c *Client4) InstallMarketplacePlugin(request *InstallMarketplacePluginRequ if err != nil { return nil, nil, err } - r, err := c.DoApiPost(c.pluginsRoute()+"/marketplace", json) + r, err := c.DoAPIPost(c.pluginsRoute()+"/marketplace", json) if err != nil { return nil, BuildResponse(r), err } @@ -5811,7 +5811,7 @@ func (c *Client4) InstallMarketplacePlugin(request *InstallMarketplacePluginRequ // GetPlugins will return a list of plugin manifests for currently active plugins. func (c *Client4) GetPlugins() (*PluginsResponse, *Response, error) { - r, err := c.DoApiGet(c.pluginsRoute(), "") + r, err := c.DoAPIGet(c.pluginsRoute(), "") if err != nil { return nil, BuildResponse(r), err } @@ -5822,7 +5822,7 @@ func (c *Client4) GetPlugins() (*PluginsResponse, *Response, error) { // GetPluginStatuses will return the plugins installed on any server in the cluster, for reporting // to the administrator via the system console. func (c *Client4) GetPluginStatuses() (PluginStatuses, *Response, error) { - r, err := c.DoApiGet(c.pluginsRoute()+"/statuses", "") + r, err := c.DoAPIGet(c.pluginsRoute()+"/statuses", "") if err != nil { return nil, BuildResponse(r), err } @@ -5832,7 +5832,7 @@ func (c *Client4) GetPluginStatuses() (PluginStatuses, *Response, error) { // RemovePlugin will disable and delete a plugin. func (c *Client4) RemovePlugin(id string) (*Response, error) { - r, err := c.DoApiDelete(c.pluginRoute(id)) + r, err := c.DoAPIDelete(c.pluginRoute(id)) if err != nil { return BuildResponse(r), err } @@ -5842,7 +5842,7 @@ func (c *Client4) RemovePlugin(id string) (*Response, error) { // GetWebappPlugins will return a list of plugins that the webapp should download. func (c *Client4) GetWebappPlugins() ([]*Manifest, *Response, error) { - r, err := c.DoApiGet(c.pluginsRoute()+"/webapp", "") + r, err := c.DoAPIGet(c.pluginsRoute()+"/webapp", "") if err != nil { return nil, BuildResponse(r), err } @@ -5852,7 +5852,7 @@ func (c *Client4) GetWebappPlugins() ([]*Manifest, *Response, error) { // EnablePlugin will enable an plugin installed. func (c *Client4) EnablePlugin(id string) (*Response, error) { - r, err := c.DoApiPost(c.pluginRoute(id)+"/enable", "") + r, err := c.DoAPIPost(c.pluginRoute(id)+"/enable", "") if err != nil { return BuildResponse(r), err } @@ -5862,7 +5862,7 @@ func (c *Client4) EnablePlugin(id string) (*Response, error) { // DisablePlugin will disable an enabled plugin. func (c *Client4) DisablePlugin(id string) (*Response, error) { - r, err := c.DoApiPost(c.pluginRoute(id)+"/disable", "") + r, err := c.DoAPIPost(c.pluginRoute(id)+"/disable", "") if err != nil { return BuildResponse(r), err } @@ -5880,7 +5880,7 @@ func (c *Client4) GetMarketplacePlugins(filter *MarketplacePluginFilter) ([]*Mar filter.ApplyToURL(u) - r, err := c.DoApiGet(u.String(), "") + r, err := c.DoAPIGet(u.String(), "") if err != nil { return nil, BuildResponse(r), err } @@ -5901,7 +5901,7 @@ func (c *Client4) UpdateChannelScheme(channelId, schemeId string) (*Response, er if err != nil { return nil, NewAppError("UpdateChannelScheme", "api.marshal_error", nil, err.Error(), http.StatusInternalServerError) } - r, err := c.doApiPutBytes(c.channelSchemeRoute(channelId), buf) + r, err := c.DoAPIPutBytes(c.channelSchemeRoute(channelId), buf) if err != nil { return BuildResponse(r), err } @@ -5916,7 +5916,7 @@ func (c *Client4) UpdateTeamScheme(teamId, schemeId string) (*Response, error) { if err != nil { return nil, NewAppError("UpdateTeamScheme", "api.marshal_error", nil, err.Error(), http.StatusInternalServerError) } - r, err := c.doApiPutBytes(c.teamSchemeRoute(teamId), buf) + r, err := c.DoAPIPutBytes(c.teamSchemeRoute(teamId), buf) if err != nil { return BuildResponse(r), err } @@ -5927,7 +5927,7 @@ func (c *Client4) UpdateTeamScheme(teamId, schemeId string) (*Response, error) { // GetRedirectLocation retrieves the value of the 'Location' header of an HTTP response for a given URL. func (c *Client4) GetRedirectLocation(urlParam, etag string) (string, *Response, error) { url := fmt.Sprintf("%s?url=%s", c.redirectLocationRoute(), url.QueryEscape(urlParam)) - r, err := c.DoApiGet(url, etag) + r, err := c.DoAPIGet(url, etag) if err != nil { return "", BuildResponse(r), err } @@ -5938,7 +5938,7 @@ func (c *Client4) GetRedirectLocation(urlParam, etag string) (string, *Response, // SetServerBusy will mark the server as busy, which disables non-critical services for `secs` seconds. func (c *Client4) SetServerBusy(secs int) (*Response, error) { url := fmt.Sprintf("%s?seconds=%d", c.serverBusyRoute(), secs) - r, err := c.DoApiPost(url, "") + r, err := c.DoAPIPost(url, "") if err != nil { return BuildResponse(r), err } @@ -5948,7 +5948,7 @@ func (c *Client4) SetServerBusy(secs int) (*Response, error) { // ClearServerBusy will mark the server as not busy. func (c *Client4) ClearServerBusy() (*Response, error) { - r, err := c.DoApiDelete(c.serverBusyRoute()) + r, err := c.DoAPIDelete(c.serverBusyRoute()) if err != nil { return BuildResponse(r), err } @@ -5959,7 +5959,7 @@ func (c *Client4) ClearServerBusy() (*Response, error) { // GetServerBusy returns the current ServerBusyState including the time when a server marked busy // will automatically have the flag cleared. func (c *Client4) GetServerBusy() (*ServerBusyState, *Response, error) { - r, err := c.DoApiGet(c.serverBusyRoute(), "") + r, err := c.DoAPIGet(c.serverBusyRoute(), "") if err != nil { return nil, BuildResponse(r), err } @@ -5973,7 +5973,7 @@ func (c *Client4) GetServerBusy() (*ServerBusyState, *Response, error) { func (c *Client4) RegisterTermsOfServiceAction(userId, termsOfServiceId string, accepted bool) (*Response, error) { url := c.userTermsOfServiceRoute(userId) data := map[string]interface{}{"termsOfServiceId": termsOfServiceId, "accepted": accepted} - r, err := c.DoApiPost(url, StringInterfaceToJson(data)) + r, err := c.DoAPIPost(url, StringInterfaceToJson(data)) if err != nil { return BuildResponse(r), err } @@ -5984,7 +5984,7 @@ func (c *Client4) RegisterTermsOfServiceAction(userId, termsOfServiceId string, // GetTermsOfService fetches the latest terms of service func (c *Client4) GetTermsOfService(etag string) (*TermsOfService, *Response, error) { url := c.termsOfServiceRoute() - r, err := c.DoApiGet(url, etag) + r, err := c.DoAPIGet(url, etag) if err != nil { return nil, BuildResponse(r), err } @@ -5995,7 +5995,7 @@ func (c *Client4) GetTermsOfService(etag string) (*TermsOfService, *Response, er // GetUserTermsOfService fetches user's latest terms of service action if the latest action was for acceptance. func (c *Client4) GetUserTermsOfService(userId, etag string) (*UserTermsOfService, *Response, error) { url := c.userTermsOfServiceRoute(userId) - r, err := c.DoApiGet(url, etag) + r, err := c.DoAPIGet(url, etag) if err != nil { return nil, BuildResponse(r), err } @@ -6007,7 +6007,7 @@ func (c *Client4) GetUserTermsOfService(userId, etag string) (*UserTermsOfServic func (c *Client4) CreateTermsOfService(text, userId string) (*TermsOfService, *Response, error) { url := c.termsOfServiceRoute() data := map[string]interface{}{"text": text} - r, err := c.DoApiPost(url, StringInterfaceToJson(data)) + r, err := c.DoAPIPost(url, StringInterfaceToJson(data)) if err != nil { return nil, BuildResponse(r), err } @@ -6016,7 +6016,7 @@ func (c *Client4) CreateTermsOfService(text, userId string) (*TermsOfService, *R } func (c *Client4) GetGroup(groupID, etag string) (*Group, *Response, error) { - r, err := c.DoApiGet(c.groupRoute(groupID), etag) + r, err := c.DoAPIGet(c.groupRoute(groupID), etag) if err != nil { return nil, BuildResponse(r), err } @@ -6026,7 +6026,7 @@ func (c *Client4) GetGroup(groupID, etag string) (*Group, *Response, error) { func (c *Client4) PatchGroup(groupID string, patch *GroupPatch) (*Group, *Response, error) { payload, _ := json.Marshal(patch) - r, err := c.DoApiPut(c.groupRoute(groupID)+"/patch", string(payload)) + r, err := c.DoAPIPut(c.groupRoute(groupID)+"/patch", string(payload)) if err != nil { return nil, BuildResponse(r), err } @@ -6037,7 +6037,7 @@ func (c *Client4) PatchGroup(groupID string, patch *GroupPatch) (*Group, *Respon func (c *Client4) LinkGroupSyncable(groupID, syncableID string, syncableType GroupSyncableType, patch *GroupSyncablePatch) (*GroupSyncable, *Response, error) { payload, _ := json.Marshal(patch) url := fmt.Sprintf("%s/link", c.groupSyncableRoute(groupID, syncableID, syncableType)) - r, err := c.DoApiPost(url, string(payload)) + r, err := c.DoAPIPost(url, string(payload)) if err != nil { return nil, BuildResponse(r), err } @@ -6047,7 +6047,7 @@ func (c *Client4) LinkGroupSyncable(groupID, syncableID string, syncableType Gro func (c *Client4) UnlinkGroupSyncable(groupID, syncableID string, syncableType GroupSyncableType) (*Response, error) { url := fmt.Sprintf("%s/link", c.groupSyncableRoute(groupID, syncableID, syncableType)) - r, err := c.DoApiDelete(url) + r, err := c.DoAPIDelete(url) if err != nil { return BuildResponse(r), err } @@ -6056,7 +6056,7 @@ func (c *Client4) UnlinkGroupSyncable(groupID, syncableID string, syncableType G } func (c *Client4) GetGroupSyncable(groupID, syncableID string, syncableType GroupSyncableType, etag string) (*GroupSyncable, *Response, error) { - r, err := c.DoApiGet(c.groupSyncableRoute(groupID, syncableID, syncableType), etag) + r, err := c.DoAPIGet(c.groupSyncableRoute(groupID, syncableID, syncableType), etag) if err != nil { return nil, BuildResponse(r), err } @@ -6065,7 +6065,7 @@ func (c *Client4) GetGroupSyncable(groupID, syncableID string, syncableType Grou } func (c *Client4) GetGroupSyncables(groupID string, syncableType GroupSyncableType, etag string) ([]*GroupSyncable, *Response, error) { - r, err := c.DoApiGet(c.groupSyncablesRoute(groupID, syncableType), etag) + r, err := c.DoAPIGet(c.groupSyncablesRoute(groupID, syncableType), etag) if err != nil { return nil, BuildResponse(r), err } @@ -6075,7 +6075,7 @@ func (c *Client4) GetGroupSyncables(groupID string, syncableType GroupSyncableTy func (c *Client4) PatchGroupSyncable(groupID, syncableID string, syncableType GroupSyncableType, patch *GroupSyncablePatch) (*GroupSyncable, *Response, error) { payload, _ := json.Marshal(patch) - r, err := c.DoApiPut(c.groupSyncableRoute(groupID, syncableID, syncableType)+"/patch", string(payload)) + r, err := c.DoAPIPut(c.groupSyncableRoute(groupID, syncableID, syncableType)+"/patch", string(payload)) if err != nil { return nil, BuildResponse(r), err } @@ -6086,7 +6086,7 @@ func (c *Client4) PatchGroupSyncable(groupID, syncableID string, syncableType Gr func (c *Client4) TeamMembersMinusGroupMembers(teamID string, groupIDs []string, page, perPage int, etag string) ([]*UserWithGroups, int64, *Response, error) { groupIDStr := strings.Join(groupIDs, ",") query := fmt.Sprintf("?group_ids=%s&page=%d&per_page=%d", groupIDStr, page, perPage) - r, err := c.DoApiGet(c.teamRoute(teamID)+"/members_minus_group_members"+query, etag) + r, err := c.DoAPIGet(c.teamRoute(teamID)+"/members_minus_group_members"+query, etag) if err != nil { return nil, 0, BuildResponse(r), err } @@ -6098,7 +6098,7 @@ func (c *Client4) TeamMembersMinusGroupMembers(teamID string, groupIDs []string, func (c *Client4) ChannelMembersMinusGroupMembers(channelID string, groupIDs []string, page, perPage int, etag string) ([]*UserWithGroups, int64, *Response, error) { groupIDStr := strings.Join(groupIDs, ",") query := fmt.Sprintf("?group_ids=%s&page=%d&per_page=%d", groupIDStr, page, perPage) - r, err := c.DoApiGet(c.channelRoute(channelID)+"/members_minus_group_members"+query, etag) + r, err := c.DoAPIGet(c.channelRoute(channelID)+"/members_minus_group_members"+query, etag) if err != nil { return nil, 0, BuildResponse(r), err } @@ -6112,7 +6112,7 @@ func (c *Client4) PatchConfig(config *Config) (*Config, *Response, error) { if err != nil { return nil, nil, NewAppError("PatchConfig", "api.marshal_error", nil, err.Error(), http.StatusInternalServerError) } - r, err := c.doApiPutBytes(c.configRoute()+"/patch", buf) + r, err := c.DoAPIPutBytes(c.configRoute()+"/patch", buf) if err != nil { return nil, BuildResponse(r), err } @@ -6121,7 +6121,7 @@ func (c *Client4) PatchConfig(config *Config) (*Config, *Response, error) { } func (c *Client4) GetChannelModerations(channelID string, etag string) ([]*ChannelModeration, *Response, error) { - r, err := c.DoApiGet(c.channelRoute(channelID)+"/moderations", etag) + r, err := c.DoAPIGet(c.channelRoute(channelID)+"/moderations", etag) if err != nil { return nil, BuildResponse(r), err } @@ -6141,7 +6141,7 @@ func (c *Client4) PatchChannelModerations(channelID string, patch []*ChannelMode return nil, nil, NewAppError("PatchChannelModerations", "api.marshal_error", nil, err.Error(), http.StatusInternalServerError) } - r, err := c.DoApiPut(c.channelRoute(channelID)+"/moderations/patch", string(payload)) + r, err := c.DoAPIPut(c.channelRoute(channelID)+"/moderations/patch", string(payload)) if err != nil { return nil, BuildResponse(r), err } @@ -6156,7 +6156,7 @@ func (c *Client4) PatchChannelModerations(channelID string, patch []*ChannelMode } func (c *Client4) GetKnownUsers() ([]string, *Response, error) { - r, err := c.DoApiGet(c.usersRoute()+"/known", "") + r, err := c.DoAPIGet(c.usersRoute()+"/known", "") if err != nil { return nil, BuildResponse(r), err } @@ -6172,7 +6172,7 @@ func (c *Client4) PublishUserTyping(userID string, typingRequest TypingRequest) if err != nil { return nil, NewAppError("PublishUserTyping", "api.marshal_error", nil, err.Error(), http.StatusInternalServerError) } - r, err := c.doApiPostBytes(c.publishUserTypingRoute(userID), buf) + r, err := c.DoAPIPostBytes(c.publishUserTypingRoute(userID), buf) if err != nil { return BuildResponse(r), err } @@ -6181,7 +6181,7 @@ func (c *Client4) PublishUserTyping(userID string, typingRequest TypingRequest) } func (c *Client4) GetChannelMemberCountsByGroup(channelID string, includeTimezones bool, etag string) ([]*ChannelMemberCountByGroup, *Response, error) { - r, err := c.DoApiGet(c.channelRoute(channelID)+"/member_counts_by_group?include_timezones="+strconv.FormatBool(includeTimezones), etag) + r, err := c.DoAPIGet(c.channelRoute(channelID)+"/member_counts_by_group?include_timezones="+strconv.FormatBool(includeTimezones), etag) if err != nil { return nil, BuildResponse(r), err } @@ -6198,7 +6198,7 @@ func (c *Client4) GetChannelMemberCountsByGroup(channelID string, includeTimezon // RequestTrialLicense will request a trial license and install it in the server func (c *Client4) RequestTrialLicense(users int) (*Response, error) { b, _ := json.Marshal(map[string]interface{}{"users": users, "terms_accepted": true}) - r, err := c.DoApiPost("/trial-license", string(b)) + r, err := c.DoAPIPost("/trial-license", string(b)) if err != nil { return BuildResponse(r), err } @@ -6208,7 +6208,7 @@ func (c *Client4) RequestTrialLicense(users int) (*Response, error) { // GetGroupStats retrieves stats for a Mattermost Group func (c *Client4) GetGroupStats(groupID string) (*GroupStats, *Response, error) { - r, err := c.DoApiGet(c.groupRoute(groupID)+"/stats", "") + r, err := c.DoAPIGet(c.groupRoute(groupID)+"/stats", "") if err != nil { return nil, BuildResponse(r), err } @@ -6218,7 +6218,7 @@ func (c *Client4) GetGroupStats(groupID string) (*GroupStats, *Response, error) func (c *Client4) GetSidebarCategoriesForTeamForUser(userID, teamID, etag string) (*OrderedSidebarCategories, *Response, error) { route := c.userCategoryRoute(userID, teamID) - r, err := c.DoApiGet(route, etag) + r, err := c.DoAPIGet(route, etag) if err != nil { return nil, BuildResponse(r), err } @@ -6234,7 +6234,7 @@ func (c *Client4) GetSidebarCategoriesForTeamForUser(userID, teamID, etag string func (c *Client4) CreateSidebarCategoryForTeamForUser(userID, teamID string, category *SidebarCategoryWithChannels) (*SidebarCategoryWithChannels, *Response, error) { payload, _ := json.Marshal(category) route := c.userCategoryRoute(userID, teamID) - r, err := c.doApiPostBytes(route, payload) + r, err := c.DoAPIPostBytes(route, payload) if err != nil { return nil, BuildResponse(r), err } @@ -6251,7 +6251,7 @@ func (c *Client4) UpdateSidebarCategoriesForTeamForUser(userID, teamID string, c payload, _ := json.Marshal(categories) route := c.userCategoryRoute(userID, teamID) - r, err := c.doApiPutBytes(route, payload) + r, err := c.DoAPIPutBytes(route, payload) if err != nil { return nil, BuildResponse(r), err } @@ -6268,7 +6268,7 @@ func (c *Client4) UpdateSidebarCategoriesForTeamForUser(userID, teamID string, c func (c *Client4) GetSidebarCategoryOrderForTeamForUser(userID, teamID, etag string) ([]string, *Response, error) { route := c.userCategoryRoute(userID, teamID) + "/order" - r, err := c.DoApiGet(route, etag) + r, err := c.DoAPIGet(route, etag) if err != nil { return nil, BuildResponse(r), err } @@ -6279,7 +6279,7 @@ func (c *Client4) GetSidebarCategoryOrderForTeamForUser(userID, teamID, etag str func (c *Client4) UpdateSidebarCategoryOrderForTeamForUser(userID, teamID string, order []string) ([]string, *Response, error) { payload, _ := json.Marshal(order) route := c.userCategoryRoute(userID, teamID) + "/order" - r, err := c.doApiPutBytes(route, payload) + r, err := c.DoAPIPutBytes(route, payload) if err != nil { return nil, BuildResponse(r), err } @@ -6289,7 +6289,7 @@ func (c *Client4) UpdateSidebarCategoryOrderForTeamForUser(userID, teamID string func (c *Client4) GetSidebarCategoryForTeamForUser(userID, teamID, categoryID, etag string) (*SidebarCategoryWithChannels, *Response, error) { route := c.userCategoryRoute(userID, teamID) + "/" + categoryID - r, err := c.DoApiGet(route, etag) + r, err := c.DoAPIGet(route, etag) if err != nil { return nil, BuildResponse(r), err } @@ -6306,7 +6306,7 @@ func (c *Client4) GetSidebarCategoryForTeamForUser(userID, teamID, categoryID, e func (c *Client4) UpdateSidebarCategoryForTeamForUser(userID, teamID, categoryID string, category *SidebarCategoryWithChannels) (*SidebarCategoryWithChannels, *Response, error) { payload, _ := json.Marshal(category) route := c.userCategoryRoute(userID, teamID) + "/" + categoryID - r, err := c.doApiPutBytes(route, payload) + r, err := c.DoAPIPutBytes(route, payload) if err != nil { return nil, BuildResponse(r), err } @@ -6322,7 +6322,7 @@ func (c *Client4) UpdateSidebarCategoryForTeamForUser(userID, teamID, categoryID // CheckIntegrity performs a database integrity check. func (c *Client4) CheckIntegrity() ([]IntegrityCheckResult, *Response, error) { - r, err := c.DoApiPost("/integrity", "") + r, err := c.DoAPIPost("/integrity", "") if err != nil { return nil, BuildResponse(r), err } @@ -6336,7 +6336,7 @@ func (c *Client4) CheckIntegrity() ([]IntegrityCheckResult, *Response, error) { func (c *Client4) GetNotices(lastViewed int64, teamId string, client NoticeClientType, clientVersion, locale, etag string) (NoticeMessages, *Response, error) { url := fmt.Sprintf("/system/notices/%s?lastViewed=%d&client=%s&clientVersion=%s&locale=%s", teamId, lastViewed, client, clientVersion, locale) - r, err := c.DoApiGet(url, etag) + r, err := c.DoAPIGet(url, etag) if err != nil { return nil, BuildResponse(r), err } @@ -6349,7 +6349,7 @@ func (c *Client4) GetNotices(lastViewed int64, teamId string, client NoticeClien } func (c *Client4) MarkNoticesViewed(ids []string) (*Response, error) { - r, err := c.DoApiPut("/system/notices/view", ArrayToJson(ids)) + r, err := c.DoAPIPut("/system/notices/view", ArrayToJson(ids)) if err != nil { return BuildResponse(r), err } @@ -6363,7 +6363,7 @@ func (c *Client4) CreateUpload(us *UploadSession) (*UploadSession, *Response, er if err != nil { return nil, nil, NewAppError("CreateUpload", "api.marshal_error", nil, err.Error(), http.StatusInternalServerError) } - r, err := c.doApiPostBytes(c.uploadsRoute(), buf) + r, err := c.DoAPIPostBytes(c.uploadsRoute(), buf) if err != nil { return nil, BuildResponse(r), err } @@ -6373,7 +6373,7 @@ func (c *Client4) CreateUpload(us *UploadSession) (*UploadSession, *Response, er // GetUpload returns the upload session for the specified uploadId. func (c *Client4) GetUpload(uploadId string) (*UploadSession, *Response, error) { - r, err := c.DoApiGet(c.uploadRoute(uploadId), "") + r, err := c.DoAPIGet(c.uploadRoute(uploadId), "") if err != nil { return nil, BuildResponse(r), err } @@ -6384,7 +6384,7 @@ func (c *Client4) GetUpload(uploadId string) (*UploadSession, *Response, error) // GetUploadsForUser returns the upload sessions created by the specified // userId. func (c *Client4) GetUploadsForUser(userId string) ([]*UploadSession, *Response, error) { - r, err := c.DoApiGet(c.userRoute(userId)+"/uploads", "") + r, err := c.DoAPIGet(c.userRoute(userId)+"/uploads", "") if err != nil { return nil, BuildResponse(r), err } @@ -6396,7 +6396,7 @@ func (c *Client4) GetUploadsForUser(userId string) ([]*UploadSession, *Response, // a FileInfo object. func (c *Client4) UploadData(uploadId string, data io.Reader) (*FileInfo, *Response, error) { url := c.uploadRoute(uploadId) - r, err := c.doApiRequestReader("POST", c.ApiUrl+url, data, nil) + r, err := c.DoAPIRequestReader("POST", c.APIURL+url, data, nil) if err != nil { return nil, BuildResponse(r), err } @@ -6406,7 +6406,7 @@ func (c *Client4) UploadData(uploadId string, data io.Reader) (*FileInfo, *Respo func (c *Client4) UpdatePassword(userId, currentPassword, newPassword string) (*Response, error) { requestBody := map[string]string{"current_password": currentPassword, "new_password": newPassword} - r, err := c.DoApiPut(c.userRoute(userId)+"/password", MapToJson(requestBody)) + r, err := c.DoAPIPut(c.userRoute(userId)+"/password", MapToJson(requestBody)) if err != nil { return BuildResponse(r), err } @@ -6417,7 +6417,7 @@ func (c *Client4) UpdatePassword(userId, currentPassword, newPassword string) (* // Cloud Section func (c *Client4) GetCloudProducts() ([]*Product, *Response, error) { - r, err := c.DoApiGet(c.cloudRoute()+"/products", "") + r, err := c.DoAPIGet(c.cloudRoute()+"/products", "") if err != nil { return nil, BuildResponse(r), err } @@ -6430,7 +6430,7 @@ func (c *Client4) GetCloudProducts() ([]*Product, *Response, error) { } func (c *Client4) CreateCustomerPayment() (*StripeSetupIntent, *Response, error) { - r, err := c.DoApiPost(c.cloudRoute()+"/payment", "") + r, err := c.DoAPIPost(c.cloudRoute()+"/payment", "") if err != nil { return nil, BuildResponse(r), err } @@ -6445,7 +6445,7 @@ func (c *Client4) CreateCustomerPayment() (*StripeSetupIntent, *Response, error) func (c *Client4) ConfirmCustomerPayment(confirmRequest *ConfirmPaymentMethodRequest) (*Response, error) { json, _ := json.Marshal(confirmRequest) - r, err := c.doApiPostBytes(c.cloudRoute()+"/payment/confirm", json) + r, err := c.DoAPIPostBytes(c.cloudRoute()+"/payment/confirm", json) if err != nil { return BuildResponse(r), err } @@ -6455,7 +6455,7 @@ func (c *Client4) ConfirmCustomerPayment(confirmRequest *ConfirmPaymentMethodReq } func (c *Client4) GetCloudCustomer() (*CloudCustomer, *Response, error) { - r, err := c.DoApiGet(c.cloudRoute()+"/customer", "") + r, err := c.DoAPIGet(c.cloudRoute()+"/customer", "") if err != nil { return nil, BuildResponse(r), err } @@ -6468,7 +6468,7 @@ func (c *Client4) GetCloudCustomer() (*CloudCustomer, *Response, error) { } func (c *Client4) GetSubscription() (*Subscription, *Response, error) { - r, err := c.DoApiGet(c.cloudRoute()+"/subscription", "") + r, err := c.DoAPIGet(c.cloudRoute()+"/subscription", "") if err != nil { return nil, BuildResponse(r), err } @@ -6481,7 +6481,7 @@ func (c *Client4) GetSubscription() (*Subscription, *Response, error) { } func (c *Client4) GetSubscriptionStats() (*SubscriptionStats, *Response, error) { - r, err := c.DoApiGet(c.cloudRoute()+"/subscription/stats", "") + r, err := c.DoAPIGet(c.cloudRoute()+"/subscription/stats", "") if err != nil { return nil, BuildResponse(r), err } @@ -6493,7 +6493,7 @@ func (c *Client4) GetSubscriptionStats() (*SubscriptionStats, *Response, error) } func (c *Client4) GetInvoicesForSubscription() ([]*Invoice, *Response, error) { - r, err := c.DoApiGet(c.cloudRoute()+"/subscription/invoices", "") + r, err := c.DoAPIGet(c.cloudRoute()+"/subscription/invoices", "") if err != nil { return nil, BuildResponse(r), err } @@ -6508,7 +6508,7 @@ func (c *Client4) GetInvoicesForSubscription() ([]*Invoice, *Response, error) { func (c *Client4) UpdateCloudCustomer(customerInfo *CloudCustomerInfo) (*CloudCustomer, *Response, error) { customerBytes, _ := json.Marshal(customerInfo) - r, err := c.doApiPutBytes(c.cloudRoute()+"/customer", customerBytes) + r, err := c.DoAPIPutBytes(c.cloudRoute()+"/customer", customerBytes) if err != nil { return nil, BuildResponse(r), err } @@ -6523,7 +6523,7 @@ func (c *Client4) UpdateCloudCustomer(customerInfo *CloudCustomerInfo) (*CloudCu func (c *Client4) UpdateCloudCustomerAddress(address *Address) (*CloudCustomer, *Response, error) { addressBytes, _ := json.Marshal(address) - r, err := c.doApiPutBytes(c.cloudRoute()+"/customer/address", addressBytes) + r, err := c.DoAPIPutBytes(c.cloudRoute()+"/customer/address", addressBytes) if err != nil { return nil, BuildResponse(r), err } @@ -6536,7 +6536,7 @@ func (c *Client4) UpdateCloudCustomerAddress(address *Address) (*CloudCustomer, } func (c *Client4) ListImports() ([]string, *Response, error) { - r, err := c.DoApiGet(c.importsRoute(), "") + r, err := c.DoAPIGet(c.importsRoute(), "") if err != nil { return nil, BuildResponse(r), err } @@ -6545,7 +6545,7 @@ func (c *Client4) ListImports() ([]string, *Response, error) { } func (c *Client4) ListExports() ([]string, *Response, error) { - r, err := c.DoApiGet(c.exportsRoute(), "") + r, err := c.DoAPIGet(c.exportsRoute(), "") if err != nil { return nil, BuildResponse(r), err } @@ -6554,7 +6554,7 @@ func (c *Client4) ListExports() ([]string, *Response, error) { } func (c *Client4) DeleteExport(name string) (*Response, error) { - r, err := c.DoApiDelete(c.exportRoute(name)) + r, err := c.DoAPIDelete(c.exportRoute(name)) if err != nil { return BuildResponse(r), err } @@ -6569,7 +6569,7 @@ func (c *Client4) DownloadExport(name string, wr io.Writer, offset int64) (int64 HeaderRange: fmt.Sprintf("bytes=%d-", offset), } } - r, err := c.DoApiRequestWithHeaders(http.MethodGet, c.ApiUrl+c.exportRoute(name), "", headers) + r, err := c.DoAPIRequestWithHeaders(http.MethodGet, c.APIURL+c.exportRoute(name), "", headers) if err != nil { return 0, BuildResponse(r), err } @@ -6609,7 +6609,7 @@ func (c *Client4) GetUserThreads(userId, teamId string, options GetUserThreadsOp url += "?" + v.Encode() } - r, err := c.DoApiGet(url, "") + r, err := c.DoAPIGet(url, "") if err != nil { return nil, BuildResponse(r), err } @@ -6626,7 +6626,7 @@ func (c *Client4) GetUserThread(userId, teamId, threadId string, extended bool) if extended { url += "?extended=true" } - r, err := c.DoApiGet(url, "") + r, err := c.DoAPIGet(url, "") if err != nil { return nil, BuildResponse(r), err } @@ -6639,7 +6639,7 @@ func (c *Client4) GetUserThread(userId, teamId, threadId string, extended bool) } func (c *Client4) UpdateThreadsReadForUser(userId, teamId string) (*Response, error) { - r, err := c.DoApiPut(fmt.Sprintf("%s/read", c.userThreadsRoute(userId, teamId)), "") + r, err := c.DoAPIPut(fmt.Sprintf("%s/read", c.userThreadsRoute(userId, teamId)), "") if err != nil { return BuildResponse(r), err } @@ -6649,7 +6649,7 @@ func (c *Client4) UpdateThreadsReadForUser(userId, teamId string) (*Response, er } func (c *Client4) UpdateThreadReadForUser(userId, teamId, threadId string, timestamp int64) (*ThreadResponse, *Response, error) { - r, err := c.DoApiPut(fmt.Sprintf("%s/read/%d", c.userThreadRoute(userId, teamId, threadId), timestamp), "") + r, err := c.DoAPIPut(fmt.Sprintf("%s/read/%d", c.userThreadRoute(userId, teamId, threadId), timestamp), "") if err != nil { return nil, BuildResponse(r), err } @@ -6664,9 +6664,9 @@ func (c *Client4) UpdateThreadFollowForUser(userId, teamId, threadId string, sta var err error var r *http.Response if state { - r, err = c.DoApiPut(c.userThreadRoute(userId, teamId, threadId)+"/following", "") + r, err = c.DoAPIPut(c.userThreadRoute(userId, teamId, threadId)+"/following", "") } else { - r, err = c.DoApiDelete(c.userThreadRoute(userId, teamId, threadId) + "/following") + r, err = c.DoAPIDelete(c.userThreadRoute(userId, teamId, threadId) + "/following") } if err != nil { return BuildResponse(r), err @@ -6677,7 +6677,7 @@ func (c *Client4) UpdateThreadFollowForUser(userId, teamId, threadId string, sta } func (c *Client4) SendAdminUpgradeRequestEmail() (*Response, error) { - r, err := c.DoApiPost(c.cloudRoute()+"/subscription/limitreached/invite", "") + r, err := c.DoAPIPost(c.cloudRoute()+"/subscription/limitreached/invite", "") if err != nil { return BuildResponse(r), err } @@ -6687,7 +6687,7 @@ func (c *Client4) SendAdminUpgradeRequestEmail() (*Response, error) { } func (c *Client4) SendAdminUpgradeRequestEmailOnJoin() (*Response, error) { - r, err := c.DoApiPost(c.cloudRoute()+"/subscription/limitreached/join", "") + r, err := c.DoAPIPost(c.cloudRoute()+"/subscription/limitreached/join", "") if err != nil { return BuildResponse(r), err } @@ -6698,7 +6698,7 @@ func (c *Client4) SendAdminUpgradeRequestEmailOnJoin() (*Response, error) { func (c *Client4) GetAllSharedChannels(teamID string, page, perPage int) ([]*SharedChannel, *Response, error) { url := fmt.Sprintf("%s/%s?page=%d&per_page=%d", c.sharedChannelsRoute(), teamID, page, perPage) - r, err := c.DoApiGet(url, "") + r, err := c.DoAPIGet(url, "") if err != nil { return nil, BuildResponse(r), err } @@ -6712,7 +6712,7 @@ func (c *Client4) GetAllSharedChannels(teamID string, page, perPage int) ([]*Sha func (c *Client4) GetRemoteClusterInfo(remoteID string) (RemoteClusterInfo, *Response, error) { url := fmt.Sprintf("%s/remote_info/%s", c.sharedChannelsRoute(), remoteID) - r, err := c.DoApiGet(url, "") + r, err := c.DoAPIGet(url, "") if err != nil { return RemoteClusterInfo{}, BuildResponse(r), err } @@ -6727,7 +6727,7 @@ func (c *Client4) GetRemoteClusterInfo(remoteID string) (RemoteClusterInfo, *Res func (c *Client4) GetAncillaryPermissions(subsectionPermissions []string) ([]string, *Response, error) { var returnedPermissions []string url := fmt.Sprintf("%s/ancillary?subsection_permissions=%s", c.permissionsRoute(), strings.Join(subsectionPermissions, ",")) - r, err := c.DoApiGet(url, "") + r, err := c.DoAPIGet(url, "") if err != nil { return returnedPermissions, BuildResponse(r), err } diff --git a/model/client4_test.go b/model/client4_test.go index a846953716..5df300fbcc 100644 --- a/model/client4_test.go +++ b/model/client4_test.go @@ -15,13 +15,13 @@ import ( // https://github.com/mattermost/mattermost-plugin-starter-template/issues/115 func TestClient4TrimTrailingSlash(t *testing.T) { slashes := []int{0, 1, 5} - baseUrl := "https://foo.com:1234" + baseURL := "https://foo.com:1234" for _, s := range slashes { - testUrl := baseUrl + strings.Repeat("/", s) - client := NewAPIv4Client(testUrl) - assert.Equal(t, baseUrl, client.Url) - assert.Equal(t, baseUrl+ApiUrlSuffix, client.ApiUrl) + testURL := baseURL + strings.Repeat("/", s) + client := NewAPIv4Client(testURL) + assert.Equal(t, baseURL, client.URL) + assert.Equal(t, baseURL+APIURLSuffix, client.APIURL) } } diff --git a/model/command.go b/model/command.go index daad03a7b2..923ed590de 100644 --- a/model/command.go +++ b/model/command.go @@ -99,7 +99,7 @@ func (o *Command) IsValid() *AppError { return NewAppError("Command.IsValid", "model.command.is_valid.url.app_error", nil, "", http.StatusBadRequest) } - if !IsValidHTTPUrl(o.URL) { + if !IsValidHTTPURL(o.URL) { return NewAppError("Command.IsValid", "model.command.is_valid.url_http.app_error", nil, "", http.StatusBadRequest) } diff --git a/model/config.go b/model/config.go index 8c118bf65a..5721bc1b92 100644 --- a/model/config.go +++ b/model/config.go @@ -99,7 +99,7 @@ const ( SitenameMaxLength = 30 - ServiceSettingsDefaultSiteUrl = "http://localhost:8065" + ServiceSettingsDefaultSiteURL = "http://localhost:8065" ServiceSettingsDefaultTLSCertFile = "" ServiceSettingsDefaultTLSKeyFile = "" ServiceSettingsDefaultReadTimeout = 300 @@ -108,8 +108,8 @@ const ( ServiceSettingsDefaultMaxLoginAttempts = 10 ServiceSettingsDefaultAllowCorsFrom = "" ServiceSettingsDefaultListenAndAddress = ":8065" - ServiceSettingsDefaultGfycatApiKey = "2_KtH_W5" - ServiceSettingsDefaultGfycatApiSecret = "3wLVZPiswc3DnaiaFoLkDvB4X0IV6CpMkj4tf2inJRsBY6-FnkT08zGmppWFgeof" + ServiceSettingsDefaultGfycatAPIKey = "2_KtH_W5" + ServiceSettingsDefaultGfycatAPISecret = "3wLVZPiswc3DnaiaFoLkDvB4X0IV6CpMkj4tf2inJRsBY6-FnkT08zGmppWFgeof" TeamSettingsDefaultSiteName = "Mattermost" TeamSettingsDefaultMaxUsersPerTeam = 50 @@ -179,12 +179,12 @@ const ( AnnouncementSettingsDefaultBannerColor = "#f2a93b" AnnouncementSettingsDefaultBannerTextColor = "#333333" - AnnouncementSettingsDefaultNoticesJsonUrl = "https://notices.mattermost.com/" + AnnouncementSettingsDefaultNoticesJsonURL = "https://notices.mattermost.com/" AnnouncementSettingsDefaultNoticesFetchFrequencySeconds = 3600 TeamSettingsDefaultTeamText = "default" - ElasticsearchSettingsDefaultConnectionUrl = "http://localhost:9200" + ElasticsearchSettingsDefaultConnectionURL = "http://localhost:9200" ElasticsearchSettingsDefaultUsername = "elastic" ElasticsearchSettingsDefaultPassword = "changeme" ElasticsearchSettingsDefaultPostIndexReplicas = 1 @@ -211,8 +211,8 @@ const ( PluginSettingsDefaultDirectory = "./plugins" PluginSettingsDefaultClientDirectory = "./client/plugins" PluginSettingsDefaultEnableMarketplace = true - PluginSettingsDefaultMarketplaceUrl = "https://api.integrations.mattermost.com" - PluginSettingsOldMarketplaceUrl = "https://marketplace.integrations.mattermost.com" + PluginSettingsDefaultMarketplaceURL = "https://api.integrations.mattermost.com" + PluginSettingsOldMarketplaceURL = "https://marketplace.integrations.mattermost.com" ComplianceExportTypeCsv = "csv" ComplianceExportTypeActiance = "actiance" @@ -230,15 +230,15 @@ const ( GoogleSettingsDefaultScope = "profile email" GoogleSettingsDefaultAuthEndpoint = "https://accounts.google.com/o/oauth2/v2/auth" GoogleSettingsDefaultTokenEndpoint = "https://www.googleapis.com/oauth2/v4/token" - GoogleSettingsDefaultUserApiEndpoint = "https://people.googleapis.com/v1/people/me?personFields=names,emailAddresses,nicknames,metadata" + GoogleSettingsDefaultUserAPIEndpoint = "https://people.googleapis.com/v1/people/me?personFields=names,emailAddresses,nicknames,metadata" Office365SettingsDefaultScope = "User.Read" Office365SettingsDefaultAuthEndpoint = "https://login.microsoftonline.com/common/oauth2/v2.0/authorize" Office365SettingsDefaultTokenEndpoint = "https://login.microsoftonline.com/common/oauth2/v2.0/token" - Office365SettingsDefaultUserApiEndpoint = "https://graph.microsoft.com/v1.0/me" + Office365SettingsDefaultUserAPIEndpoint = "https://graph.microsoft.com/v1.0/me" - CloudSettingsDefaultCwsUrl = "https://customers.mattermost.com" - CloudSettingsDefaultCwsApiUrl = "https://portal.internal.prod.cloud.mattermost.com" + CloudSettingsDefaultCwsURL = "https://customers.mattermost.com" + CloudSettingsDefaultCwsAPIURL = "https://portal.internal.prod.cloud.mattermost.com" OpenidSettingsDefaultScope = "profile openid email" LocalModeSocketPath = "/var/tmp/mattermost_local.socket" @@ -329,8 +329,8 @@ type ServiceSettings struct { WebsocketPort *int `access:"write_restrictable,cloud_restrictable"` // telemetry: none WebserverMode *string `access:"environment_web_server,write_restrictable,cloud_restrictable"` EnableGifPicker *bool `access:"integrations_gif"` - GfycatApiKey *string `access:"integrations_gif"` - GfycatApiSecret *string `access:"integrations_gif"` + GfycatAPIKey *string `access:"integrations_gif"` + GfycatAPISecret *string `access:"integrations_gif"` EnableCustomEmoji *bool `access:"site_emoji"` EnableEmojiPicker *bool `access:"site_emoji"` DEPRECATED_DO_NOT_USE_RestrictCustomEmojiCreation *string `json:"RestrictCustomEmojiCreation" mapstructure:"RestrictCustomEmojiCreation"` // Deprecated: do not use @@ -392,7 +392,7 @@ func (s *ServiceSettings) SetDefaults(isUpdate bool) { if s.SiteURL == nil { if s.EnableDeveloper != nil && *s.EnableDeveloper { - s.SiteURL = NewString(ServiceSettingsDefaultSiteUrl) + s.SiteURL = NewString(ServiceSettingsDefaultSiteURL) } else { s.SiteURL = NewString("") } @@ -683,12 +683,12 @@ func (s *ServiceSettings) SetDefaults(isUpdate bool) { s.EnableGifPicker = NewBool(true) } - if s.GfycatApiKey == nil || *s.GfycatApiKey == "" { - s.GfycatApiKey = NewString(ServiceSettingsDefaultGfycatApiKey) + if s.GfycatAPIKey == nil || *s.GfycatAPIKey == "" { + s.GfycatAPIKey = NewString(ServiceSettingsDefaultGfycatAPIKey) } - if s.GfycatApiSecret == nil || *s.GfycatApiSecret == "" { - s.GfycatApiSecret = NewString(ServiceSettingsDefaultGfycatApiSecret) + if s.GfycatAPISecret == nil || *s.GfycatAPISecret == "" { + s.GfycatAPISecret = NewString(ServiceSettingsDefaultGfycatAPISecret) } if s.DEPRECATED_DO_NOT_USE_RestrictCustomEmojiCreation == nil { @@ -1015,13 +1015,13 @@ type SSOSettings struct { Scope *string `access:"authentication_openid"` // telemetry: none AuthEndpoint *string `access:"authentication_openid"` // telemetry: none TokenEndpoint *string `access:"authentication_openid"` // telemetry: none - UserApiEndpoint *string `access:"authentication_openid"` // telemetry: none + UserAPIEndpoint *string `access:"authentication_openid"` // telemetry: none DiscoveryEndpoint *string `access:"authentication_openid"` // telemetry: none ButtonText *string `access:"authentication_openid"` // telemetry: none ButtonColor *string `access:"authentication_openid"` // telemetry: none } -func (s *SSOSettings) setDefaults(scope, authEndpoint, tokenEndpoint, userApiEndpoint, buttonColor string) { +func (s *SSOSettings) setDefaults(scope, authEndpoint, tokenEndpoint, userAPIEndpoint, buttonColor string) { if s.Enable == nil { s.Enable = NewBool(false) } @@ -1050,8 +1050,8 @@ func (s *SSOSettings) setDefaults(scope, authEndpoint, tokenEndpoint, userApiEnd s.TokenEndpoint = NewString(tokenEndpoint) } - if s.UserApiEndpoint == nil { - s.UserApiEndpoint = NewString(userApiEndpoint) + if s.UserAPIEndpoint == nil { + s.UserAPIEndpoint = NewString(userAPIEndpoint) } if s.ButtonText == nil { @@ -1070,7 +1070,7 @@ type Office365Settings struct { Scope *string `access:"authentication_openid"` AuthEndpoint *string `access:"authentication_openid"` // telemetry: none TokenEndpoint *string `access:"authentication_openid"` // telemetry: none - UserApiEndpoint *string `access:"authentication_openid"` // telemetry: none + UserAPIEndpoint *string `access:"authentication_openid"` // telemetry: none DiscoveryEndpoint *string `access:"authentication_openid"` // telemetry: none DirectoryId *string `access:"authentication_openid"` // telemetry: none } @@ -1104,8 +1104,8 @@ func (s *Office365Settings) setDefaults() { s.TokenEndpoint = NewString(Office365SettingsDefaultTokenEndpoint) } - if s.UserApiEndpoint == nil { - s.UserApiEndpoint = NewString(Office365SettingsDefaultUserApiEndpoint) + if s.UserAPIEndpoint == nil { + s.UserAPIEndpoint = NewString(Office365SettingsDefaultUserAPIEndpoint) } if s.DirectoryId == nil { @@ -1122,7 +1122,7 @@ func (s *Office365Settings) SSOSettings() *SSOSettings { ssoSettings.DiscoveryEndpoint = s.DiscoveryEndpoint ssoSettings.AuthEndpoint = s.AuthEndpoint ssoSettings.TokenEndpoint = s.TokenEndpoint - ssoSettings.UserApiEndpoint = s.UserApiEndpoint + ssoSettings.UserAPIEndpoint = s.UserAPIEndpoint return &ssoSettings } @@ -1882,7 +1882,7 @@ func (s *AnnouncementSettings) SetDefaults() { s.UserNoticesEnabled = NewBool(true) } if s.NoticesURL == nil { - s.NoticesURL = NewString(AnnouncementSettingsDefaultNoticesJsonUrl) + s.NoticesURL = NewString(AnnouncementSettingsDefaultNoticesJsonURL) } if s.NoticesSkipCache == nil { s.NoticesSkipCache = NewBool(false) @@ -2369,9 +2369,9 @@ type SamlSettings struct { Encrypt *bool `access:"authentication_saml"` SignRequest *bool `access:"authentication_saml"` - IdpUrl *string `access:"authentication_saml"` // telemetry: none - IdpDescriptorUrl *string `access:"authentication_saml"` // telemetry: none - IdpMetadataUrl *string `access:"authentication_saml"` // telemetry: none + IdpURL *string `access:"authentication_saml"` // telemetry: none + IdpDescriptorURL *string `access:"authentication_saml"` // telemetry: none + IdpMetadataURL *string `access:"authentication_saml"` // telemetry: none ServiceProviderIdentifier *string `access:"authentication_saml"` // telemetry: none AssertionConsumerServiceURL *string `access:"authentication_saml"` // telemetry: none @@ -2446,24 +2446,24 @@ func (s *SamlSettings) SetDefaults() { s.CanonicalAlgorithm = NewString(SamlSettingsDefaultCanonicalAlgorithm) } - if s.IdpUrl == nil { - s.IdpUrl = NewString("") + if s.IdpURL == nil { + s.IdpURL = NewString("") } - if s.IdpDescriptorUrl == nil { - s.IdpDescriptorUrl = NewString("") + if s.IdpDescriptorURL == nil { + s.IdpDescriptorURL = NewString("") } if s.ServiceProviderIdentifier == nil { - if s.IdpDescriptorUrl != nil { - s.ServiceProviderIdentifier = NewString(*s.IdpDescriptorUrl) + if s.IdpDescriptorURL != nil { + s.ServiceProviderIdentifier = NewString(*s.IdpDescriptorURL) } else { s.ServiceProviderIdentifier = NewString("") } } - if s.IdpMetadataUrl == nil { - s.IdpMetadataUrl = NewString("") + if s.IdpMetadataURL == nil { + s.IdpMetadataURL = NewString("") } if s.IdpCertificateFile == nil { @@ -2571,7 +2571,7 @@ func (s *NativeAppSettings) SetDefaults() { } type ElasticsearchSettings struct { - ConnectionUrl *string `access:"environment_elasticsearch,write_restrictable,cloud_restrictable"` + ConnectionURL *string `access:"environment_elasticsearch,write_restrictable,cloud_restrictable"` Username *string `access:"environment_elasticsearch,write_restrictable,cloud_restrictable"` Password *string `access:"environment_elasticsearch,write_restrictable,cloud_restrictable"` EnableIndexing *bool `access:"environment_elasticsearch,write_restrictable,cloud_restrictable"` @@ -2595,8 +2595,8 @@ type ElasticsearchSettings struct { } func (s *ElasticsearchSettings) SetDefaults() { - if s.ConnectionUrl == nil { - s.ConnectionUrl = NewString(ElasticsearchSettingsDefaultConnectionUrl) + if s.ConnectionURL == nil { + s.ConnectionURL = NewString(ElasticsearchSettingsDefaultConnectionURL) } if s.Username == nil { @@ -2761,16 +2761,16 @@ func (s *JobSettings) SetDefaults() { } type CloudSettings struct { - CWSUrl *string `access:"write_restrictable"` - CWSAPIUrl *string `access:"write_restrictable"` + CWSURL *string `access:"write_restrictable"` + CWSAPIURL *string `access:"write_restrictable"` } func (s *CloudSettings) SetDefaults() { - if s.CWSUrl == nil { - s.CWSUrl = NewString(CloudSettingsDefaultCwsUrl) + if s.CWSURL == nil { + s.CWSURL = NewString(CloudSettingsDefaultCwsURL) } - if s.CWSAPIUrl == nil { - s.CWSAPIUrl = NewString(CloudSettingsDefaultCwsApiUrl) + if s.CWSAPIURL == nil { + s.CWSAPIURL = NewString(CloudSettingsDefaultCwsAPIURL) } } @@ -2781,7 +2781,7 @@ type PluginState struct { type PluginSettings struct { Enable *bool `access:"plugins,write_restrictable"` EnableUploads *bool `access:"plugins,write_restrictable,cloud_restrictable"` - AllowInsecureDownloadUrl *bool `access:"plugins,write_restrictable,cloud_restrictable"` + AllowInsecureDownloadURL *bool `access:"plugins,write_restrictable,cloud_restrictable"` EnableHealthCheck *bool `access:"plugins,write_restrictable,cloud_restrictable"` Directory *string `access:"plugins,write_restrictable,cloud_restrictable"` // telemetry: none ClientDirectory *string `access:"plugins,write_restrictable,cloud_restrictable"` // telemetry: none @@ -2791,9 +2791,9 @@ type PluginSettings struct { EnableRemoteMarketplace *bool `access:"plugins,write_restrictable,cloud_restrictable"` AutomaticPrepackagedPlugins *bool `access:"plugins,write_restrictable,cloud_restrictable"` RequirePluginSignature *bool `access:"plugins,write_restrictable,cloud_restrictable"` - MarketplaceUrl *string `access:"plugins,write_restrictable,cloud_restrictable"` + MarketplaceURL *string `access:"plugins,write_restrictable,cloud_restrictable"` SignaturePublicKeyFiles []string `access:"plugins,write_restrictable,cloud_restrictable"` - ChimeraOAuthProxyUrl *string `access:"plugins,write_restrictable,cloud_restrictable"` + ChimeraOAuthProxyURL *string `access:"plugins,write_restrictable,cloud_restrictable"` } func (s *PluginSettings) SetDefaults(ls LogSettings) { @@ -2805,8 +2805,8 @@ func (s *PluginSettings) SetDefaults(ls LogSettings) { s.EnableUploads = NewBool(false) } - if s.AllowInsecureDownloadUrl == nil { - s.AllowInsecureDownloadUrl = NewBool(false) + if s.AllowInsecureDownloadURL == nil { + s.AllowInsecureDownloadURL = NewBool(false) } if s.EnableHealthCheck == nil { @@ -2856,8 +2856,8 @@ func (s *PluginSettings) SetDefaults(ls LogSettings) { s.AutomaticPrepackagedPlugins = NewBool(true) } - if s.MarketplaceUrl == nil || *s.MarketplaceUrl == "" || *s.MarketplaceUrl == PluginSettingsOldMarketplaceUrl { - s.MarketplaceUrl = NewString(PluginSettingsDefaultMarketplaceUrl) + if s.MarketplaceURL == nil || *s.MarketplaceURL == "" || *s.MarketplaceURL == PluginSettingsOldMarketplaceURL { + s.MarketplaceURL = NewString(PluginSettingsDefaultMarketplaceURL) } if s.RequirePluginSignature == nil { @@ -2868,8 +2868,8 @@ func (s *PluginSettings) SetDefaults(ls LogSettings) { s.SignaturePublicKeyFiles = []string{} } - if s.ChimeraOAuthProxyUrl == nil { - s.ChimeraOAuthProxyUrl = NewString("") + if s.ChimeraOAuthProxyURL == nil { + s.ChimeraOAuthProxyURL = NewString("") } } @@ -2943,14 +2943,14 @@ func (s *MessageExportSettings) SetDefaults() { } type DisplaySettings struct { - CustomUrlSchemes []string `access:"site_customization"` + CustomURLSchemes []string `access:"site_customization"` ExperimentalTimezone *bool `access:"experimental_features"` } func (s *DisplaySettings) SetDefaults() { - if s.CustomUrlSchemes == nil { - customUrlSchemes := []string{} - s.CustomUrlSchemes = customUrlSchemes + if s.CustomURLSchemes == nil { + customURLSchemes := []string{} + s.CustomURLSchemes = customURLSchemes } if s.ExperimentalTimezone == nil { @@ -3245,7 +3245,7 @@ func (o *Config) SetDefaults() { o.Office365Settings.setDefaults() o.Office365Settings.setDefaults() o.GitLabSettings.setDefaults("", "", "", "", "") - o.GoogleSettings.setDefaults(GoogleSettingsDefaultScope, GoogleSettingsDefaultAuthEndpoint, GoogleSettingsDefaultTokenEndpoint, GoogleSettingsDefaultUserApiEndpoint, "") + o.GoogleSettings.setDefaults(GoogleSettingsDefaultScope, GoogleSettingsDefaultAuthEndpoint, GoogleSettingsDefaultTokenEndpoint, GoogleSettingsDefaultUserAPIEndpoint, "") o.OpenIdSettings.setDefaults(OpenidSettingsDefaultScope, "", "", "", "#145DBF") o.ServiceSettings.SetDefaults(isUpdate) o.PasswordSettings.SetDefaults() @@ -3547,11 +3547,11 @@ func (s *LdapSettings) isValid() *AppError { func (s *SamlSettings) isValid() *AppError { if *s.Enable { - if *s.IdpUrl == "" || !IsValidHTTPUrl(*s.IdpUrl) { + if *s.IdpURL == "" || !IsValidHTTPURL(*s.IdpURL) { return NewAppError("Config.IsValid", "model.config.is_valid.saml_idp_url.app_error", nil, "", http.StatusBadRequest) } - if *s.IdpDescriptorUrl == "" || !IsValidHTTPUrl(*s.IdpDescriptorUrl) { + if *s.IdpDescriptorURL == "" || !IsValidHTTPURL(*s.IdpDescriptorURL) { return NewAppError("Config.IsValid", "model.config.is_valid.saml_idp_descriptor_url.app_error", nil, "", http.StatusBadRequest) } @@ -3572,7 +3572,7 @@ func (s *SamlSettings) isValid() *AppError { } if *s.Verify { - if *s.AssertionConsumerServiceURL == "" || !IsValidHTTPUrl(*s.AssertionConsumerServiceURL) { + if *s.AssertionConsumerServiceURL == "" || !IsValidHTTPURL(*s.AssertionConsumerServiceURL) { return NewAppError("Config.IsValid", "model.config.is_valid.saml_assertion_consumer_service_url.app_error", nil, "", http.StatusBadRequest) } } @@ -3708,7 +3708,7 @@ func (s *ServiceSettings) isValid() *AppError { func (s *ElasticsearchSettings) isValid() *AppError { if *s.EnableIndexing { - if *s.ConnectionUrl == "" { + if *s.ConnectionURL == "" { return NewAppError("Config.IsValid", "model.config.is_valid.elastic_search.connection_url.app_error", nil, "", http.StatusBadRequest) } } @@ -3827,10 +3827,10 @@ func (s *MessageExportSettings) isValid() *AppError { } func (s *DisplaySettings) isValid() *AppError { - if len(s.CustomUrlSchemes) != 0 { + if len(s.CustomURLSchemes) != 0 { validProtocolPattern := regexp.MustCompile(`(?i)^\s*[A-Za-z][A-Za-z0-9.+-]*\s*$`) - for _, scheme := range s.CustomUrlSchemes { + for _, scheme := range s.CustomURLSchemes { if !validProtocolPattern.MatchString(scheme) { return NewAppError( "Config.IsValid", @@ -3923,8 +3923,8 @@ func (o *Config) Sanitize() { *o.MessageExportSettings.GlobalRelaySettings.SMTPPassword = FakeSetting } - if o.ServiceSettings.GfycatApiSecret != nil && *o.ServiceSettings.GfycatApiSecret != "" { - *o.ServiceSettings.GfycatApiSecret = FakeSetting + if o.ServiceSettings.GfycatAPISecret != nil && *o.ServiceSettings.GfycatAPISecret != "" { + *o.ServiceSettings.GfycatAPISecret = FakeSetting } *o.ServiceSettings.SplitKey = FakeSetting @@ -4046,7 +4046,7 @@ func isDomainName(s string) bool { func isSafeLink(link *string) bool { if link != nil { - if IsValidHTTPUrl(*link) { + if IsValidHTTPURL(*link) { return true } else if strings.HasPrefix(*link, "/") { return true diff --git a/model/config_test.go b/model/config_test.go index 2df9b7733f..be1483d0de 100644 --- a/model/config_test.go +++ b/model/config_test.go @@ -73,7 +73,7 @@ func TestConfigEnableDeveloper(t *testing.T) { EnableDeveloper *bool ExpectedSiteURL string }{ - {"enable developer is true", NewBool(true), ServiceSettingsDefaultSiteUrl}, + {"enable developer is true", NewBool(true), ServiceSettingsDefaultSiteURL}, {"enable developer is false", NewBool(false), ""}, {"enable developer is nil", nil, ""}, } @@ -144,8 +144,8 @@ func TestConfigIsValidDefaultAlgorithms(t *testing.T) { *c1.SamlSettings.Verify = false *c1.SamlSettings.Encrypt = false - *c1.SamlSettings.IdpUrl = "http://test.url.com" - *c1.SamlSettings.IdpDescriptorUrl = "http://test.url.com" + *c1.SamlSettings.IdpURL = "http://test.url.com" + *c1.SamlSettings.IdpDescriptorURL = "http://test.url.com" *c1.SamlSettings.IdpCertificateFile = "certificatefile" *c1.SamlSettings.ServiceProviderIdentifier = "http://test.url.com" *c1.SamlSettings.EmailAttribute = "Email" @@ -161,8 +161,8 @@ func TestConfigServiceProviderDefault(t *testing.T) { Enable: NewBool(true), Verify: NewBool(false), Encrypt: NewBool(false), - IdpUrl: NewString("http://test.url.com"), - IdpDescriptorUrl: NewString("http://test2.url.com"), + IdpURL: NewString("http://test.url.com"), + IdpDescriptorURL: NewString("http://test2.url.com"), IdpCertificateFile: NewString("certificatefile"), EmailAttribute: NewString("Email"), UsernameAttribute: NewString("Username"), @@ -170,7 +170,7 @@ func TestConfigServiceProviderDefault(t *testing.T) { } c1.SetDefaults() - assert.Equal(t, *c1.SamlSettings.ServiceProviderIdentifier, *c1.SamlSettings.IdpDescriptorUrl) + assert.Equal(t, *c1.SamlSettings.ServiceProviderIdentifier, *c1.SamlSettings.IdpDescriptorURL) err := c1.SamlSettings.isValid() require.Nil(t, err) @@ -184,9 +184,9 @@ func TestConfigIsValidFakeAlgorithm(t *testing.T) { *c1.SamlSettings.Verify = false *c1.SamlSettings.Encrypt = false - *c1.SamlSettings.IdpUrl = "http://test.url.com" - *c1.SamlSettings.IdpDescriptorUrl = "http://test.url.com" - *c1.SamlSettings.IdpMetadataUrl = "http://test.url.com" + *c1.SamlSettings.IdpURL = "http://test.url.com" + *c1.SamlSettings.IdpDescriptorURL = "http://test.url.com" + *c1.SamlSettings.IdpMetadataURL = "http://test.url.com" *c1.SamlSettings.IdpCertificateFile = "certificatefile" *c1.SamlSettings.ServiceProviderIdentifier = "http://test.url.com" *c1.SamlSettings.EmailAttribute = "Email" @@ -688,7 +688,7 @@ func TestMessageExportSetDefaultsExportDisabledExportFromTimestampNonZero(t *tes require.Equal(t, 10000, *mes.BatchSize) } -func TestDisplaySettingsIsValidCustomUrlSchemes(t *testing.T) { +func TestDisplaySettingsIsValidCustomURLSchemes(t *testing.T) { tests := []struct { name string value []string @@ -760,12 +760,12 @@ func TestDisplaySettingsIsValidCustomUrlSchemes(t *testing.T) { ds := &DisplaySettings{} ds.SetDefaults() - ds.CustomUrlSchemes = test.value + ds.CustomURLSchemes = test.value if err := ds.isValid(); err != nil && test.valid { - t.Error("Expected CustomUrlSchemes to be valid but got error:", err) + t.Error("Expected CustomURLSchemes to be valid but got error:", err) } else if err == nil && !test.valid { - t.Error("Expected CustomUrlSchemes to be invalid but got no error") + t.Error("Expected CustomURLSchemes to be invalid but got no error") } }) } @@ -1368,29 +1368,29 @@ func TestConfigMarketplaceDefaults(t *testing.T) { c.SetDefaults() require.True(t, *c.PluginSettings.EnableMarketplace) - require.Equal(t, PluginSettingsDefaultMarketplaceUrl, *c.PluginSettings.MarketplaceUrl) + require.Equal(t, PluginSettingsDefaultMarketplaceURL, *c.PluginSettings.MarketplaceURL) }) t.Run("old marketplace url", func(t *testing.T) { c := Config{} c.SetDefaults() - *c.PluginSettings.MarketplaceUrl = PluginSettingsOldMarketplaceUrl + *c.PluginSettings.MarketplaceURL = PluginSettingsOldMarketplaceURL c.SetDefaults() require.True(t, *c.PluginSettings.EnableMarketplace) - require.Equal(t, PluginSettingsDefaultMarketplaceUrl, *c.PluginSettings.MarketplaceUrl) + require.Equal(t, PluginSettingsDefaultMarketplaceURL, *c.PluginSettings.MarketplaceURL) }) t.Run("custom marketplace url", func(t *testing.T) { c := Config{} c.SetDefaults() - *c.PluginSettings.MarketplaceUrl = "https://marketplace.example.com" + *c.PluginSettings.MarketplaceURL = "https://marketplace.example.com" c.SetDefaults() require.True(t, *c.PluginSettings.EnableMarketplace) - require.Equal(t, "https://marketplace.example.com", *c.PluginSettings.MarketplaceUrl) + require.Equal(t, "https://marketplace.example.com", *c.PluginSettings.MarketplaceURL) }) } diff --git a/model/manifest.go b/model/manifest.go index fe5eee7854..d37b8279fa 100644 --- a/model/manifest.go +++ b/model/manifest.go @@ -321,15 +321,15 @@ func (m *Manifest) IsValid() error { return errors.New("a plugin name is needed") } - if m.HomepageURL != "" && !IsValidHTTPUrl(m.HomepageURL) { + if m.HomepageURL != "" && !IsValidHTTPURL(m.HomepageURL) { return errors.New("invalid HomepageURL") } - if m.SupportURL != "" && !IsValidHTTPUrl(m.SupportURL) { + if m.SupportURL != "" && !IsValidHTTPURL(m.SupportURL) { return errors.New("invalid SupportURL") } - if m.ReleaseNotesURL != "" && !IsValidHTTPUrl(m.ReleaseNotesURL) { + if m.ReleaseNotesURL != "" && !IsValidHTTPURL(m.ReleaseNotesURL) { return errors.New("invalid ReleaseNotesURL") } diff --git a/model/oauth.go b/model/oauth.go index b663e2359a..7e32908eb1 100644 --- a/model/oauth.go +++ b/model/oauth.go @@ -66,12 +66,12 @@ func (a *OAuthApp) IsValid() *AppError { } for _, callback := range a.CallbackUrls { - if !IsValidHTTPUrl(callback) { + if !IsValidHTTPURL(callback) { return NewAppError("OAuthApp.IsValid", "model.oauth.is_valid.callback.app_error", nil, "", http.StatusBadRequest) } } - if a.Homepage == "" || len(a.Homepage) > 256 || !IsValidHTTPUrl(a.Homepage) { + if a.Homepage == "" || len(a.Homepage) > 256 || !IsValidHTTPURL(a.Homepage) { return NewAppError("OAuthApp.IsValid", "model.oauth.is_valid.homepage.app_error", nil, "app_id="+a.Id, http.StatusBadRequest) } @@ -80,7 +80,7 @@ func (a *OAuthApp) IsValid() *AppError { } if a.IconURL != "" { - if len(a.IconURL) > 512 || !IsValidHTTPUrl(a.IconURL) { + if len(a.IconURL) > 512 || !IsValidHTTPURL(a.IconURL) { return NewAppError("OAuthApp.IsValid", "model.oauth.is_valid.icon_url.app_error", nil, "app_id="+a.Id, http.StatusBadRequest) } } diff --git a/model/outgoing_webhook.go b/model/outgoing_webhook.go index 36fd2c1cab..10abbd52e0 100644 --- a/model/outgoing_webhook.go +++ b/model/outgoing_webhook.go @@ -165,7 +165,7 @@ func (o *OutgoingWebhook) IsValid() *AppError { } for _, callback := range o.CallbackURLs { - if !IsValidHTTPUrl(callback) { + if !IsValidHTTPURL(callback) { return NewAppError("OutgoingWebhook.IsValid", "model.outgoing_hook.is_valid.url.app_error", nil, "", http.StatusBadRequest) } } diff --git a/model/permission.go b/model/permission.go index 863d538d74..6c10bab053 100644 --- a/model/permission.go +++ b/model/permission.go @@ -108,7 +108,7 @@ var PermissionCreateComplianceExportJob *Permission var PermissionReadComplianceExportJob *Permission var PermissionReadAudits *Permission var PermissionTestElasticsearch *Permission -var PermissionTestSiteUrl *Permission +var PermissionTestSiteURL *Permission var PermissionTestS3 *Permission var PermissionReloadConfig *Permission var PermissionInvalidateCaches *Permission @@ -909,7 +909,7 @@ func initializePermissions() { PermissionScopeSystem, } - PermissionTestSiteUrl = &Permission{ + PermissionTestSiteURL = &Permission{ "test_site_url", "", "", @@ -2048,7 +2048,7 @@ func initializePermissions() { PermissionCreateComplianceExportJob, PermissionReadComplianceExportJob, PermissionReadAudits, - PermissionTestSiteUrl, + PermissionTestSiteURL, PermissionTestElasticsearch, PermissionTestS3, PermissionReloadConfig, diff --git a/model/post.go b/model/post.go index 59f46522e0..0a4a7470e1 100644 --- a/model/post.go +++ b/model/post.go @@ -62,7 +62,7 @@ const ( PostPropsAddedUserId = "addedUserId" PostPropsDeleteBy = "deleteBy" - PostPropsOverrideIconUrl = "override_icon_url" + PostPropsOverrideIconURL = "override_icon_url" PostPropsOverrideIconEmoji = "override_icon_emoji" PostPropsMentionHighlightDisabled = "mentionHighlightDisabled" diff --git a/model/push_notification.go b/model/push_notification.go index 59bf982cb0..a8b214ff85 100644 --- a/model/push_notification.go +++ b/model/push_notification.go @@ -64,7 +64,7 @@ type PushNotification struct { SenderId string `json:"sender_id,omitempty"` SenderName string `json:"sender_name,omitempty"` OverrideUsername string `json:"override_username,omitempty"` - OverrideIconUrl string `json:"override_icon_url,omitempty"` + OverrideIconURL string `json:"override_icon_url,omitempty"` FromWebhook string `json:"from_webhook,omitempty"` Version string `json:"version,omitempty"` IsIdLoaded bool `json:"is_id_loaded"` diff --git a/model/role.go b/model/role.go index 8a44258d16..b0020e9e24 100644 --- a/model/role.go +++ b/model/role.go @@ -73,7 +73,7 @@ func init() { PermissionReadElasticsearchPostAggregationJob, }, PermissionSysconsoleWriteEnvironmentWebServer.Id: { - PermissionTestSiteUrl, + PermissionTestSiteURL, PermissionReloadConfig, PermissionInvalidateCaches, }, diff --git a/model/saml.go b/model/saml.go index 99b023957f..2723e78537 100644 --- a/model/saml.go +++ b/model/saml.go @@ -31,8 +31,8 @@ type SamlCertificateStatus struct { } type SamlMetadataResponse struct { - IdpDescriptorUrl string `json:"idp_descriptor_url"` - IdpUrl string `json:"idp_url"` + IdpDescriptorURL string `json:"idp_descriptor_url"` + IdpURL string `json:"idp_url"` IdpPublicCertificate string `json:"idp_public_certificate"` } diff --git a/model/utils.go b/model/utils.go index 66a383cc98..e599538f81 100644 --- a/model/utils.go +++ b/model/utils.go @@ -487,12 +487,12 @@ func ClearMentionTags(post string) string { return post } -func IsValidHTTPUrl(rawUrl string) bool { - if strings.Index(rawUrl, "http://") != 0 && strings.Index(rawUrl, "https://") != 0 { +func IsValidHTTPURL(rawURL string) bool { + if strings.Index(rawURL, "http://") != 0 && strings.Index(rawURL, "https://") != 0 { return false } - if u, err := url.ParseRequestURI(rawUrl); err != nil || u.Scheme == "" || u.Host == "" { + if u, err := url.ParseRequestURI(rawURL); err != nil || u.Scheme == "" || u.Host == "" { return false } diff --git a/model/utils_test.go b/model/utils_test.go index 18ba3ee771..163491c00b 100644 --- a/model/utils_test.go +++ b/model/utils_test.go @@ -855,7 +855,7 @@ func TestSanitizeUnicode(t *testing.T) { } } -func TestIsValidHTTPUrl(t *testing.T) { +func TestIsValidHTTPURL(t *testing.T) { t.Parallel() testCases := []struct { @@ -940,7 +940,7 @@ func TestIsValidHTTPUrl(t *testing.T) { }() t.Parallel() - require.Equal(t, testCase.Expected, IsValidHTTPUrl(testCase.Value)) + require.Equal(t, testCase.Expected, IsValidHTTPURL(testCase.Value)) }) } } diff --git a/model/websocket_client.go b/model/websocket_client.go index d1259231a0..c1415fa9b9 100644 --- a/model/websocket_client.go +++ b/model/websocket_client.go @@ -37,9 +37,9 @@ const avgReadMsgSizeBytes = 1024 // A client must read from PingTimeoutChannel, EventChannel and ResponseChannel to prevent // deadlocks from occurring in the program. type WebSocketClient struct { - Url string // The location of the server like "ws://localhost:8065" - ApiUrl string // The API location of the server like "ws://localhost:8065/api/v3" - ConnectUrl string // The WebSocket URL to connect to like "ws://localhost:8065/api/v3/path/to/websocket" + URL string // The location of the server like "ws://localhost:8065" + APIURL string // The API location of the server like "ws://localhost:8065/api/v3" + ConnectURL string // The WebSocket URL to connect to like "ws://localhost:8065/api/v3/path/to/websocket" Conn *websocket.Conn // The WebSocket connection AuthToken string // The token used to open the WebSocket connection Sequence int64 // The ever-incrementing sequence attached to each WebSocket action @@ -66,15 +66,15 @@ func NewWebSocketClient(url, authToken string) (*WebSocketClient, error) { // NewWebSocketClientWithDialer constructs a new WebSocket client with convenience // methods for talking to the server using a custom dialer. func NewWebSocketClientWithDialer(dialer *websocket.Dialer, url, authToken string) (*WebSocketClient, error) { - conn, _, err := dialer.Dial(url+ApiUrlSuffix+"/websocket", nil) + conn, _, err := dialer.Dial(url+APIURLSuffix+"/websocket", nil) if err != nil { return nil, NewAppError("NewWebSocketClient", "model.websocket_client.connect_fail.app_error", nil, err.Error(), http.StatusInternalServerError) } client := &WebSocketClient{ - Url: url, - ApiUrl: url + ApiUrlSuffix, - ConnectUrl: url + ApiUrlSuffix + "/websocket", + URL: url, + APIURL: url + APIURLSuffix, + ConnectURL: url + APIURLSuffix + "/websocket", Conn: conn, AuthToken: authToken, Sequence: 1, @@ -107,17 +107,17 @@ func NewWebSocketClient4WithDialer(dialer *websocket.Dialer, url, authToken stri return NewWebSocketClientWithDialer(dialer, url, authToken) } -// Connect creates a websocket connection with the given ConnectUrl. +// Connect creates a websocket connection with the given ConnectURL. // This is racy and error-prone should not be used. Use any of the New* functions to create a websocket. func (wsc *WebSocketClient) Connect() *AppError { return wsc.ConnectWithDialer(websocket.DefaultDialer) } -// ConnectWithDialer creates a websocket connection with the given ConnectUrl using the dialer. +// ConnectWithDialer creates a websocket connection with the given ConnectURL using the dialer. // This is racy and error-prone and should not be used. Use any of the New* functions to create a websocket. func (wsc *WebSocketClient) ConnectWithDialer(dialer *websocket.Dialer) *AppError { var err error - wsc.Conn, _, err = dialer.Dial(wsc.ConnectUrl, nil) + wsc.Conn, _, err = dialer.Dial(wsc.ConnectURL, nil) if err != nil { return NewAppError("Connect", "model.websocket_client.connect_fail.app_error", nil, err.Error(), http.StatusInternalServerError) } diff --git a/plugin/api_timer_layer_generated.go b/plugin/api_timer_layer_generated.go index 17c8aaaff4..ba066a7267 100644 --- a/plugin/api_timer_layer_generated.go +++ b/plugin/api_timer_layer_generated.go @@ -24,7 +24,7 @@ type apiTimerLayer struct { func (api *apiTimerLayer) recordTime(startTime timePkg.Time, name string, success bool) { if api.metrics != nil { elapsedTime := float64(timePkg.Since(startTime)) / float64(timePkg.Second) - api.metrics.ObservePluginApiDuration(api.pluginID, name, success, elapsedTime) + api.metrics.ObservePluginAPIDuration(api.pluginID, name, success, elapsedTime) } } diff --git a/plugin/interface_generator/main.go b/plugin/interface_generator/main.go index 6ee6d60d69..a6217d20b4 100644 --- a/plugin/interface_generator/main.go +++ b/plugin/interface_generator/main.go @@ -386,7 +386,7 @@ type apiTimerLayer struct { func (api *apiTimerLayer) recordTime(startTime timePkg.Time, name string, success bool) { if api.metrics != nil { elapsedTime := float64(timePkg.Since(startTime)) / float64(timePkg.Second) - api.metrics.ObservePluginApiDuration(api.pluginID, name, success, elapsedTime) + api.metrics.ObservePluginAPIDuration(api.pluginID, name, success, elapsedTime) } } diff --git a/scripts/config_generator/main_test.go b/scripts/config_generator/main_test.go index 09c22a9691..be54cf5936 100644 --- a/scripts/config_generator/main_test.go +++ b/scripts/config_generator/main_test.go @@ -31,11 +31,11 @@ func TestDefaultsGenerator(t *testing.T) { require.Equal(t, *config.Office365Settings.Scope, model.Office365SettingsDefaultScope) require.Equal(t, *config.Office365Settings.AuthEndpoint, model.Office365SettingsDefaultAuthEndpoint) - require.Equal(t, *config.Office365Settings.UserApiEndpoint, model.Office365SettingsDefaultUserApiEndpoint) + require.Equal(t, *config.Office365Settings.UserAPIEndpoint, model.Office365SettingsDefaultUserAPIEndpoint) require.Equal(t, *config.Office365Settings.TokenEndpoint, model.Office365SettingsDefaultTokenEndpoint) require.Equal(t, *config.GoogleSettings.Scope, model.GoogleSettingsDefaultScope) require.Equal(t, *config.GoogleSettings.AuthEndpoint, model.GoogleSettingsDefaultAuthEndpoint) - require.Equal(t, *config.GoogleSettings.UserApiEndpoint, model.GoogleSettingsDefaultUserApiEndpoint) + require.Equal(t, *config.GoogleSettings.UserAPIEndpoint, model.GoogleSettingsDefaultUserAPIEndpoint) require.Equal(t, *config.GoogleSettings.TokenEndpoint, model.GoogleSettingsDefaultTokenEndpoint) } diff --git a/services/remotecluster/sendfile.go b/services/remotecluster/sendfile.go index 87afb0d169..d94434e2bf 100644 --- a/services/remotecluster/sendfile.go +++ b/services/remotecluster/sendfile.go @@ -98,7 +98,7 @@ func (rcs *Service) sendFileToRemote(timeout time.Duration, task sendFileTask) ( if err != nil { return nil, fmt.Errorf("invalid siteURL while sending file to remote %s: %w", task.rc.RemoteId, err) } - u.Path = path.Join(u.Path, model.ApiUrlSuffix, "remotecluster", "upload", task.us.Id) + u.Path = path.Join(u.Path, model.APIURLSuffix, "remotecluster", "upload", task.us.Id) req, err := http.NewRequest("POST", u.String(), r) if err != nil { diff --git a/services/remotecluster/sendprofileImage.go b/services/remotecluster/sendprofileImage.go index 73331941a4..ff148a3472 100644 --- a/services/remotecluster/sendprofileImage.go +++ b/services/remotecluster/sendprofileImage.go @@ -99,7 +99,7 @@ func (rcs *Service) sendProfileImageToRemote(timeout time.Duration, task sendPro if err != nil { return fmt.Errorf("invalid siteURL while sending file to remote %s: %w", task.rc.RemoteId, err) } - u.Path = path.Join(u.Path, model.ApiUrlSuffix, "remotecluster", task.userID, "image") + u.Path = path.Join(u.Path, model.APIURLSuffix, "remotecluster", task.userID, "image") body := &bytes.Buffer{} writer := multipart.NewWriter(body) diff --git a/services/telemetry/telemetry.go b/services/telemetry/telemetry.go index 30d3a56a0d..d5678ac2b4 100644 --- a/services/telemetry/telemetry.go +++ b/services/telemetry/telemetry.go @@ -104,7 +104,7 @@ type TelemetryService struct { type RudderConfig struct { RudderKey string - DataplaneUrl string + DataplaneURL string } func New(srv ServerIface, dbStore store.Store, searchEngine *searchengine.Broker, log *mlog.Logger) *TelemetryService { @@ -154,8 +154,8 @@ func (ts *TelemetryService) telemetryEnabled() bool { func (ts *TelemetryService) sendDailyTelemetry(override bool) { config := ts.getRudderConfig() - if ts.telemetryEnabled() && ((config.DataplaneUrl != "" && config.RudderKey != "") || override) { - ts.initRudder(config.DataplaneUrl, config.RudderKey) + if ts.telemetryEnabled() && ((config.DataplaneURL != "" && config.RudderKey != "") || override) { + ts.initRudder(config.DataplaneURL, config.RudderKey) ts.trackActivity() ts.trackConfig() ts.trackLicense() @@ -373,8 +373,8 @@ func (ts *TelemetryService) trackConfig() { "enable_custom_emoji": *cfg.ServiceSettings.EnableCustomEmoji, "enable_emoji_picker": *cfg.ServiceSettings.EnableEmojiPicker, "enable_gif_picker": *cfg.ServiceSettings.EnableGifPicker, - "gfycat_api_key": isDefault(*cfg.ServiceSettings.GfycatApiKey, model.ServiceSettingsDefaultGfycatApiKey), - "gfycat_api_secret": isDefault(*cfg.ServiceSettings.GfycatApiSecret, model.ServiceSettingsDefaultGfycatApiSecret), + "gfycat_api_key": isDefault(*cfg.ServiceSettings.GfycatAPIKey, model.ServiceSettingsDefaultGfycatAPIKey), + "gfycat_api_secret": isDefault(*cfg.ServiceSettings.GfycatAPISecret, model.ServiceSettingsDefaultGfycatAPISecret), "experimental_enable_authentication_transfer": *cfg.ServiceSettings.ExperimentalEnableAuthenticationTransfer, "restrict_custom_emoji_creation": *cfg.ServiceSettings.DEPRECATED_DO_NOT_USE_RestrictCustomEmojiCreation, "enable_testing": cfg.ServiceSettings.EnableTesting, @@ -393,7 +393,7 @@ func (ts *TelemetryService) trackConfig() { "session_length_sso_in_days": *cfg.ServiceSettings.SessionLengthSSOInDays, "session_cache_in_minutes": *cfg.ServiceSettings.SessionCacheInMinutes, "session_idle_timeout_in_minutes": *cfg.ServiceSettings.SessionIdleTimeoutInMinutes, - "isdefault_site_url": isDefault(*cfg.ServiceSettings.SiteURL, model.ServiceSettingsDefaultSiteUrl), + "isdefault_site_url": isDefault(*cfg.ServiceSettings.SiteURL, model.ServiceSettingsDefaultSiteURL), "isdefault_tls_cert_file": isDefault(*cfg.ServiceSettings.TLSCertFile, model.ServiceSettingsDefaultTLSCertFile), "isdefault_tls_key_file": isDefault(*cfg.ServiceSettings.TLSKeyFile, model.ServiceSettingsDefaultTLSKeyFile), "isdefault_read_timeout": isDefault(*cfg.ServiceSettings.ReadTimeout, model.ServiceSettingsDefaultReadTimeout), @@ -755,7 +755,7 @@ func (ts *TelemetryService) trackConfig() { }) ts.sendTelemetry(TrackConfigElasticsearch, map[string]interface{}{ - "isdefault_connection_url": isDefault(*cfg.ElasticsearchSettings.ConnectionUrl, model.ElasticsearchSettingsDefaultConnectionUrl), + "isdefault_connection_url": isDefault(*cfg.ElasticsearchSettings.ConnectionURL, model.ElasticsearchSettingsDefaultConnectionURL), "isdefault_username": isDefault(*cfg.ElasticsearchSettings.Username, model.ElasticsearchSettingsDefaultUsername), "isdefault_password": isDefault(*cfg.ElasticsearchSettings.Password, model.ElasticsearchSettingsDefaultPassword), "enable_indexing": *cfg.ElasticsearchSettings.EnableIndexing, @@ -776,7 +776,7 @@ func (ts *TelemetryService) trackConfig() { "trace": *cfg.ElasticsearchSettings.Trace, }) - ts.trackPluginConfig(cfg, model.PluginSettingsDefaultMarketplaceUrl) + ts.trackPluginConfig(cfg, model.PluginSettingsDefaultMarketplaceURL) ts.sendTelemetry(TrackConfigDataRetention, map[string]interface{}{ "enable_message_deletion": *cfg.DataRetentionSettings.EnableMessageDeletion, @@ -803,7 +803,7 @@ func (ts *TelemetryService) trackConfig() { ts.sendTelemetry(TrackConfigDisplay, map[string]interface{}{ "experimental_timezone": *cfg.DisplaySettings.ExperimentalTimezone, - "isdefault_custom_url_schemes": len(cfg.DisplaySettings.CustomUrlSchemes) != 0, + "isdefault_custom_url_schemes": len(cfg.DisplaySettings.CustomURLSchemes) != 0, }) ts.sendTelemetry(TrackConfigGuestAccounts, map[string]interface{}{ @@ -1306,15 +1306,15 @@ func (ts *TelemetryService) trackPluginConfig(cfg *model.Config, marketplaceURL "enable_nps_survey": pluginSetting(&cfg.PluginSettings, "com.mattermost.nps", "enablesurvey", true), "enable": *cfg.PluginSettings.Enable, "enable_uploads": *cfg.PluginSettings.EnableUploads, - "allow_insecure_download_url": *cfg.PluginSettings.AllowInsecureDownloadUrl, + "allow_insecure_download_url": *cfg.PluginSettings.AllowInsecureDownloadURL, "enable_health_check": *cfg.PluginSettings.EnableHealthCheck, "enable_marketplace": *cfg.PluginSettings.EnableMarketplace, "require_pluginSignature": *cfg.PluginSettings.RequirePluginSignature, "enable_remote_marketplace": *cfg.PluginSettings.EnableRemoteMarketplace, "automatic_prepackaged_plugins": *cfg.PluginSettings.AutomaticPrepackagedPlugins, - "is_default_marketplace_url": isDefault(*cfg.PluginSettings.MarketplaceUrl, model.PluginSettingsDefaultMarketplaceUrl), + "is_default_marketplace_url": isDefault(*cfg.PluginSettings.MarketplaceURL, model.PluginSettingsDefaultMarketplaceURL), "signature_public_key_files": len(cfg.PluginSettings.SignaturePublicKeyFiles), - "chimera_oauth_proxy_url": *cfg.PluginSettings.ChimeraOAuthProxyUrl, + "chimera_oauth_proxy_url": *cfg.PluginSettings.ChimeraOAuthProxyURL, } // knownPluginIDs lists all known plugin IDs in the Marketplace diff --git a/services/telemetry/telemetry_test.go b/services/telemetry/telemetry_test.go index 4fe293b934..c36a358e05 100644 --- a/services/telemetry/telemetry_test.go +++ b/services/telemetry/telemetry_test.go @@ -532,7 +532,7 @@ func TestRudderTelemetry(t *testing.T) { config := telemetryService.getRudderConfig() - assert.Equal(t, "arudderstackplace", config.DataplaneUrl) + assert.Equal(t, "arudderstackplace", config.DataplaneURL) assert.Equal(t, "abc123", config.RudderKey) }) } diff --git a/services/upgrader/upgrader_linux.go b/services/upgrader/upgrader_linux.go index edbdd6cbf0..c4f65d335b 100644 --- a/services/upgrader/upgrader_linux.go +++ b/services/upgrader/upgrader_linux.go @@ -69,7 +69,7 @@ func (wc *writeCounter) Write(p []byte) (int, error) { return n, nil } -func getCurrentVersionTgzUrl() string { +func getCurrentVersionTgzURL() string { version := model.CurrentVersion if strings.HasPrefix(model.BuildNumber, version+"-rc") { version = model.BuildNumber @@ -184,24 +184,24 @@ func UpgradeToE0() error { return err } - filename, err := download(getCurrentVersionTgzUrl(), 1024*1024*300) + filename, err := download(getCurrentVersionTgzURL(), 1024*1024*300) if err != nil { if filename != "" { os.Remove(filename) } upgradeError = fmt.Errorf("error downloading the new Mattermost server binary file (percentage: %d)", upgradePercentage) - mlog.Error("Unable to download the Mattermost server binary file", mlog.Int64("percentage", upgradePercentage), mlog.String("url", getCurrentVersionTgzUrl()), mlog.Err(err)) + mlog.Error("Unable to download the Mattermost server binary file", mlog.Int64("percentage", upgradePercentage), mlog.String("url", getCurrentVersionTgzURL()), mlog.Err(err)) upgradePercentage = 0 return err } defer os.Remove(filename) - sigfilename, err := download(getCurrentVersionTgzUrl()+".sig", 1024) + sigfilename, err := download(getCurrentVersionTgzURL()+".sig", 1024) if err != nil { if sigfilename != "" { os.Remove(sigfilename) } upgradeError = errors.New("error downloading the signature file of the new server") - mlog.Error("Unable to download the signature file of the new Mattermost server", mlog.String("url", getCurrentVersionTgzUrl()+".sig"), mlog.Err(err)) + mlog.Error("Unable to download the signature file of the new Mattermost server", mlog.String("url", getCurrentVersionTgzURL()+".sig"), mlog.Err(err)) upgradePercentage = 0 return err } diff --git a/services/upgrader/upgrader_linux_test.go b/services/upgrader/upgrader_linux_test.go index 5c9d1b2a49..43583a243a 100644 --- a/services/upgrader/upgrader_linux_test.go +++ b/services/upgrader/upgrader_linux_test.go @@ -35,7 +35,7 @@ func TestCanIUpgradeToE0(t *testing.T) { }) } -func TestGetCurrentVersionTgzUrl(t *testing.T) { +func TestGetCurrentVersionTgzURL(t *testing.T) { t.Run("get release version in regular version", func(t *testing.T) { currentVersion := model.CurrentVersion buildNumber := model.CurrentVersion @@ -45,7 +45,7 @@ func TestGetCurrentVersionTgzUrl(t *testing.T) { model.CurrentVersion = currentVersion model.BuildNumber = buildNumber }() - require.Equal(t, "https://releases.mattermost.com/5.22.0/mattermost-5.22.0-linux-amd64.tar.gz", getCurrentVersionTgzUrl()) + require.Equal(t, "https://releases.mattermost.com/5.22.0/mattermost-5.22.0-linux-amd64.tar.gz", getCurrentVersionTgzURL()) }) t.Run("get release version in dev version", func(t *testing.T) { @@ -57,7 +57,7 @@ func TestGetCurrentVersionTgzUrl(t *testing.T) { model.CurrentVersion = currentVersion model.BuildNumber = buildNumber }() - require.Equal(t, "https://releases.mattermost.com/5.22.0/mattermost-5.22.0-linux-amd64.tar.gz", getCurrentVersionTgzUrl()) + require.Equal(t, "https://releases.mattermost.com/5.22.0/mattermost-5.22.0-linux-amd64.tar.gz", getCurrentVersionTgzURL()) }) t.Run("get release version in rc version", func(t *testing.T) { @@ -69,7 +69,7 @@ func TestGetCurrentVersionTgzUrl(t *testing.T) { model.CurrentVersion = currentVersion model.BuildNumber = buildNumber }() - require.Equal(t, "https://releases.mattermost.com/5.22.0-rc2/mattermost-5.22.0-rc2-linux-amd64.tar.gz", getCurrentVersionTgzUrl()) + require.Equal(t, "https://releases.mattermost.com/5.22.0-rc2/mattermost-5.22.0-rc2-linux-amd64.tar.gz", getCurrentVersionTgzURL()) }) } diff --git a/shared/mfa/mfa.go b/shared/mfa/mfa.go index d3a55ff4d5..1e015c5062 100644 --- a/shared/mfa/mfa.go +++ b/shared/mfa/mfa.go @@ -44,14 +44,14 @@ func newRandomBase32String(size int) string { return base32.StdEncoding.EncodeToString(data) } -func getIssuerFromUrl(uri string) string { +func getIssuerFromURL(uri string) string { issuer := "Mattermost" - siteUrl := strings.TrimSpace(uri) + siteURL := strings.TrimSpace(uri) - if siteUrl != "" { - siteUrl = strings.TrimPrefix(siteUrl, "https://") - siteUrl = strings.TrimPrefix(siteUrl, "http://") - issuer = strings.TrimPrefix(siteUrl, "www.") + if siteURL != "" { + siteURL = strings.TrimPrefix(siteURL, "https://") + siteURL = strings.TrimPrefix(siteURL, "http://") + issuer = strings.TrimPrefix(siteURL, "www.") } return url.QueryEscape(issuer) @@ -59,7 +59,7 @@ func getIssuerFromUrl(uri string) string { // GenerateSecret generates a new user mfa secret and store it with the StoreSecret function provided func (m *MFA) GenerateSecret(siteURL, userEmail, userID string) (string, []byte, error) { - issuer := getIssuerFromUrl(siteURL) + issuer := getIssuerFromURL(siteURL) secret := newRandomBase32String(mfaSecretSize) diff --git a/shared/mfa/mfa_test.go b/shared/mfa/mfa_test.go index 448175259b..bc08e218d4 100644 --- a/shared/mfa/mfa_test.go +++ b/shared/mfa/mfa_test.go @@ -47,7 +47,7 @@ func TestGenerateSecret(t *testing.T) { }) } -func TestGetIssuerFromUrl(t *testing.T) { +func TestGetIssuerFromURL(t *testing.T) { cases := []struct { Input string Expected string @@ -64,7 +64,7 @@ func TestGetIssuerFromUrl(t *testing.T) { } for _, c := range cases { - assert.Equal(t, c.Expected, getIssuerFromUrl(c.Input)) + assert.Equal(t, c.Expected, getIssuerFromURL(c.Input)) } } diff --git a/store/storetest/settings.go b/store/storetest/settings.go index 989476832a..af02b303e6 100644 --- a/store/storetest/settings.go +++ b/store/storetest/settings.go @@ -71,15 +71,15 @@ func MySQLSettings(withReplica bool) *model.SqlSettings { // The database name is generated randomly and must be created before use. func PostgreSQLSettings() *model.SqlSettings { dsn := getEnv("TEST_DATABASE_POSTGRESQL_DSN", defaultPostgresqlDSN) - dsnUrl, err := url.Parse(dsn) + dsnURL, err := url.Parse(dsn) if err != nil { panic("failed to parse dsn " + dsn + ": " + err.Error()) } // Generate a random database name - dsnUrl.Path = "db" + model.NewId() + dsnURL.Path = "db" + model.NewId() - return databaseSettings("postgres", dsnUrl.String()) + return databaseSettings("postgres", dsnURL.String()) } func mySQLRootDSN(dsn string) string { @@ -97,7 +97,7 @@ func mySQLRootDSN(dsn string) string { } func postgreSQLRootDSN(dsn string) string { - dsnUrl, err := url.Parse(dsn) + dsnURL, err := url.Parse(dsn) if err != nil { panic("failed to parse dsn " + dsn + ": " + err.Error()) } @@ -109,9 +109,9 @@ func postgreSQLRootDSN(dsn string) string { // } // dsnUrl.User = url.UserPassword("", password) - dsnUrl.Path = "postgres" + dsnURL.Path = "postgres" - return dsnUrl.String() + return dsnURL.String() } func mySQLDSNDatabase(dsn string) string { @@ -124,12 +124,12 @@ func mySQLDSNDatabase(dsn string) string { } func postgreSQLDSNDatabase(dsn string) string { - dsnUrl, err := url.Parse(dsn) + dsnURL, err := url.Parse(dsn) if err != nil { panic("failed to parse dsn " + dsn + ": " + err.Error()) } - return path.Base(dsnUrl.Path) + return path.Base(dsnURL.Path) } func databaseSettings(driver, dataSource string) *model.SqlSettings { diff --git a/utils/urlencode_test.go b/utils/urlencode_test.go index a87af6fcce..a70c6cd134 100644 --- a/utils/urlencode_test.go +++ b/utils/urlencode_test.go @@ -9,7 +9,7 @@ import ( "github.com/stretchr/testify/require" ) -func TestUrlEncode(t *testing.T) { +func TestURLEncode(t *testing.T) { toEncode := "testing 1 2 3" encoded := URLEncode(toEncode) diff --git a/utils/utils.go b/utils/utils.go index c2e1b7faeb..52cd3d2da0 100644 --- a/utils/utils.go +++ b/utils/utils.go @@ -176,7 +176,7 @@ func GetURLWithCache(url string, cache *RequestCache, skip bool) ([]byte, error) return cache.Data, err } -// Append tokens to passed baseUrl as query params +// Append tokens to passed baseURL as query params func AppendQueryParamsToURL(baseURL string, params map[string]string) string { u, err := url.Parse(baseURL) if err != nil { diff --git a/web/context.go b/web/context.go index 83303531d1..3cca15b0e2 100644 --- a/web/context.go +++ b/web/context.go @@ -209,8 +209,8 @@ func (c *Context) SetInvalidParam(parameter string) { c.Err = NewInvalidParamError(parameter) } -func (c *Context) SetInvalidUrlParam(parameter string) { - c.Err = NewInvalidUrlParamError(parameter) +func (c *Context) SetInvalidURLParam(parameter string) { + c.Err = NewInvalidURLParamError(parameter) } func (c *Context) SetServerBusyError() { @@ -257,7 +257,7 @@ func NewInvalidParamError(parameter string) *model.AppError { err := model.NewAppError("Context", "api.context.invalid_body_param.app_error", map[string]interface{}{"Name": parameter}, "", http.StatusBadRequest) return err } -func NewInvalidUrlParamError(parameter string) *model.AppError { +func NewInvalidURLParamError(parameter string) *model.AppError { err := model.NewAppError("Context", "api.context.invalid_url_param.app_error", map[string]interface{}{"Name": parameter}, "", http.StatusBadRequest) return err } @@ -303,7 +303,7 @@ func (c *Context) RequireUserId() *Context { } if !model.IsValidId(c.Params.UserId) { - c.SetInvalidUrlParam("user_id") + c.SetInvalidURLParam("user_id") } return c } @@ -314,7 +314,7 @@ func (c *Context) RequireTeamId() *Context { } if !model.IsValidId(c.Params.TeamId) { - c.SetInvalidUrlParam("team_id") + c.SetInvalidURLParam("team_id") } return c } @@ -325,7 +325,7 @@ func (c *Context) RequireCategoryId() *Context { } if !model.IsValidCategoryId(c.Params.CategoryId) { - c.SetInvalidUrlParam("category_id") + c.SetInvalidURLParam("category_id") } return c } @@ -336,7 +336,7 @@ func (c *Context) RequireInviteId() *Context { } if c.Params.InviteId == "" { - c.SetInvalidUrlParam("invite_id") + c.SetInvalidURLParam("invite_id") } return c } @@ -347,7 +347,7 @@ func (c *Context) RequireTokenId() *Context { } if !model.IsValidId(c.Params.TokenId) { - c.SetInvalidUrlParam("token_id") + c.SetInvalidURLParam("token_id") } return c } @@ -358,7 +358,7 @@ func (c *Context) RequireThreadId() *Context { } if !model.IsValidId(c.Params.ThreadId) { - c.SetInvalidUrlParam("thread_id") + c.SetInvalidURLParam("thread_id") } return c } @@ -369,7 +369,7 @@ func (c *Context) RequireTimestamp() *Context { } if c.Params.Timestamp == 0 { - c.SetInvalidUrlParam("timestamp") + c.SetInvalidURLParam("timestamp") } return c } @@ -380,7 +380,7 @@ func (c *Context) RequireChannelId() *Context { } if !model.IsValidId(c.Params.ChannelId) { - c.SetInvalidUrlParam("channel_id") + c.SetInvalidURLParam("channel_id") } return c } @@ -403,7 +403,7 @@ func (c *Context) RequirePostId() *Context { } if !model.IsValidId(c.Params.PostId) { - c.SetInvalidUrlParam("post_id") + c.SetInvalidURLParam("post_id") } return c } @@ -414,7 +414,7 @@ func (c *Context) RequirePolicyId() *Context { } if !model.IsValidId(c.Params.PolicyId) { - c.SetInvalidUrlParam("policy_id") + c.SetInvalidURLParam("policy_id") } return c } @@ -425,7 +425,7 @@ func (c *Context) RequireAppId() *Context { } if !model.IsValidId(c.Params.AppId) { - c.SetInvalidUrlParam("app_id") + c.SetInvalidURLParam("app_id") } return c } @@ -436,7 +436,7 @@ func (c *Context) RequireFileId() *Context { } if !model.IsValidId(c.Params.FileId) { - c.SetInvalidUrlParam("file_id") + c.SetInvalidURLParam("file_id") } return c @@ -448,7 +448,7 @@ func (c *Context) RequireUploadId() *Context { } if !model.IsValidId(c.Params.UploadId) { - c.SetInvalidUrlParam("upload_id") + c.SetInvalidURLParam("upload_id") } return c @@ -460,7 +460,7 @@ func (c *Context) RequireFilename() *Context { } if c.Params.Filename == "" { - c.SetInvalidUrlParam("filename") + c.SetInvalidURLParam("filename") } return c @@ -472,7 +472,7 @@ func (c *Context) RequirePluginId() *Context { } if c.Params.PluginId == "" { - c.SetInvalidUrlParam("plugin_id") + c.SetInvalidURLParam("plugin_id") } return c @@ -484,7 +484,7 @@ func (c *Context) RequireReportId() *Context { } if !model.IsValidId(c.Params.ReportId) { - c.SetInvalidUrlParam("report_id") + c.SetInvalidURLParam("report_id") } return c } @@ -495,7 +495,7 @@ func (c *Context) RequireEmojiId() *Context { } if !model.IsValidId(c.Params.EmojiId) { - c.SetInvalidUrlParam("emoji_id") + c.SetInvalidURLParam("emoji_id") } return c } @@ -506,7 +506,7 @@ func (c *Context) RequireTeamName() *Context { } if !model.IsValidTeamName(c.Params.TeamName) { - c.SetInvalidUrlParam("team_name") + c.SetInvalidURLParam("team_name") } return c @@ -518,7 +518,7 @@ func (c *Context) RequireChannelName() *Context { } if !model.IsValidChannelIdentifier(c.Params.ChannelName) { - c.SetInvalidUrlParam("channel_name") + c.SetInvalidURLParam("channel_name") } return c @@ -530,7 +530,7 @@ func (c *Context) SanitizeEmail() *Context { } c.Params.Email = strings.ToLower(c.Params.Email) if !model.IsValidEmail(c.Params.Email) { - c.SetInvalidUrlParam("email") + c.SetInvalidURLParam("email") } return c @@ -542,7 +542,7 @@ func (c *Context) RequireCategory() *Context { } if !model.IsValidAlphaNumHyphenUnderscore(c.Params.Category, true) { - c.SetInvalidUrlParam("category") + c.SetInvalidURLParam("category") } return c @@ -554,7 +554,7 @@ func (c *Context) RequireService() *Context { } if c.Params.Service == "" { - c.SetInvalidUrlParam("service") + c.SetInvalidURLParam("service") } return c @@ -566,7 +566,7 @@ func (c *Context) RequirePreferenceName() *Context { } if !model.IsValidAlphaNumHyphenUnderscore(c.Params.PreferenceName, true) { - c.SetInvalidUrlParam("preference_name") + c.SetInvalidURLParam("preference_name") } return c @@ -580,7 +580,7 @@ func (c *Context) RequireEmojiName() *Context { validName := regexp.MustCompile(`^[a-zA-Z0-9\-\+_]+$`) if c.Params.EmojiName == "" || len(c.Params.EmojiName) > model.EmojiNameMaxLength || !validName.MatchString(c.Params.EmojiName) { - c.SetInvalidUrlParam("emoji_name") + c.SetInvalidURLParam("emoji_name") } return c @@ -592,7 +592,7 @@ func (c *Context) RequireHookId() *Context { } if !model.IsValidId(c.Params.HookId) { - c.SetInvalidUrlParam("hook_id") + c.SetInvalidURLParam("hook_id") } return c @@ -604,7 +604,7 @@ func (c *Context) RequireCommandId() *Context { } if !model.IsValidId(c.Params.CommandId) { - c.SetInvalidUrlParam("command_id") + c.SetInvalidURLParam("command_id") } return c } @@ -615,7 +615,7 @@ func (c *Context) RequireJobId() *Context { } if !model.IsValidId(c.Params.JobId) { - c.SetInvalidUrlParam("job_id") + c.SetInvalidURLParam("job_id") } return c } @@ -626,7 +626,7 @@ func (c *Context) RequireJobType() *Context { } if c.Params.JobType == "" || len(c.Params.JobType) > 32 { - c.SetInvalidUrlParam("job_type") + c.SetInvalidURLParam("job_type") } return c } @@ -637,7 +637,7 @@ func (c *Context) RequireRoleId() *Context { } if !model.IsValidId(c.Params.RoleId) { - c.SetInvalidUrlParam("role_id") + c.SetInvalidURLParam("role_id") } return c } @@ -648,7 +648,7 @@ func (c *Context) RequireSchemeId() *Context { } if !model.IsValidId(c.Params.SchemeId) { - c.SetInvalidUrlParam("scheme_id") + c.SetInvalidURLParam("scheme_id") } return c } @@ -659,7 +659,7 @@ func (c *Context) RequireRoleName() *Context { } if !model.IsValidRoleName(c.Params.RoleName) { - c.SetInvalidUrlParam("role_name") + c.SetInvalidURLParam("role_name") } return c @@ -671,7 +671,7 @@ func (c *Context) RequireGroupId() *Context { } if !model.IsValidId(c.Params.GroupId) { - c.SetInvalidUrlParam("group_id") + c.SetInvalidURLParam("group_id") } return c } @@ -682,7 +682,7 @@ func (c *Context) RequireRemoteId() *Context { } if c.Params.RemoteId == "" { - c.SetInvalidUrlParam("remote_id") + c.SetInvalidURLParam("remote_id") } return c } @@ -693,7 +693,7 @@ func (c *Context) RequireSyncableId() *Context { } if !model.IsValidId(c.Params.SyncableId) { - c.SetInvalidUrlParam("syncable_id") + c.SetInvalidURLParam("syncable_id") } return c } @@ -704,7 +704,7 @@ func (c *Context) RequireSyncableType() *Context { } if c.Params.SyncableType != model.GroupSyncableTypeTeam && c.Params.SyncableType != model.GroupSyncableTypeChannel { - c.SetInvalidUrlParam("syncable_type") + c.SetInvalidURLParam("syncable_type") } return c } @@ -715,7 +715,7 @@ func (c *Context) RequireBotUserId() *Context { } if !model.IsValidId(c.Params.BotUserId) { - c.SetInvalidUrlParam("bot_user_id") + c.SetInvalidURLParam("bot_user_id") } return c } @@ -726,7 +726,7 @@ func (c *Context) RequireInvoiceId() *Context { } if len(c.Params.InvoiceId) != 27 { - c.SetInvalidUrlParam("invoice_id") + c.SetInvalidURLParam("invoice_id") } return c diff --git a/web/handlers.go b/web/handlers.go index ca2a61a119..27aa9cf906 100644 --- a/web/handlers.go +++ b/web/handlers.go @@ -320,7 +320,7 @@ func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { c.Err.IsOAuth = false } - if IsApiCall(c.App, r) || IsWebhookCall(c.App, r) || IsOAuthApiCall(c.App, r) || r.Header.Get("X-Mobile-App") != "" { + if IsAPICall(c.App, r) || IsWebhookCall(c.App, r) || IsOAuthAPICall(c.App, r) || r.Header.Get("X-Mobile-App") != "" { w.WriteHeader(c.Err.StatusCode) w.Write([]byte(c.Err.ToJson())) } else { @@ -336,9 +336,9 @@ func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { if c.App.Metrics() != nil { c.App.Metrics().IncrementHTTPRequest() - if r.URL.Path != model.ApiUrlSuffix+"/websocket" { + if r.URL.Path != model.APIURLSuffix+"/websocket" { elapsed := float64(time.Since(now)) / float64(time.Second) - c.App.Metrics().ObserveApiEndpointDuration(h.HandlerName, r.Method, statusCode, elapsed) + c.App.Metrics().ObserveAPIEndpointDuration(h.HandlerName, r.Method, statusCode, elapsed) } } } @@ -390,9 +390,9 @@ func (h *Handler) checkCSRFToken(c *Context, r *http.Request, token string, toke return csrfCheckNeeded, csrfCheckPassed } -// ApiHandler provides a handler for API endpoints which do not require the user to be logged in order for access to be +// APIHandler provides a handler for API endpoints which do not require the user to be logged in order for access to be // granted. -func (w *Web) ApiHandler(h func(*Context, http.ResponseWriter, *http.Request)) http.Handler { +func (w *Web) APIHandler(h func(*Context, http.ResponseWriter, *http.Request)) http.Handler { handler := &Handler{ App: w.app, HandleFunc: h, @@ -409,10 +409,10 @@ func (w *Web) ApiHandler(h func(*Context, http.ResponseWriter, *http.Request)) h return handler } -// ApiHandlerTrustRequester provides a handler for API endpoints which do not require the user to be logged in and are +// APIHandlerTrustRequester provides a handler for API endpoints which do not require the user to be logged in and are // allowed to be requested directly rather than via javascript/XMLHttpRequest, such as site branding images or the // websocket. -func (w *Web) ApiHandlerTrustRequester(h func(*Context, http.ResponseWriter, *http.Request)) http.Handler { +func (w *Web) APIHandlerTrustRequester(h func(*Context, http.ResponseWriter, *http.Request)) http.Handler { handler := &Handler{ App: w.app, HandleFunc: h, @@ -429,9 +429,9 @@ func (w *Web) ApiHandlerTrustRequester(h func(*Context, http.ResponseWriter, *ht return handler } -// ApiSessionRequired provides a handler for API endpoints which require the user to be logged in in order for access to +// APISessionRequired provides a handler for API endpoints which require the user to be logged in in order for access to // be granted. -func (w *Web) ApiSessionRequired(h func(*Context, http.ResponseWriter, *http.Request)) http.Handler { +func (w *Web) APISessionRequired(h func(*Context, http.ResponseWriter, *http.Request)) http.Handler { handler := &Handler{ App: w.app, HandleFunc: h, diff --git a/web/oauth.go b/web/oauth.go index 1fabb05659..c369b3746f 100644 --- a/web/oauth.go +++ b/web/oauth.go @@ -22,22 +22,22 @@ import ( func (w *Web) InitOAuth() { // API version independent OAuth 2.0 as a service provider endpoints - w.MainRouter.Handle("/oauth/authorize", w.ApiHandlerTrustRequester(authorizeOAuthPage)).Methods("GET") - w.MainRouter.Handle("/oauth/authorize", w.ApiSessionRequired(authorizeOAuthApp)).Methods("POST") - w.MainRouter.Handle("/oauth/deauthorize", w.ApiSessionRequired(deauthorizeOAuthApp)).Methods("POST") - w.MainRouter.Handle("/oauth/access_token", w.ApiHandlerTrustRequester(getAccessToken)).Methods("POST") + w.MainRouter.Handle("/oauth/authorize", w.APIHandlerTrustRequester(authorizeOAuthPage)).Methods("GET") + w.MainRouter.Handle("/oauth/authorize", w.APISessionRequired(authorizeOAuthApp)).Methods("POST") + w.MainRouter.Handle("/oauth/deauthorize", w.APISessionRequired(deauthorizeOAuthApp)).Methods("POST") + w.MainRouter.Handle("/oauth/access_token", w.APIHandlerTrustRequester(getAccessToken)).Methods("POST") // API version independent OAuth as a client endpoints - w.MainRouter.Handle("/oauth/{service:[A-Za-z0-9]+}/complete", w.ApiHandler(completeOAuth)).Methods("GET") - w.MainRouter.Handle("/oauth/{service:[A-Za-z0-9]+}/login", w.ApiHandler(loginWithOAuth)).Methods("GET") - w.MainRouter.Handle("/oauth/{service:[A-Za-z0-9]+}/mobile_login", w.ApiHandler(mobileLoginWithOAuth)).Methods("GET") - w.MainRouter.Handle("/oauth/{service:[A-Za-z0-9]+}/signup", w.ApiHandler(signupWithOAuth)).Methods("GET") + w.MainRouter.Handle("/oauth/{service:[A-Za-z0-9]+}/complete", w.APIHandler(completeOAuth)).Methods("GET") + w.MainRouter.Handle("/oauth/{service:[A-Za-z0-9]+}/login", w.APIHandler(loginWithOAuth)).Methods("GET") + w.MainRouter.Handle("/oauth/{service:[A-Za-z0-9]+}/mobile_login", w.APIHandler(mobileLoginWithOAuth)).Methods("GET") + w.MainRouter.Handle("/oauth/{service:[A-Za-z0-9]+}/signup", w.APIHandler(signupWithOAuth)).Methods("GET") // Old endpoints for backwards compatibility, needed to not break SSO for any old setups - w.MainRouter.Handle("/api/v3/oauth/{service:[A-Za-z0-9]+}/complete", w.ApiHandler(completeOAuth)).Methods("GET") - w.MainRouter.Handle("/signup/{service:[A-Za-z0-9]+}/complete", w.ApiHandler(completeOAuth)).Methods("GET") - w.MainRouter.Handle("/login/{service:[A-Za-z0-9]+}/complete", w.ApiHandler(completeOAuth)).Methods("GET") - w.MainRouter.Handle("/api/v4/oauth_test", w.ApiSessionRequired(testHandler)).Methods("GET") + w.MainRouter.Handle("/api/v3/oauth/{service:[A-Za-z0-9]+}/complete", w.APIHandler(completeOAuth)).Methods("GET") + w.MainRouter.Handle("/signup/{service:[A-Za-z0-9]+}/complete", w.APIHandler(completeOAuth)).Methods("GET") + w.MainRouter.Handle("/login/{service:[A-Za-z0-9]+}/complete", w.APIHandler(completeOAuth)).Methods("GET") + w.MainRouter.Handle("/api/v4/oauth_test", w.APISessionRequired(testHandler)).Methods("GET") } func testHandler(c *Context, w http.ResponseWriter, r *http.Request) { @@ -67,7 +67,7 @@ func authorizeOAuthApp(c *Context, w http.ResponseWriter, r *http.Request) { defer c.LogAuditRec(auditRec) c.LogAudit("attempt") - redirectUrl, appErr := c.App.AllowOAuthAppAccessToUser(c.AppContext.Session().UserId, authRequest) + redirectURL, appErr := c.App.AllowOAuthAppAccessToUser(c.AppContext.Session().UserId, authRequest) if appErr != nil { c.Err = appErr return @@ -76,7 +76,7 @@ func authorizeOAuthApp(c *Context, w http.ResponseWriter, r *http.Request) { auditRec.Success() c.LogAudit("") - w.Write([]byte(model.MapToJson(map[string]string{"redirect": redirectUrl}))) + w.Write([]byte(model.MapToJson(map[string]string{"redirect": redirectURL}))) } func deauthorizeOAuthApp(c *Context, w http.ResponseWriter, r *http.Request) { @@ -113,7 +113,7 @@ func authorizeOAuthPage(c *Context, w http.ResponseWriter, r *http.Request) { authRequest := &model.AuthorizeRequest{ ResponseType: r.URL.Query().Get("response_type"), ClientId: r.URL.Query().Get("client_id"), - RedirectUri: r.URL.Query().Get("redirect_uri"), + RedirectURI: r.URL.Query().Get("redirect_uri"), Scope: r.URL.Query().Get("scope"), State: r.URL.Query().Get("state"), } @@ -145,7 +145,7 @@ func authorizeOAuthPage(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !oauthApp.IsValidRedirectURL(authRequest.RedirectUri) { + if !oauthApp.IsValidRedirectURL(authRequest.RedirectURI) { err := model.NewAppError("authorizeOAuthPage", "api.oauth.allow_oauth.redirect_callback.app_error", nil, "", http.StatusBadRequest) utils.RenderWebError(c.App.Config(), w, r, err.StatusCode, url.Values{ @@ -164,14 +164,14 @@ func authorizeOAuthPage(c *Context, w http.ResponseWriter, r *http.Request) { // Automatically allow if the app is trusted if oauthApp.IsTrusted || isAuthorized { - redirectUrl, err := c.App.AllowOAuthAppAccessToUser(c.AppContext.Session().UserId, authRequest) + redirectURL, err := c.App.AllowOAuthAppAccessToUser(c.AppContext.Session().UserId, authRequest) if err != nil { utils.RenderWebAppError(c.App.Config(), w, r, err, c.App.AsymmetricSigningKey()) return } - http.Redirect(w, r, redirectUrl, http.StatusFound) + http.Redirect(w, r, redirectURL, http.StatusFound) return } @@ -219,7 +219,7 @@ func getAccessToken(c *Context, w http.ResponseWriter, r *http.Request) { return } - redirectUri := r.FormValue("redirect_uri") + redirectURI := r.FormValue("redirect_uri") auditRec := c.MakeAuditRecord("getAccessToken", audit.Fail) defer c.LogAuditRec(auditRec) @@ -227,7 +227,7 @@ func getAccessToken(c *Context, w http.ResponseWriter, r *http.Request) { auditRec.AddMeta("client_id", clientId) c.LogAudit("attempt") - accessRsp, err := c.App.GetOAuthAccessTokenForCodeFlow(clientId, grantType, redirectUri, code, secret, refreshToken) + accessRsp, err := c.App.GetOAuthAccessTokenForCodeFlow(clientId, grantType, redirectURI, code, secret, refreshToken) if err != nil { c.Err = err return @@ -373,13 +373,13 @@ func loginWithOAuth(c *Context, w http.ResponseWriter, r *http.Request) { return } - authUrl, err := c.App.GetOAuthLoginEndpoint(w, r, c.Params.Service, teamId, model.OAuthActionLogin, redirectURL, loginHint, false) + authURL, err := c.App.GetOAuthLoginEndpoint(w, r, c.Params.Service, teamId, model.OAuthActionLogin, redirectURL, loginHint, false) if err != nil { c.Err = err return } - http.Redirect(w, r, authUrl, http.StatusFound) + http.Redirect(w, r, authURL, http.StatusFound) } func mobileLoginWithOAuth(c *Context, w http.ResponseWriter, r *http.Request) { @@ -402,13 +402,13 @@ func mobileLoginWithOAuth(c *Context, w http.ResponseWriter, r *http.Request) { return } - authUrl, err := c.App.GetOAuthLoginEndpoint(w, r, c.Params.Service, teamId, model.OAuthActionMobile, redirectURL, "", true) + authURL, err := c.App.GetOAuthLoginEndpoint(w, r, c.Params.Service, teamId, model.OAuthActionMobile, redirectURL, "", true) if err != nil { c.Err = err return } - http.Redirect(w, r, authUrl, http.StatusFound) + http.Redirect(w, r, authURL, http.StatusFound) } func signupWithOAuth(c *Context, w http.ResponseWriter, r *http.Request) { @@ -430,11 +430,11 @@ func signupWithOAuth(c *Context, w http.ResponseWriter, r *http.Request) { return } - authUrl, err := c.App.GetOAuthSignupEndpoint(w, r, c.Params.Service, teamId) + authURL, err := c.App.GetOAuthSignupEndpoint(w, r, c.Params.Service, teamId) if err != nil { c.Err = err return } - http.Redirect(w, r, authUrl, http.StatusFound) + http.Redirect(w, r, authURL, http.StatusFound) } diff --git a/web/oauth_test.go b/web/oauth_test.go index de2309db0f..9627b228e9 100644 --- a/web/oauth_test.go +++ b/web/oauth_test.go @@ -52,7 +52,7 @@ func TestOAuthComplete_AccessDenied(t *testing.T) { func TestAuthorizeOAuthApp(t *testing.T) { th := Setup(t).InitBasic() - th.Login(ApiClient, th.SystemAdminUser) + th.Login(apiClient, th.SystemAdminUser) defer th.TearDown() enableOAuth := *th.App.Config().ServiceSettings.EnableOAuthServiceProvider @@ -76,13 +76,13 @@ func TestAuthorizeOAuthApp(t *testing.T) { authRequest := &model.AuthorizeRequest{ ResponseType: model.AuthCodeResponseType, ClientId: rapp.Id, - RedirectUri: rapp.CallbackUrls[0], + RedirectURI: rapp.CallbackUrls[0], Scope: "", State: "123", } // Test auth code flow - ruri, _, err := ApiClient.AuthorizeOAuthApp(authRequest) + ruri, _, err := apiClient.AuthorizeOAuthApp(authRequest) require.NoError(t, err) require.NotEmpty(t, ruri, "redirect url should be set") @@ -94,7 +94,7 @@ func TestAuthorizeOAuthApp(t *testing.T) { // Test implicit flow authRequest.ResponseType = model.ImplicitResponseType - ruri, _, err = ApiClient.AuthorizeOAuthApp(authRequest) + ruri, _, err = apiClient.AuthorizeOAuthApp(authRequest) require.NoError(t, err) require.False(t, ruri == "", "redirect url should be set") @@ -105,45 +105,45 @@ func TestAuthorizeOAuthApp(t *testing.T) { assert.False(t, values.Get("access_token") == "", "access_token not returned") assert.Equal(t, authRequest.State, values.Get("state"), "returned state doesn't match") - oldToken := ApiClient.AuthToken - ApiClient.AuthToken = values.Get("access_token") - _, resp, err := ApiClient.AuthorizeOAuthApp(authRequest) + oldToken := apiClient.AuthToken + apiClient.AuthToken = values.Get("access_token") + _, resp, err := apiClient.AuthorizeOAuthApp(authRequest) require.Error(t, err) CheckForbiddenStatus(t, resp) - ApiClient.AuthToken = oldToken + apiClient.AuthToken = oldToken - authRequest.RedirectUri = "" - _, resp, err = ApiClient.AuthorizeOAuthApp(authRequest) + authRequest.RedirectURI = "" + _, resp, err = apiClient.AuthorizeOAuthApp(authRequest) require.Error(t, err) CheckBadRequestStatus(t, resp) - authRequest.RedirectUri = "http://somewhereelse.com" - _, resp, err = ApiClient.AuthorizeOAuthApp(authRequest) + authRequest.RedirectURI = "http://somewhereelse.com" + _, resp, err = apiClient.AuthorizeOAuthApp(authRequest) require.Error(t, err) CheckBadRequestStatus(t, resp) - authRequest.RedirectUri = rapp.CallbackUrls[0] + authRequest.RedirectURI = rapp.CallbackUrls[0] authRequest.ResponseType = "" - _, resp, err = ApiClient.AuthorizeOAuthApp(authRequest) + _, resp, err = apiClient.AuthorizeOAuthApp(authRequest) require.Error(t, err) CheckBadRequestStatus(t, resp) authRequest.ResponseType = model.AuthCodeResponseType authRequest.ClientId = "" - _, resp, err = ApiClient.AuthorizeOAuthApp(authRequest) + _, resp, err = apiClient.AuthorizeOAuthApp(authRequest) require.Error(t, err) CheckBadRequestStatus(t, resp) authRequest.ClientId = model.NewId() - _, resp, err = ApiClient.AuthorizeOAuthApp(authRequest) + _, resp, err = apiClient.AuthorizeOAuthApp(authRequest) require.Error(t, err) CheckNotFoundStatus(t, resp) } func TestDeauthorizeOAuthApp(t *testing.T) { th := Setup(t).InitBasic() - th.Login(ApiClient, th.SystemAdminUser) + th.Login(apiClient, th.SystemAdminUser) defer th.TearDown() enableOAuth := th.App.Config().ServiceSettings.EnableOAuthServiceProvider @@ -166,26 +166,26 @@ func TestDeauthorizeOAuthApp(t *testing.T) { authRequest := &model.AuthorizeRequest{ ResponseType: model.AuthCodeResponseType, ClientId: rapp.Id, - RedirectUri: rapp.CallbackUrls[0], + RedirectURI: rapp.CallbackUrls[0], Scope: "", State: "123", } - _, _, err := ApiClient.AuthorizeOAuthApp(authRequest) + _, _, err := apiClient.AuthorizeOAuthApp(authRequest) require.NoError(t, err) - _, err = ApiClient.DeauthorizeOAuthApp(rapp.Id) + _, err = apiClient.DeauthorizeOAuthApp(rapp.Id) require.NoError(t, err) - resp, err := ApiClient.DeauthorizeOAuthApp("junk") + resp, err := apiClient.DeauthorizeOAuthApp("junk") require.Error(t, err) CheckBadRequestStatus(t, resp) - _, err = ApiClient.DeauthorizeOAuthApp(model.NewId()) + _, err = apiClient.DeauthorizeOAuthApp(model.NewId()) require.NoError(t, err) - th.Logout(ApiClient) - resp, err = ApiClient.DeauthorizeOAuthApp(rapp.Id) + th.Logout(apiClient) + resp, err = apiClient.DeauthorizeOAuthApp(rapp.Id) require.Error(t, err) CheckUnauthorizedStatus(t, resp) } @@ -196,7 +196,7 @@ func TestOAuthAccessToken(t *testing.T) { } th := Setup(t).InitBasic() - th.Login(ApiClient, th.SystemAdminUser) + th.Login(apiClient, th.SystemAdminUser) defer th.TearDown() enableOAuth := th.App.Config().ServiceSettings.EnableOAuthServiceProvider @@ -225,59 +225,59 @@ func TestOAuthAccessToken(t *testing.T) { th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableOAuthServiceProvider = false }) data := url.Values{"grant_type": []string{"junk"}, "client_id": []string{"12345678901234567890123456"}, "client_secret": []string{"12345678901234567890123456"}, "code": []string{"junk"}, "redirect_uri": []string{oauthApp.CallbackUrls[0]}} - _, _, err := ApiClient.GetOAuthAccessToken(data) + _, _, err := apiClient.GetOAuthAccessToken(data) require.Error(t, err, "should have failed - oauth providing turned off") th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableOAuthServiceProvider = true }) authRequest := &model.AuthorizeRequest{ ResponseType: model.AuthCodeResponseType, ClientId: oauthApp.Id, - RedirectUri: oauthApp.CallbackUrls[0], + RedirectURI: oauthApp.CallbackUrls[0], Scope: "all", State: "123", } - redirect, _, err := ApiClient.AuthorizeOAuthApp(authRequest) + redirect, _, err := apiClient.AuthorizeOAuthApp(authRequest) require.NoError(t, err) rurl, _ := url.Parse(redirect) - ApiClient.Logout() + apiClient.Logout() data = url.Values{"grant_type": []string{"junk"}, "client_id": []string{oauthApp.Id}, "client_secret": []string{oauthApp.ClientSecret}, "code": []string{rurl.Query().Get("code")}, "redirect_uri": []string{oauthApp.CallbackUrls[0]}} - _, _, err = ApiClient.GetOAuthAccessToken(data) + _, _, err = apiClient.GetOAuthAccessToken(data) require.Error(t, err, "should have failed - bad grant type") data.Set("grant_type", model.AccessTokenGrantType) data.Set("client_id", "") - _, _, err = ApiClient.GetOAuthAccessToken(data) + _, _, err = apiClient.GetOAuthAccessToken(data) require.Error(t, err, "should have failed - missing client id") data.Set("client_id", "junk") - _, _, err = ApiClient.GetOAuthAccessToken(data) + _, _, err = apiClient.GetOAuthAccessToken(data) require.Error(t, err, "should have failed - bad client id") data.Set("client_id", oauthApp.Id) data.Set("client_secret", "") - _, _, err = ApiClient.GetOAuthAccessToken(data) + _, _, err = apiClient.GetOAuthAccessToken(data) require.Error(t, err, "should have failed - missing client secret") data.Set("client_secret", "junk") - _, _, err = ApiClient.GetOAuthAccessToken(data) + _, _, err = apiClient.GetOAuthAccessToken(data) require.Error(t, err, "should have failed - bad client secret") data.Set("client_secret", oauthApp.ClientSecret) data.Set("code", "") - _, _, err = ApiClient.GetOAuthAccessToken(data) + _, _, err = apiClient.GetOAuthAccessToken(data) require.Error(t, err, "should have failed - missing code") data.Set("code", "junk") - _, _, err = ApiClient.GetOAuthAccessToken(data) + _, _, err = apiClient.GetOAuthAccessToken(data) require.Error(t, err, "should have failed - bad code") data.Set("code", rurl.Query().Get("code")) data.Set("redirect_uri", "junk") - _, _, err = ApiClient.GetOAuthAccessToken(data) + _, _, err = apiClient.GetOAuthAccessToken(data) require.Error(t, err, "should have failed - non-matching redirect uri") // reset data for successful request @@ -289,29 +289,29 @@ func TestOAuthAccessToken(t *testing.T) { token := "" refreshToken := "" - rsp, _, err := ApiClient.GetOAuthAccessToken(data) + rsp, _, err := apiClient.GetOAuthAccessToken(data) require.NoError(t, err) require.NotEmpty(t, rsp.AccessToken, "access token not returned") require.NotEmpty(t, rsp.RefreshToken, "refresh token not returned") token, refreshToken = rsp.AccessToken, rsp.RefreshToken require.Equal(t, rsp.TokenType, model.AccessTokenType, "access token type incorrect") - _, err = ApiClient.DoApiGet("/oauth_test", "") + _, err = apiClient.DoAPIGet("/oauth_test", "") require.NoError(t, err) - ApiClient.SetOAuthToken("") - _, err = ApiClient.DoApiGet("/oauth_test", "") + apiClient.SetOAuthToken("") + _, err = apiClient.DoAPIGet("/oauth_test", "") require.Error(t, err, "should have failed - no access token provided") - ApiClient.SetOAuthToken("badtoken") - _, err = ApiClient.DoApiGet("/oauth_test", "") + apiClient.SetOAuthToken("badtoken") + _, err = apiClient.DoAPIGet("/oauth_test", "") require.Error(t, err, "should have failed - bad token provided") - ApiClient.SetOAuthToken(token) - _, err = ApiClient.DoApiGet("/oauth_test", "") + apiClient.SetOAuthToken(token) + _, err = apiClient.DoAPIGet("/oauth_test", "") require.NoError(t, err) - _, _, err = ApiClient.GetOAuthAccessToken(data) + _, _, err = apiClient.GetOAuthAccessToken(data) require.Error(t, err, "should have failed - tried to reuse auth code") data.Set("grant_type", model.RefreshTokenGrantType) @@ -320,31 +320,31 @@ func TestOAuthAccessToken(t *testing.T) { data.Set("refresh_token", "") data.Set("redirect_uri", oauthApp.CallbackUrls[0]) data.Del("code") - _, _, err = ApiClient.GetOAuthAccessToken(data) + _, _, err = apiClient.GetOAuthAccessToken(data) require.Error(t, err, "Should have failed - refresh token empty") data.Set("refresh_token", refreshToken) - rsp, _, err = ApiClient.GetOAuthAccessToken(data) + rsp, _, err = apiClient.GetOAuthAccessToken(data) require.NoError(t, err) require.NotEmpty(t, rsp.AccessToken, "access token not returned") require.NotEmpty(t, rsp.RefreshToken, "refresh token not returned") require.NotEqual(t, rsp.RefreshToken, refreshToken, "refresh token did not update") require.Equal(t, rsp.TokenType, model.AccessTokenType, "access token type incorrect") - ApiClient.SetOAuthToken(rsp.AccessToken) - _, err = ApiClient.DoApiGet("/oauth_test", "") + apiClient.SetOAuthToken(rsp.AccessToken) + _, err = apiClient.DoAPIGet("/oauth_test", "") require.NoError(t, err) data.Set("refresh_token", rsp.RefreshToken) - rsp, _, err = ApiClient.GetOAuthAccessToken(data) + rsp, _, err = apiClient.GetOAuthAccessToken(data) require.NoError(t, err) require.NotEmpty(t, rsp.AccessToken, "access token not returned") require.NotEmpty(t, rsp.RefreshToken, "refresh token not returned") require.NotEqual(t, rsp.RefreshToken, refreshToken, "refresh token did not update") require.Equal(t, rsp.TokenType, model.AccessTokenType, "access token type incorrect") - ApiClient.SetOAuthToken(rsp.AccessToken) - _, err = ApiClient.DoApiGet("/oauth_test", "") + apiClient.SetOAuthToken(rsp.AccessToken) + _, err = apiClient.DoAPIGet("/oauth_test", "") require.NoError(t, err) authData := &model.AuthData{ClientId: oauthApp.Id, RedirectUri: oauthApp.CallbackUrls[0], UserId: th.BasicUser.Id, Code: model.NewId(), ExpiresIn: -1} @@ -357,10 +357,10 @@ func TestOAuthAccessToken(t *testing.T) { data.Set("redirect_uri", oauthApp.CallbackUrls[0]) data.Set("code", authData.Code) data.Del("refresh_token") - _, _, err = ApiClient.GetOAuthAccessToken(data) + _, _, err = apiClient.GetOAuthAccessToken(data) require.Error(t, err, "Should have failed - code is expired") - ApiClient.ClearOAuthToken() + apiClient.ClearOAuthToken() } func TestMobileLoginWithOAuth(t *testing.T) { @@ -415,7 +415,7 @@ func TestOAuthComplete(t *testing.T) { } th := Setup(t).InitBasic() - th.Login(ApiClient, th.SystemAdminUser) + th.Login(apiClient, th.SystemAdminUser) defer th.TearDown() gitLabSettingsEnable := th.App.Config().GitLabSettings.Enable @@ -423,7 +423,7 @@ func TestOAuthComplete(t *testing.T) { gitLabSettingsId := th.App.Config().GitLabSettings.Id gitLabSettingsSecret := th.App.Config().GitLabSettings.Secret gitLabSettingsTokenEndpoint := th.App.Config().GitLabSettings.TokenEndpoint - gitLabSettingsUserApiEndpoint := th.App.Config().GitLabSettings.UserApiEndpoint + gitLabSettingsUserAPIEndpoint := th.App.Config().GitLabSettings.UserAPIEndpoint enableOAuthServiceProvider := th.App.Config().ServiceSettings.EnableOAuthServiceProvider defer func() { th.App.UpdateConfig(func(cfg *model.Config) { cfg.GitLabSettings.Enable = gitLabSettingsEnable }) @@ -431,20 +431,20 @@ func TestOAuthComplete(t *testing.T) { th.App.UpdateConfig(func(cfg *model.Config) { cfg.GitLabSettings.Id = gitLabSettingsId }) th.App.UpdateConfig(func(cfg *model.Config) { cfg.GitLabSettings.Secret = gitLabSettingsSecret }) th.App.UpdateConfig(func(cfg *model.Config) { cfg.GitLabSettings.TokenEndpoint = gitLabSettingsTokenEndpoint }) - th.App.UpdateConfig(func(cfg *model.Config) { cfg.GitLabSettings.UserApiEndpoint = gitLabSettingsUserApiEndpoint }) + th.App.UpdateConfig(func(cfg *model.Config) { cfg.GitLabSettings.UserAPIEndpoint = gitLabSettingsUserAPIEndpoint }) th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOAuthServiceProvider = enableOAuthServiceProvider }) }() - r, err := HTTPGet(ApiClient.Url+"/login/gitlab/complete?code=123", ApiClient.HTTPClient, "", true) + r, err := HTTPGet(apiClient.URL+"/login/gitlab/complete?code=123", apiClient.HTTPClient, "", true) assert.Error(t, err) closeBody(r) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.GitLabSettings.Enable = true }) - r, err = HTTPGet(ApiClient.Url+"/login/gitlab/complete?code=123&state=!#$#F@#Yˆ&~ñ", ApiClient.HTTPClient, "", true) + r, err = HTTPGet(apiClient.URL+"/login/gitlab/complete?code=123&state=!#$#F@#Yˆ&~ñ", apiClient.HTTPClient, "", true) assert.Error(t, err) closeBody(r) - th.App.UpdateConfig(func(cfg *model.Config) { *cfg.GitLabSettings.AuthEndpoint = ApiClient.Url + "/oauth/authorize" }) + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.GitLabSettings.AuthEndpoint = apiClient.URL + "/oauth/authorize" }) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.GitLabSettings.Id = model.NewId() }) stateProps := map[string]string{} @@ -453,13 +453,13 @@ func TestOAuthComplete(t *testing.T) { stateProps["redirect_to"] = *th.App.Config().GitLabSettings.AuthEndpoint state := base64.StdEncoding.EncodeToString([]byte(model.MapToJson(stateProps))) - r, err = HTTPGet(ApiClient.Url+"/login/gitlab/complete?code=123&state="+url.QueryEscape(state), ApiClient.HTTPClient, "", true) + r, err = HTTPGet(apiClient.URL+"/login/gitlab/complete?code=123&state="+url.QueryEscape(state), apiClient.HTTPClient, "", true) assert.Error(t, err) closeBody(r) stateProps["hash"] = utils.HashSha256(*th.App.Config().GitLabSettings.Id) state = base64.StdEncoding.EncodeToString([]byte(model.MapToJson(stateProps))) - r, err = HTTPGet(ApiClient.Url+"/login/gitlab/complete?code=123&state="+url.QueryEscape(state), ApiClient.HTTPClient, "", true) + r, err = HTTPGet(apiClient.URL+"/login/gitlab/complete?code=123&state="+url.QueryEscape(state), apiClient.HTTPClient, "", true) assert.Error(t, err) closeBody(r) @@ -478,8 +478,8 @@ func TestOAuthComplete(t *testing.T) { Homepage: "https://nowhere.com", Description: "test", CallbackUrls: []string{ - ApiClient.Url + "/signup/" + model.ServiceGitlab + "/complete", - ApiClient.Url + "/login/" + model.ServiceGitlab + "/complete", + apiClient.URL + "/signup/" + model.ServiceGitlab + "/complete", + apiClient.URL + "/login/" + model.ServiceGitlab + "/complete", }, CreatorId: th.SystemAdminUser.Id, IsTrusted: true, @@ -489,21 +489,21 @@ func TestOAuthComplete(t *testing.T) { th.App.UpdateConfig(func(cfg *model.Config) { *cfg.GitLabSettings.Id = oauthApp.Id }) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.GitLabSettings.Secret = oauthApp.ClientSecret }) - th.App.UpdateConfig(func(cfg *model.Config) { *cfg.GitLabSettings.AuthEndpoint = ApiClient.Url + "/oauth/authorize" }) - th.App.UpdateConfig(func(cfg *model.Config) { *cfg.GitLabSettings.TokenEndpoint = ApiClient.Url + "/oauth/access_token" }) - th.App.UpdateConfig(func(cfg *model.Config) { *cfg.GitLabSettings.UserApiEndpoint = ApiClient.ApiUrl + "/users/me" }) + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.GitLabSettings.AuthEndpoint = apiClient.URL + "/oauth/authorize" }) + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.GitLabSettings.TokenEndpoint = apiClient.URL + "/oauth/access_token" }) + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.GitLabSettings.UserAPIEndpoint = apiClient.APIURL + "/users/me" }) provider := &MattermostTestProvider{} authRequest := &model.AuthorizeRequest{ ResponseType: model.AuthCodeResponseType, ClientId: oauthApp.Id, - RedirectUri: oauthApp.CallbackUrls[0], + RedirectURI: oauthApp.CallbackUrls[0], Scope: "all", State: "123", } - redirect, _, err := ApiClient.AuthorizeOAuthApp(authRequest) + redirect, _, err := apiClient.AuthorizeOAuthApp(authRequest) require.NoError(t, err) rurl, _ := url.Parse(redirect) @@ -514,19 +514,19 @@ func TestOAuthComplete(t *testing.T) { stateProps["hash"] = utils.HashSha256(*th.App.Config().GitLabSettings.Id) stateProps["redirect_to"] = "/oauth/authorize" state = base64.StdEncoding.EncodeToString([]byte(model.MapToJson(stateProps))) - r, err = HTTPGet(ApiClient.Url+"/login/"+model.ServiceGitlab+"/complete?code="+url.QueryEscape(code)+"&state="+url.QueryEscape(state), ApiClient.HTTPClient, "", false) + r, err = HTTPGet(apiClient.URL+"/login/"+model.ServiceGitlab+"/complete?code="+url.QueryEscape(code)+"&state="+url.QueryEscape(state), apiClient.HTTPClient, "", false) if err == nil { closeBody(r) } einterfaces.RegisterOAuthProvider(model.ServiceGitlab, provider) - redirect, _, err = ApiClient.AuthorizeOAuthApp(authRequest) + redirect, _, err = apiClient.AuthorizeOAuthApp(authRequest) require.NoError(t, err) rurl, _ = url.Parse(redirect) code = rurl.Query().Get("code") - r, err = HTTPGet(ApiClient.Url+"/login/"+model.ServiceGitlab+"/complete?code="+url.QueryEscape(code)+"&state="+url.QueryEscape(state), ApiClient.HTTPClient, "", false) + r, err = HTTPGet(apiClient.URL+"/login/"+model.ServiceGitlab+"/complete?code="+url.QueryEscape(code)+"&state="+url.QueryEscape(state), apiClient.HTTPClient, "", false) if err == nil { closeBody(r) } @@ -535,36 +535,36 @@ func TestOAuthComplete(t *testing.T) { th.BasicUser.Id, model.ServiceGitlab, &th.BasicUser.Email, th.BasicUser.Email, true) require.NoError(t, nErr) - redirect, _, err = ApiClient.AuthorizeOAuthApp(authRequest) + redirect, _, err = apiClient.AuthorizeOAuthApp(authRequest) require.NoError(t, err) rurl, _ = url.Parse(redirect) code = rurl.Query().Get("code") stateProps["action"] = model.OAuthActionLogin state = base64.StdEncoding.EncodeToString([]byte(model.MapToJson(stateProps))) - if r, err = HTTPGet(ApiClient.Url+"/login/"+model.ServiceGitlab+"/complete?code="+url.QueryEscape(code)+"&state="+url.QueryEscape(state), ApiClient.HTTPClient, "", false); err == nil { + if r, err = HTTPGet(apiClient.URL+"/login/"+model.ServiceGitlab+"/complete?code="+url.QueryEscape(code)+"&state="+url.QueryEscape(state), apiClient.HTTPClient, "", false); err == nil { closeBody(r) } - redirect, _, err = ApiClient.AuthorizeOAuthApp(authRequest) + redirect, _, err = apiClient.AuthorizeOAuthApp(authRequest) require.NoError(t, err) rurl, _ = url.Parse(redirect) code = rurl.Query().Get("code") delete(stateProps, "action") state = base64.StdEncoding.EncodeToString([]byte(model.MapToJson(stateProps))) - if r, err = HTTPGet(ApiClient.Url+"/login/"+model.ServiceGitlab+"/complete?code="+url.QueryEscape(code)+"&state="+url.QueryEscape(state), ApiClient.HTTPClient, "", false); err == nil { + if r, err = HTTPGet(apiClient.URL+"/login/"+model.ServiceGitlab+"/complete?code="+url.QueryEscape(code)+"&state="+url.QueryEscape(state), apiClient.HTTPClient, "", false); err == nil { closeBody(r) } - redirect, _, err = ApiClient.AuthorizeOAuthApp(authRequest) + redirect, _, err = apiClient.AuthorizeOAuthApp(authRequest) require.NoError(t, err) rurl, _ = url.Parse(redirect) code = rurl.Query().Get("code") stateProps["action"] = model.OAuthActionSignup state = base64.StdEncoding.EncodeToString([]byte(model.MapToJson(stateProps))) - if r, err := HTTPGet(ApiClient.Url+"/login/"+model.ServiceGitlab+"/complete?code="+url.QueryEscape(code)+"&state="+url.QueryEscape(state), ApiClient.HTTPClient, "", false); err == nil { + if r, err := HTTPGet(apiClient.URL+"/login/"+model.ServiceGitlab+"/complete?code="+url.QueryEscape(code)+"&state="+url.QueryEscape(state), apiClient.HTTPClient, "", false); err == nil { closeBody(r) } } diff --git a/web/saml.go b/web/saml.go index 17bd52e931..005874b7f5 100644 --- a/web/saml.go +++ b/web/saml.go @@ -17,8 +17,8 @@ import ( ) func (w *Web) InitSaml() { - w.MainRouter.Handle("/login/sso/saml", w.ApiHandler(loginWithSaml)).Methods("GET") - w.MainRouter.Handle("/login/sso/saml", w.ApiHandlerTrustRequester(completeSaml)).Methods("POST") + w.MainRouter.Handle("/login/sso/saml", w.APIHandler(loginWithSaml)).Methods("GET") + w.MainRouter.Handle("/login/sso/saml", w.APIHandlerTrustRequester(completeSaml)).Methods("POST") } func loginWithSaml(c *Context, w http.ResponseWriter, r *http.Request) { diff --git a/web/static.go b/web/static.go index 6ea57acdd2..fc5cd3b2e3 100644 --- a/web/static.go +++ b/web/static.go @@ -65,7 +65,7 @@ func root(c *Context, w http.ResponseWriter, r *http.Request) { return } - if IsApiCall(c.App, r) { + if IsAPICall(c.App, r) { Handle404(c.App, w, r) return } diff --git a/web/web.go b/web/web.go index f682ffd24e..33ff506d5d 100644 --- a/web/web.go +++ b/web/web.go @@ -62,7 +62,7 @@ func Handle404(a app.AppIface, w http.ResponseWriter, r *http.Request) { ipAddress := utils.GetIPAddress(r, a.Config().ServiceSettings.TrustedProxyIPHeader) mlog.Debug("not found handler triggered", mlog.String("path", r.URL.Path), mlog.Int("code", 404), mlog.String("ip", ipAddress)) - if IsApiCall(a, r) { + if IsAPICall(a, r) { w.WriteHeader(err.StatusCode) err.DetailedError = "There doesn't appear to be an api call for the url='" + r.URL.Path + "'. Typo? are you missing a team_id or user_id as part of the url?" w.Write([]byte(err.ToJson())) @@ -73,7 +73,7 @@ func Handle404(a app.AppIface, w http.ResponseWriter, r *http.Request) { } } -func IsApiCall(a app.AppIface, r *http.Request) bool { +func IsAPICall(a app.AppIface, r *http.Request) bool { subpath, _ := utils.GetSubpathFromConfig(a.Config()) return strings.HasPrefix(r.URL.Path, path.Join(subpath, "api")+"/") @@ -85,7 +85,7 @@ func IsWebhookCall(a app.AppIface, r *http.Request) bool { return strings.HasPrefix(r.URL.Path, path.Join(subpath, "hooks")+"/") } -func IsOAuthApiCall(a app.AppIface, r *http.Request) bool { +func IsOAuthAPICall(a app.AppIface, r *http.Request) bool { subpath, _ := utils.GetSubpathFromConfig(a.Config()) if r.Method == "POST" && r.URL.Path == path.Join(subpath, "oauth", "authorize") { diff --git a/web/web_test.go b/web/web_test.go index 786b98e1b5..214a31b9ff 100644 --- a/web/web_test.go +++ b/web/web_test.go @@ -27,7 +27,7 @@ import ( "github.com/mattermost/mattermost-server/v6/utils" ) -var ApiClient *model.Client4 +var apiClient *model.Client4 var URL string type TestHelper struct { @@ -115,7 +115,7 @@ func setupTestHelper(includeCacheLayer bool) *TestHelper { web := New(a, s.Router) URL = fmt.Sprintf("http://localhost:%v", s.ListenAddr.Port) - ApiClient = model.NewAPIv4Client(URL) + apiClient = model.NewAPIv4Client(URL) s.Store.MarkSystemRanUnitTests() diff --git a/web/webhook_test.go b/web/webhook_test.go index d1bec45368..ebda0c7104 100644 --- a/web/webhook_test.go +++ b/web/webhook_test.go @@ -21,7 +21,7 @@ func TestIncomingWebhook(t *testing.T) { defer th.TearDown() if !*th.App.Config().ServiceSettings.EnableIncomingWebhooks { - _, err := http.Post(ApiClient.Url+"/hooks/123", "", strings.NewReader("123")) + _, err := http.Post(apiClient.URL+"/hooks/123", "", strings.NewReader("123")) assert.Error(t, err, "should have errored - webhooks turned off") return } @@ -29,7 +29,7 @@ func TestIncomingWebhook(t *testing.T) { hook, err := th.App.CreateIncomingWebhookForChannel(th.BasicUser.Id, th.BasicChannel, &model.IncomingWebhook{ChannelId: th.BasicChannel.Id}) require.Nil(t, err) - url := ApiClient.Url + "/hooks/" + hook.Id + url := apiClient.URL + "/hooks/" + hook.Id tooLongText := "" for i := 0; i < 8200; i++ { @@ -53,7 +53,7 @@ func TestIncomingWebhook(t *testing.T) { assert.NotEqual(t, http.StatusOK, resp.StatusCode, "should have errored - bad channel") payload = "payload={\"text\": \"test text\"}" - resp, err = http.Post(ApiClient.Url+"/hooks/abc123", "application/x-www-form-urlencoded", strings.NewReader(payload)) + resp, err = http.Post(apiClient.URL+"/hooks/abc123", "application/x-www-form-urlencoded", strings.NewReader(payload)) require.NoError(t, err) assert.NotEqual(t, http.StatusOK, resp.StatusCode, "should have errored - bad hook") @@ -116,7 +116,7 @@ func TestIncomingWebhook(t *testing.T) { assert.Equal(t, http.StatusBadRequest, resp.StatusCode) payloadMultiPart := "------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"username\"\r\n\r\nwebhook-bot\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"text\"\r\n\r\nthis is a test :tada:\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW--" - resp, err = http.Post(ApiClient.Url+"/hooks/"+hook.Id, "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW", strings.NewReader(payloadMultiPart)) + resp, err = http.Post(apiClient.URL+"/hooks/"+hook.Id, "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW", strings.NewReader(payloadMultiPart)) require.NoError(t, err) assert.Equal(t, http.StatusOK, resp.StatusCode) @@ -146,9 +146,9 @@ func TestIncomingWebhook(t *testing.T) { // System-Admin Owned Hook adminHook, appErr := th.App.CreateIncomingWebhookForChannel(th.SystemAdminUser.Id, th.BasicChannel, &model.IncomingWebhook{ChannelId: th.BasicChannel.Id}) require.Nil(t, appErr) - adminUrl := ApiClient.Url + "/hooks/" + adminHook.Id + adminURL := apiClient.URL + "/hooks/" + adminHook.Id - resp, err = http.Post(adminUrl, "application/json", strings.NewReader(fmt.Sprintf("{\"text\":\"this is a test\", \"channel\":\"%s\"}", model.DefaultChannelName))) + resp, err = http.Post(adminURL, "application/json", strings.NewReader(fmt.Sprintf("{\"text\":\"this is a test\", \"channel\":\"%s\"}", model.DefaultChannelName))) require.NoError(t, err) assert.Equal(t, http.StatusOK, resp.StatusCode) @@ -239,18 +239,18 @@ func TestIncomingWebhook(t *testing.T) { require.Nil(t, err) require.NotNil(t, hook) - apiHookUrl := ApiClient.Url + "/hooks/" + hook.Id + apiHookURL := apiClient.URL + "/hooks/" + hook.Id payload := "payload={\"text\": \"test text\"}" - resp, err2 := http.Post(apiHookUrl, "application/x-www-form-urlencoded", strings.NewReader(payload)) + resp, err2 := http.Post(apiHookURL, "application/x-www-form-urlencoded", strings.NewReader(payload)) require.NoError(t, err2) assert.True(t, resp.StatusCode == http.StatusOK) - resp, err2 = http.Post(apiHookUrl, "application/json", strings.NewReader(fmt.Sprintf("{\"text\":\"this is a test\", \"channel\":\"%s\"}", th.BasicChannel.Name))) + resp, err2 = http.Post(apiHookURL, "application/json", strings.NewReader(fmt.Sprintf("{\"text\":\"this is a test\", \"channel\":\"%s\"}", th.BasicChannel.Name))) require.NoError(t, err2) assert.True(t, resp.StatusCode == http.StatusOK) - resp, err2 = http.Post(apiHookUrl, "application/json", strings.NewReader(fmt.Sprintf("{\"text\":\"this is a test\", \"channel\":\"%s\"}", channel.Name))) + resp, err2 = http.Post(apiHookURL, "application/json", strings.NewReader(fmt.Sprintf("{\"text\":\"this is a test\", \"channel\":\"%s\"}", channel.Name))) require.NoError(t, err2) assert.True(t, resp.StatusCode == http.StatusForbidden) }) @@ -284,20 +284,20 @@ func TestCommandWebhooks(t *testing.T) { hook, appErr := th.App.CreateCommandWebhook(cmd.Id, args) require.Nil(t, appErr) - resp, err := http.Post(ApiClient.Url+"/hooks/commands/123123123123", "application/json", bytes.NewBufferString(`{"text":"this is a test"}`)) + resp, err := http.Post(apiClient.URL+"/hooks/commands/123123123123", "application/json", bytes.NewBufferString(`{"text":"this is a test"}`)) require.NoError(t, err) assert.Equal(t, http.StatusNotFound, resp.StatusCode, "expected not-found for non-existent hook") - resp, err = http.Post(ApiClient.Url+"/hooks/commands/"+hook.Id, "application/json", bytes.NewBufferString(`{"text":"invalid`)) + resp, err = http.Post(apiClient.URL+"/hooks/commands/"+hook.Id, "application/json", bytes.NewBufferString(`{"text":"invalid`)) require.NoError(t, err) assert.Equal(t, http.StatusBadRequest, resp.StatusCode) for i := 0; i < 5; i++ { - response, err2 := http.Post(ApiClient.Url+"/hooks/commands/"+hook.Id, "application/json", bytes.NewBufferString(`{"text":"this is a test"}`)) + response, err2 := http.Post(apiClient.URL+"/hooks/commands/"+hook.Id, "application/json", bytes.NewBufferString(`{"text":"this is a test"}`)) require.NoError(t, err2) require.Equal(t, http.StatusOK, response.StatusCode) } - resp, _ = http.Post(ApiClient.Url+"/hooks/commands/"+hook.Id, "application/json", bytes.NewBufferString(`{"text":"this is a test"}`)) + resp, _ = http.Post(apiClient.URL+"/hooks/commands/"+hook.Id, "application/json", bytes.NewBufferString(`{"text":"this is a test"}`)) require.Equal(t, http.StatusBadRequest, resp.StatusCode) } diff --git a/wsapi/status.go b/wsapi/status.go index 0951aecad2..7e10ff12cd 100644 --- a/wsapi/status.go +++ b/wsapi/status.go @@ -9,8 +9,8 @@ import ( ) func (api *API) InitStatus() { - api.Router.Handle("get_statuses", api.ApiWebSocketHandler(api.getStatuses)) - api.Router.Handle("get_statuses_by_ids", api.ApiWebSocketHandler(api.getStatusesByIds)) + api.Router.Handle("get_statuses", api.APIWebSocketHandler(api.getStatuses)) + api.Router.Handle("get_statuses_by_ids", api.APIWebSocketHandler(api.getStatusesByIds)) } func (api *API) getStatuses(req *model.WebSocketRequest) (map[string]interface{}, *model.AppError) { diff --git a/wsapi/system.go b/wsapi/system.go index 7733367811..274836ed37 100644 --- a/wsapi/system.go +++ b/wsapi/system.go @@ -8,7 +8,7 @@ import ( ) func (api *API) InitSystem() { - api.Router.Handle("ping", api.ApiWebSocketHandler(ping)) + api.Router.Handle("ping", api.APIWebSocketHandler(ping)) } func ping(req *model.WebSocketRequest) (map[string]interface{}, *model.AppError) { diff --git a/wsapi/user.go b/wsapi/user.go index 81f5bd33a4..245f8bef3d 100644 --- a/wsapi/user.go +++ b/wsapi/user.go @@ -8,8 +8,8 @@ import ( ) func (api *API) InitUser() { - api.Router.Handle("user_typing", api.ApiWebSocketHandler(api.userTyping)) - api.Router.Handle("user_update_active_status", api.ApiWebSocketHandler(api.userUpdateActiveStatus)) + api.Router.Handle("user_typing", api.APIWebSocketHandler(api.userTyping)) + api.Router.Handle("user_update_active_status", api.APIWebSocketHandler(api.userUpdateActiveStatus)) } func (api *API) userTyping(req *model.WebSocketRequest) (map[string]interface{}, *model.AppError) { diff --git a/wsapi/websocket_handler.go b/wsapi/websocket_handler.go index 529320236e..9f25325f01 100644 --- a/wsapi/websocket_handler.go +++ b/wsapi/websocket_handler.go @@ -12,7 +12,7 @@ import ( "github.com/mattermost/mattermost-server/v6/shared/mlog" ) -func (api *API) ApiWebSocketHandler(wh func(*model.WebSocketRequest) (map[string]interface{}, *model.AppError)) webSocketHandler { +func (api *API) APIWebSocketHandler(wh func(*model.WebSocketRequest) (map[string]interface{}, *model.AppError)) webSocketHandler { return webSocketHandler{api.App, wh} }