From dcf9e96a0b16530549168a7891ed8242663b5f28 Mon Sep 17 00:00:00 2001 From: Chris Date: Fri, 22 Sep 2017 12:54:27 -0500 Subject: remove global refs from api/api4 (#7496) --- api/admin.go | 54 +++++----- api/api.go | 118 +++++++++----------- api/apitestlib.go | 4 +- api/channel.go | 68 ++++++------ api/command.go | 24 ++--- api/context.go | 91 ++++++++++------ api/deprecated.go | 2 +- api/emoji.go | 10 +- api/file.go | 18 ++-- api/general.go | 8 +- api/license.go | 10 +- api/oauth.go | 22 ++-- api/post.go | 52 ++++----- api/preference.go | 12 +-- api/reaction.go | 8 +- api/status.go | 6 +- api/team.go | 44 ++++---- api/user.go | 110 +++++++++---------- api/webhook.go | 20 ++-- api/webrtc.go | 4 +- api/websocket.go | 4 +- api4/api.go | 233 +++++++++++++++++++--------------------- api4/apitestlib.go | 2 +- api4/brand.go | 6 +- api4/channel.go | 70 ++++++------ api4/cluster.go | 4 +- api4/command.go | 20 ++-- api4/compliance.go | 10 +- api4/context.go | 46 ++++++-- api4/elasticsearch.go | 6 +- api4/emoji.go | 12 +-- api4/file.go | 16 +-- api4/job.go | 12 +-- api4/ldap.go | 6 +- api4/oauth.go | 40 +++---- api4/openGraph.go | 4 +- api4/plugin.go | 10 +- api4/post.go | 42 ++++---- api4/preference.go | 12 +-- api4/reaction.go | 8 +- api4/saml.go | 18 ++-- api4/status.go | 8 +- api4/system.go | 34 +++--- api4/team.go | 60 +++++------ api4/user.go | 98 ++++++++--------- api4/webhook.go | 30 +++--- api4/webrtc.go | 4 +- api4/websocket.go | 4 +- cmd/platform/server.go | 8 +- cmd/platform/test.go | 8 +- manualtesting/manual_testing.go | 8 +- manualtesting/test_autolink.go | 2 +- web/web.go | 7 +- web/web_test.go | 6 +- 54 files changed, 783 insertions(+), 760 deletions(-) diff --git a/api/admin.go b/api/admin.go index 65cea5eb7..5b532c81a 100644 --- a/api/admin.go +++ b/api/admin.go @@ -15,34 +15,34 @@ import ( "github.com/mssola/user_agent" ) -func InitAdmin() { +func (api *API) InitAdmin() { l4g.Debug(utils.T("api.admin.init.debug")) - BaseRoutes.Admin.Handle("/logs", ApiAdminSystemRequired(getLogs)).Methods("GET") - BaseRoutes.Admin.Handle("/audits", ApiAdminSystemRequired(getAllAudits)).Methods("GET") - BaseRoutes.Admin.Handle("/config", ApiAdminSystemRequired(getConfig)).Methods("GET") - BaseRoutes.Admin.Handle("/save_config", ApiAdminSystemRequired(saveConfig)).Methods("POST") - BaseRoutes.Admin.Handle("/reload_config", ApiAdminSystemRequired(reloadConfig)).Methods("GET") - BaseRoutes.Admin.Handle("/invalidate_all_caches", ApiAdminSystemRequired(invalidateAllCaches)).Methods("GET") - BaseRoutes.Admin.Handle("/test_email", ApiAdminSystemRequired(testEmail)).Methods("POST") - BaseRoutes.Admin.Handle("/recycle_db_conn", ApiAdminSystemRequired(recycleDatabaseConnection)).Methods("GET") - BaseRoutes.Admin.Handle("/analytics/{id:[A-Za-z0-9]+}/{name:[A-Za-z0-9_]+}", ApiAdminSystemRequired(getAnalytics)).Methods("GET") - BaseRoutes.Admin.Handle("/analytics/{name:[A-Za-z0-9_]+}", ApiAdminSystemRequired(getAnalytics)).Methods("GET") - BaseRoutes.Admin.Handle("/save_compliance_report", ApiAdminSystemRequired(saveComplianceReport)).Methods("POST") - BaseRoutes.Admin.Handle("/compliance_reports", ApiAdminSystemRequired(getComplianceReports)).Methods("GET") - BaseRoutes.Admin.Handle("/download_compliance_report/{id:[A-Za-z0-9]+}", ApiAdminSystemRequiredTrustRequester(downloadComplianceReport)).Methods("GET") - BaseRoutes.Admin.Handle("/upload_brand_image", ApiAdminSystemRequired(uploadBrandImage)).Methods("POST") - BaseRoutes.Admin.Handle("/get_brand_image", ApiAppHandlerTrustRequester(getBrandImage)).Methods("GET") - BaseRoutes.Admin.Handle("/reset_mfa", ApiAdminSystemRequired(adminResetMfa)).Methods("POST") - BaseRoutes.Admin.Handle("/reset_password", ApiAdminSystemRequired(adminResetPassword)).Methods("POST") - BaseRoutes.Admin.Handle("/ldap_sync_now", ApiAdminSystemRequired(ldapSyncNow)).Methods("POST") - BaseRoutes.Admin.Handle("/ldap_test", ApiAdminSystemRequired(ldapTest)).Methods("POST") - BaseRoutes.Admin.Handle("/saml_metadata", ApiAppHandler(samlMetadata)).Methods("GET") - BaseRoutes.Admin.Handle("/add_certificate", ApiAdminSystemRequired(addCertificate)).Methods("POST") - BaseRoutes.Admin.Handle("/remove_certificate", ApiAdminSystemRequired(removeCertificate)).Methods("POST") - BaseRoutes.Admin.Handle("/saml_cert_status", ApiAdminSystemRequired(samlCertificateStatus)).Methods("GET") - BaseRoutes.Admin.Handle("/cluster_status", ApiAdminSystemRequired(getClusterStatus)).Methods("GET") - BaseRoutes.Admin.Handle("/recently_active_users/{team_id:[A-Za-z0-9]+}", ApiUserRequired(getRecentlyActiveUsers)).Methods("GET") + api.BaseRoutes.Admin.Handle("/logs", api.ApiAdminSystemRequired(getLogs)).Methods("GET") + api.BaseRoutes.Admin.Handle("/audits", api.ApiAdminSystemRequired(getAllAudits)).Methods("GET") + api.BaseRoutes.Admin.Handle("/config", api.ApiAdminSystemRequired(getConfig)).Methods("GET") + api.BaseRoutes.Admin.Handle("/save_config", api.ApiAdminSystemRequired(saveConfig)).Methods("POST") + api.BaseRoutes.Admin.Handle("/reload_config", api.ApiAdminSystemRequired(reloadConfig)).Methods("GET") + api.BaseRoutes.Admin.Handle("/invalidate_all_caches", api.ApiAdminSystemRequired(invalidateAllCaches)).Methods("GET") + api.BaseRoutes.Admin.Handle("/test_email", api.ApiAdminSystemRequired(testEmail)).Methods("POST") + api.BaseRoutes.Admin.Handle("/recycle_db_conn", api.ApiAdminSystemRequired(recycleDatabaseConnection)).Methods("GET") + api.BaseRoutes.Admin.Handle("/analytics/{id:[A-Za-z0-9]+}/{name:[A-Za-z0-9_]+}", api.ApiAdminSystemRequired(getAnalytics)).Methods("GET") + api.BaseRoutes.Admin.Handle("/analytics/{name:[A-Za-z0-9_]+}", api.ApiAdminSystemRequired(getAnalytics)).Methods("GET") + api.BaseRoutes.Admin.Handle("/save_compliance_report", api.ApiAdminSystemRequired(saveComplianceReport)).Methods("POST") + api.BaseRoutes.Admin.Handle("/compliance_reports", api.ApiAdminSystemRequired(getComplianceReports)).Methods("GET") + api.BaseRoutes.Admin.Handle("/download_compliance_report/{id:[A-Za-z0-9]+}", api.ApiAdminSystemRequiredTrustRequester(downloadComplianceReport)).Methods("GET") + api.BaseRoutes.Admin.Handle("/upload_brand_image", api.ApiAdminSystemRequired(uploadBrandImage)).Methods("POST") + api.BaseRoutes.Admin.Handle("/get_brand_image", api.ApiAppHandlerTrustRequester(getBrandImage)).Methods("GET") + api.BaseRoutes.Admin.Handle("/reset_mfa", api.ApiAdminSystemRequired(adminResetMfa)).Methods("POST") + api.BaseRoutes.Admin.Handle("/reset_password", api.ApiAdminSystemRequired(adminResetPassword)).Methods("POST") + api.BaseRoutes.Admin.Handle("/ldap_sync_now", api.ApiAdminSystemRequired(ldapSyncNow)).Methods("POST") + api.BaseRoutes.Admin.Handle("/ldap_test", api.ApiAdminSystemRequired(ldapTest)).Methods("POST") + api.BaseRoutes.Admin.Handle("/saml_metadata", api.ApiAppHandler(samlMetadata)).Methods("GET") + api.BaseRoutes.Admin.Handle("/add_certificate", api.ApiAdminSystemRequired(addCertificate)).Methods("POST") + api.BaseRoutes.Admin.Handle("/remove_certificate", api.ApiAdminSystemRequired(removeCertificate)).Methods("POST") + api.BaseRoutes.Admin.Handle("/saml_cert_status", api.ApiAdminSystemRequired(samlCertificateStatus)).Methods("GET") + api.BaseRoutes.Admin.Handle("/cluster_status", api.ApiAdminSystemRequired(getClusterStatus)).Methods("GET") + api.BaseRoutes.Admin.Handle("/recently_active_users/{team_id:[A-Za-z0-9]+}", api.ApiUserRequired(getRecentlyActiveUsers)).Methods("GET") } func getLogs(c *Context, w http.ResponseWriter, r *http.Request) { @@ -69,7 +69,7 @@ func getAllAudits(c *Context, w http.ResponseWriter, r *http.Request) { if audits, err := c.App.GetAudits("", 200); err != nil { c.Err = err return - } else if HandleEtag(audits.Etag(), "Get All Audits", w, r) { + } else if c.HandleEtag(audits.Etag(), "Get All Audits", w, r) { return } else { etag := audits.Etag() diff --git a/api/api.go b/api/api.go index 2dca63a07..283120b55 100644 --- a/api/api.go +++ b/api/api.go @@ -56,7 +56,10 @@ type Routes struct { Webrtc *mux.Router // 'api/v3/webrtc' } -var BaseRoutes *Routes +type API struct { + App *app.App + BaseRoutes *Routes +} func NewRouter() *mux.Router { ret := mux.NewRouter() @@ -64,51 +67,54 @@ func NewRouter() *mux.Router { return ret } -func InitApi(root *mux.Router) { - BaseRoutes = &Routes{} - BaseRoutes.Root = root - BaseRoutes.ApiRoot = root.PathPrefix(model.API_URL_SUFFIX_V3).Subrouter() - BaseRoutes.Users = BaseRoutes.ApiRoot.PathPrefix("/users").Subrouter() - BaseRoutes.NeedUser = BaseRoutes.Users.PathPrefix("/{user_id:[A-Za-z0-9]+}").Subrouter() - BaseRoutes.Teams = BaseRoutes.ApiRoot.PathPrefix("/teams").Subrouter() - BaseRoutes.NeedTeam = BaseRoutes.Teams.PathPrefix("/{team_id:[A-Za-z0-9]+}").Subrouter() - BaseRoutes.Channels = BaseRoutes.NeedTeam.PathPrefix("/channels").Subrouter() - BaseRoutes.NeedChannel = BaseRoutes.Channels.PathPrefix("/{channel_id:[A-Za-z0-9]+}").Subrouter() - BaseRoutes.NeedChannelName = BaseRoutes.Channels.PathPrefix("/name/{channel_name:[A-Za-z0-9_-]+}").Subrouter() - BaseRoutes.Posts = BaseRoutes.NeedChannel.PathPrefix("/posts").Subrouter() - BaseRoutes.NeedPost = BaseRoutes.Posts.PathPrefix("/{post_id:[A-Za-z0-9]+}").Subrouter() - BaseRoutes.Commands = BaseRoutes.NeedTeam.PathPrefix("/commands").Subrouter() - BaseRoutes.TeamFiles = BaseRoutes.NeedTeam.PathPrefix("/files").Subrouter() - BaseRoutes.Files = BaseRoutes.ApiRoot.PathPrefix("/files").Subrouter() - BaseRoutes.NeedFile = BaseRoutes.Files.PathPrefix("/{file_id:[A-Za-z0-9]+}").Subrouter() - BaseRoutes.Hooks = BaseRoutes.NeedTeam.PathPrefix("/hooks").Subrouter() - BaseRoutes.OAuth = BaseRoutes.ApiRoot.PathPrefix("/oauth").Subrouter() - BaseRoutes.Admin = BaseRoutes.ApiRoot.PathPrefix("/admin").Subrouter() - BaseRoutes.General = BaseRoutes.ApiRoot.PathPrefix("/general").Subrouter() - BaseRoutes.Preferences = BaseRoutes.ApiRoot.PathPrefix("/preferences").Subrouter() - BaseRoutes.License = BaseRoutes.ApiRoot.PathPrefix("/license").Subrouter() - BaseRoutes.Public = BaseRoutes.ApiRoot.PathPrefix("/public").Subrouter() - BaseRoutes.Emoji = BaseRoutes.ApiRoot.PathPrefix("/emoji").Subrouter() - BaseRoutes.Webrtc = BaseRoutes.ApiRoot.PathPrefix("/webrtc").Subrouter() - - InitUser() - InitTeam() - InitChannel() - InitPost() - InitWebSocket() - InitFile() - InitCommand() - InitAdmin() - InitGeneral() - InitOAuth() - InitWebhook() - InitPreference() - InitLicense() - InitEmoji() - InitStatus() - InitWebrtc() - InitReaction() - InitDeprecated() +func Init(a *app.App, root *mux.Router) *API { + api := &API{ + App: a, + BaseRoutes: &Routes{}, + } + api.BaseRoutes.Root = root + api.BaseRoutes.ApiRoot = root.PathPrefix(model.API_URL_SUFFIX_V3).Subrouter() + api.BaseRoutes.Users = api.BaseRoutes.ApiRoot.PathPrefix("/users").Subrouter() + api.BaseRoutes.NeedUser = api.BaseRoutes.Users.PathPrefix("/{user_id:[A-Za-z0-9]+}").Subrouter() + api.BaseRoutes.Teams = api.BaseRoutes.ApiRoot.PathPrefix("/teams").Subrouter() + api.BaseRoutes.NeedTeam = api.BaseRoutes.Teams.PathPrefix("/{team_id:[A-Za-z0-9]+}").Subrouter() + api.BaseRoutes.Channels = api.BaseRoutes.NeedTeam.PathPrefix("/channels").Subrouter() + api.BaseRoutes.NeedChannel = api.BaseRoutes.Channels.PathPrefix("/{channel_id:[A-Za-z0-9]+}").Subrouter() + api.BaseRoutes.NeedChannelName = api.BaseRoutes.Channels.PathPrefix("/name/{channel_name:[A-Za-z0-9_-]+}").Subrouter() + api.BaseRoutes.Posts = api.BaseRoutes.NeedChannel.PathPrefix("/posts").Subrouter() + api.BaseRoutes.NeedPost = api.BaseRoutes.Posts.PathPrefix("/{post_id:[A-Za-z0-9]+}").Subrouter() + api.BaseRoutes.Commands = api.BaseRoutes.NeedTeam.PathPrefix("/commands").Subrouter() + api.BaseRoutes.TeamFiles = api.BaseRoutes.NeedTeam.PathPrefix("/files").Subrouter() + api.BaseRoutes.Files = api.BaseRoutes.ApiRoot.PathPrefix("/files").Subrouter() + api.BaseRoutes.NeedFile = api.BaseRoutes.Files.PathPrefix("/{file_id:[A-Za-z0-9]+}").Subrouter() + api.BaseRoutes.Hooks = api.BaseRoutes.NeedTeam.PathPrefix("/hooks").Subrouter() + api.BaseRoutes.OAuth = api.BaseRoutes.ApiRoot.PathPrefix("/oauth").Subrouter() + api.BaseRoutes.Admin = api.BaseRoutes.ApiRoot.PathPrefix("/admin").Subrouter() + api.BaseRoutes.General = api.BaseRoutes.ApiRoot.PathPrefix("/general").Subrouter() + api.BaseRoutes.Preferences = api.BaseRoutes.ApiRoot.PathPrefix("/preferences").Subrouter() + api.BaseRoutes.License = api.BaseRoutes.ApiRoot.PathPrefix("/license").Subrouter() + api.BaseRoutes.Public = api.BaseRoutes.ApiRoot.PathPrefix("/public").Subrouter() + api.BaseRoutes.Emoji = api.BaseRoutes.ApiRoot.PathPrefix("/emoji").Subrouter() + api.BaseRoutes.Webrtc = api.BaseRoutes.ApiRoot.PathPrefix("/webrtc").Subrouter() + + api.InitUser() + api.InitTeam() + api.InitChannel() + api.InitPost() + api.InitWebSocket() + api.InitFile() + api.InitCommand() + api.InitAdmin() + api.InitGeneral() + api.InitOAuth() + api.InitWebhook() + api.InitPreference() + api.InitLicense() + api.InitEmoji() + api.InitStatus() + api.InitWebrtc() + api.InitReaction() + api.InitDeprecated() // 404 on any api route before web.go has a chance to serve it root.Handle("/api/{anything:.*}", http.HandlerFunc(Handle404)) @@ -120,26 +126,8 @@ func InitApi(root *mux.Router) { if *utils.Cfg.ServiceSettings.EnableAPIv3 { l4g.Info("API version 3 is scheduled for deprecation. Please see https://api.mattermost.com for details.") } -} - -func HandleEtag(etag string, routeName string, w http.ResponseWriter, r *http.Request) bool { - metrics := app.Global().Metrics - if et := r.Header.Get(model.HEADER_ETAG_CLIENT); len(etag) > 0 { - if et == etag { - w.Header().Set(model.HEADER_ETAG_SERVER, etag) - w.WriteHeader(http.StatusNotModified) - if metrics != nil { - metrics.IncrementEtagHitCounter(routeName) - } - return true - } - } - - if metrics != nil { - metrics.IncrementEtagMissCounter(routeName) - } - return false + return api } func ReturnStatusOK(w http.ResponseWriter) { diff --git a/api/apitestlib.go b/api/apitestlib.go index 276ff81e1..8504748e1 100644 --- a/api/apitestlib.go +++ b/api/apitestlib.go @@ -51,8 +51,8 @@ func setupTestHelper(enterprise bool) *TestHelper { th.App.Srv.Router = NewRouter() wsapi.InitRouter() th.App.StartServer() - api4.InitApi(th.App.Srv.Router, false) - InitApi(th.App.Srv.Router) + api4.Init(th.App, th.App.Srv.Router, false) + Init(th.App, th.App.Srv.Router) wsapi.InitApi() utils.EnableDebugLogForTest() th.App.Srv.Store.MarkSystemRanUnitTests() diff --git a/api/channel.go b/api/channel.go index 6867e0017..3b033fcb8 100644 --- a/api/channel.go +++ b/api/channel.go @@ -14,38 +14,38 @@ import ( "github.com/mattermost/mattermost-server/utils" ) -func InitChannel() { +func (api *API) InitChannel() { l4g.Debug(utils.T("api.channel.init.debug")) - BaseRoutes.Channels.Handle("/", ApiUserRequired(getChannels)).Methods("GET") - BaseRoutes.Channels.Handle("/more/{offset:[0-9]+}/{limit:[0-9]+}", ApiUserRequired(getMoreChannelsPage)).Methods("GET") - BaseRoutes.Channels.Handle("/more/search", ApiUserRequired(searchMoreChannels)).Methods("POST") - BaseRoutes.Channels.Handle("/counts", ApiUserRequired(getChannelCounts)).Methods("GET") - BaseRoutes.Channels.Handle("/members", ApiUserRequired(getMyChannelMembers)).Methods("GET") - BaseRoutes.Channels.Handle("/create", ApiUserRequired(createChannel)).Methods("POST") - BaseRoutes.Channels.Handle("/view", ApiUserRequired(viewChannel)).Methods("POST") - BaseRoutes.Channels.Handle("/create_direct", ApiUserRequired(createDirectChannel)).Methods("POST") - BaseRoutes.Channels.Handle("/create_group", ApiUserRequired(createGroupChannel)).Methods("POST") - BaseRoutes.Channels.Handle("/update", ApiUserRequired(updateChannel)).Methods("POST") - BaseRoutes.Channels.Handle("/update_header", ApiUserRequired(updateChannelHeader)).Methods("POST") - BaseRoutes.Channels.Handle("/update_purpose", ApiUserRequired(updateChannelPurpose)).Methods("POST") - BaseRoutes.Channels.Handle("/update_notify_props", ApiUserRequired(updateNotifyProps)).Methods("POST") - BaseRoutes.Channels.Handle("/autocomplete", ApiUserRequired(autocompleteChannels)).Methods("GET") - BaseRoutes.Channels.Handle("/name/{channel_name:[A-Za-z0-9_-]+}", ApiUserRequired(getChannelByName)).Methods("GET") - - BaseRoutes.NeedChannelName.Handle("/join", ApiUserRequired(join)).Methods("POST") - - BaseRoutes.NeedChannel.Handle("/", ApiUserRequired(getChannel)).Methods("GET") - BaseRoutes.NeedChannel.Handle("/stats", ApiUserRequired(getChannelStats)).Methods("GET") - BaseRoutes.NeedChannel.Handle("/members/{user_id:[A-Za-z0-9]+}", ApiUserRequired(getChannelMember)).Methods("GET") - BaseRoutes.NeedChannel.Handle("/members/ids", ApiUserRequired(getChannelMembersByIds)).Methods("POST") - BaseRoutes.NeedChannel.Handle("/pinned", ApiUserRequired(getPinnedPosts)).Methods("GET") - BaseRoutes.NeedChannel.Handle("/join", ApiUserRequired(join)).Methods("POST") - BaseRoutes.NeedChannel.Handle("/leave", ApiUserRequired(leave)).Methods("POST") - BaseRoutes.NeedChannel.Handle("/delete", ApiUserRequired(deleteChannel)).Methods("POST") - BaseRoutes.NeedChannel.Handle("/add", ApiUserRequired(addMember)).Methods("POST") - BaseRoutes.NeedChannel.Handle("/remove", ApiUserRequired(removeMember)).Methods("POST") - BaseRoutes.NeedChannel.Handle("/update_member_roles", ApiUserRequired(updateChannelMemberRoles)).Methods("POST") + api.BaseRoutes.Channels.Handle("/", api.ApiUserRequired(getChannels)).Methods("GET") + api.BaseRoutes.Channels.Handle("/more/{offset:[0-9]+}/{limit:[0-9]+}", api.ApiUserRequired(getMoreChannelsPage)).Methods("GET") + api.BaseRoutes.Channels.Handle("/more/search", api.ApiUserRequired(searchMoreChannels)).Methods("POST") + api.BaseRoutes.Channels.Handle("/counts", api.ApiUserRequired(getChannelCounts)).Methods("GET") + api.BaseRoutes.Channels.Handle("/members", api.ApiUserRequired(getMyChannelMembers)).Methods("GET") + api.BaseRoutes.Channels.Handle("/create", api.ApiUserRequired(createChannel)).Methods("POST") + api.BaseRoutes.Channels.Handle("/view", api.ApiUserRequired(viewChannel)).Methods("POST") + api.BaseRoutes.Channels.Handle("/create_direct", api.ApiUserRequired(createDirectChannel)).Methods("POST") + api.BaseRoutes.Channels.Handle("/create_group", api.ApiUserRequired(createGroupChannel)).Methods("POST") + api.BaseRoutes.Channels.Handle("/update", api.ApiUserRequired(updateChannel)).Methods("POST") + api.BaseRoutes.Channels.Handle("/update_header", api.ApiUserRequired(updateChannelHeader)).Methods("POST") + api.BaseRoutes.Channels.Handle("/update_purpose", api.ApiUserRequired(updateChannelPurpose)).Methods("POST") + api.BaseRoutes.Channels.Handle("/update_notify_props", api.ApiUserRequired(updateNotifyProps)).Methods("POST") + api.BaseRoutes.Channels.Handle("/autocomplete", api.ApiUserRequired(autocompleteChannels)).Methods("GET") + api.BaseRoutes.Channels.Handle("/name/{channel_name:[A-Za-z0-9_-]+}", api.ApiUserRequired(getChannelByName)).Methods("GET") + + api.BaseRoutes.NeedChannelName.Handle("/join", api.ApiUserRequired(join)).Methods("POST") + + api.BaseRoutes.NeedChannel.Handle("/", api.ApiUserRequired(getChannel)).Methods("GET") + api.BaseRoutes.NeedChannel.Handle("/stats", api.ApiUserRequired(getChannelStats)).Methods("GET") + api.BaseRoutes.NeedChannel.Handle("/members/{user_id:[A-Za-z0-9]+}", api.ApiUserRequired(getChannelMember)).Methods("GET") + api.BaseRoutes.NeedChannel.Handle("/members/ids", api.ApiUserRequired(getChannelMembersByIds)).Methods("POST") + api.BaseRoutes.NeedChannel.Handle("/pinned", api.ApiUserRequired(getPinnedPosts)).Methods("GET") + api.BaseRoutes.NeedChannel.Handle("/join", api.ApiUserRequired(join)).Methods("POST") + api.BaseRoutes.NeedChannel.Handle("/leave", api.ApiUserRequired(leave)).Methods("POST") + api.BaseRoutes.NeedChannel.Handle("/delete", api.ApiUserRequired(deleteChannel)).Methods("POST") + api.BaseRoutes.NeedChannel.Handle("/add", api.ApiUserRequired(addMember)).Methods("POST") + api.BaseRoutes.NeedChannel.Handle("/remove", api.ApiUserRequired(removeMember)).Methods("POST") + api.BaseRoutes.NeedChannel.Handle("/update_member_roles", api.ApiUserRequired(updateChannelMemberRoles)).Methods("POST") } func createChannel(c *Context, w http.ResponseWriter, r *http.Request) { @@ -327,7 +327,7 @@ func getChannels(c *Context, w http.ResponseWriter, r *http.Request) { } c.Err = err return - } else if HandleEtag(channels.Etag(), "Get Channels", w, r) { + } else if c.HandleEtag(channels.Etag(), "Get Channels", w, r) { return } else { w.Header().Set(model.HEADER_ETAG_SERVER, channels.Etag()) @@ -372,7 +372,7 @@ func getChannelCounts(c *Context, w http.ResponseWriter, r *http.Request) { if counts, err := c.App.GetChannelCounts(c.TeamId, c.Session.UserId); err != nil { c.Err = model.NewAppError("getChannelCounts", "api.channel.get_channel_counts.app_error", nil, err.Message, http.StatusInternalServerError) return - } else if HandleEtag(counts.Etag(), "Get Channel Counts", w, r) { + } else if c.HandleEtag(counts.Etag(), "Get Channel Counts", w, r) { return } else { w.Header().Set(model.HEADER_ETAG_SERVER, counts.Etag()) @@ -494,7 +494,7 @@ func getChannel(c *Context, w http.ResponseWriter, r *http.Request) { data.Channel = channel data.Member = member - if HandleEtag(data.Etag(), "Get Channel", w, r) { + if c.HandleEtag(data.Etag(), "Get Channel", w, r) { return } else { w.Header().Set(model.HEADER_ETAG_SERVER, data.Etag()) @@ -520,7 +520,7 @@ func getChannelByName(c *Context, w http.ResponseWriter, r *http.Request) { return } - if HandleEtag(channel.Etag(), "Get Channel By Name", w, r) { + if c.HandleEtag(channel.Etag(), "Get Channel By Name", w, r) { return } else { w.Header().Set(model.HEADER_ETAG_SERVER, channel.Etag()) diff --git a/api/command.go b/api/command.go index cad294823..673683d6a 100644 --- a/api/command.go +++ b/api/command.go @@ -15,22 +15,22 @@ import ( "github.com/mattermost/mattermost-server/utils" ) -func InitCommand() { +func (api *API) InitCommand() { l4g.Debug(utils.T("api.command.init.debug")) - BaseRoutes.Commands.Handle("/execute", ApiUserRequired(executeCommand)).Methods("POST") - BaseRoutes.Commands.Handle("/list", ApiUserRequired(listCommands)).Methods("GET") + api.BaseRoutes.Commands.Handle("/execute", api.ApiUserRequired(executeCommand)).Methods("POST") + api.BaseRoutes.Commands.Handle("/list", api.ApiUserRequired(listCommands)).Methods("GET") - BaseRoutes.Commands.Handle("/create", ApiUserRequired(createCommand)).Methods("POST") - BaseRoutes.Commands.Handle("/update", ApiUserRequired(updateCommand)).Methods("POST") - BaseRoutes.Commands.Handle("/list_team_commands", ApiUserRequired(listTeamCommands)).Methods("GET") - BaseRoutes.Commands.Handle("/regen_token", ApiUserRequired(regenCommandToken)).Methods("POST") - BaseRoutes.Commands.Handle("/delete", ApiUserRequired(deleteCommand)).Methods("POST") + api.BaseRoutes.Commands.Handle("/create", api.ApiUserRequired(createCommand)).Methods("POST") + api.BaseRoutes.Commands.Handle("/update", api.ApiUserRequired(updateCommand)).Methods("POST") + api.BaseRoutes.Commands.Handle("/list_team_commands", api.ApiUserRequired(listTeamCommands)).Methods("GET") + api.BaseRoutes.Commands.Handle("/regen_token", api.ApiUserRequired(regenCommandToken)).Methods("POST") + api.BaseRoutes.Commands.Handle("/delete", api.ApiUserRequired(deleteCommand)).Methods("POST") - BaseRoutes.Teams.Handle("/command_test", ApiAppHandler(testCommand)).Methods("POST") - BaseRoutes.Teams.Handle("/command_test", ApiAppHandler(testCommand)).Methods("GET") - BaseRoutes.Teams.Handle("/command_test_e", ApiAppHandler(testEphemeralCommand)).Methods("POST") - BaseRoutes.Teams.Handle("/command_test_e", ApiAppHandler(testEphemeralCommand)).Methods("GET") + api.BaseRoutes.Teams.Handle("/command_test", api.ApiAppHandler(testCommand)).Methods("POST") + api.BaseRoutes.Teams.Handle("/command_test", api.ApiAppHandler(testCommand)).Methods("GET") + api.BaseRoutes.Teams.Handle("/command_test_e", api.ApiAppHandler(testEphemeralCommand)).Methods("POST") + api.BaseRoutes.Teams.Handle("/command_test_e", api.ApiAppHandler(testEphemeralCommand)).Methods("GET") } func listCommands(c *Context, w http.ResponseWriter, r *http.Request) { diff --git a/api/context.go b/api/context.go index ebc439d31..0322b6c43 100644 --- a/api/context.go +++ b/api/context.go @@ -35,59 +35,60 @@ type Context struct { isSystemAdmin bool } -func ApiAppHandler(h func(*Context, http.ResponseWriter, *http.Request)) http.Handler { - return &handler{h, false, false, true, false, false, false, false} +func (api *API) ApiAppHandler(h func(*Context, http.ResponseWriter, *http.Request)) http.Handler { + return &handler{api.App, h, false, false, true, false, false, false, false} } -func AppHandler(h func(*Context, http.ResponseWriter, *http.Request)) http.Handler { - return &handler{h, false, false, false, false, false, false, false} +func (api *API) AppHandler(h func(*Context, http.ResponseWriter, *http.Request)) http.Handler { + return &handler{api.App, h, false, false, false, false, false, false, false} } -func AppHandlerIndependent(h func(*Context, http.ResponseWriter, *http.Request)) http.Handler { - return &handler{h, false, false, false, false, true, false, false} +func (api *API) AppHandlerIndependent(h func(*Context, http.ResponseWriter, *http.Request)) http.Handler { + return &handler{api.App, h, false, false, false, false, true, false, false} } -func ApiUserRequired(h func(*Context, http.ResponseWriter, *http.Request)) http.Handler { - return &handler{h, true, false, true, false, false, false, true} +func (api *API) ApiUserRequired(h func(*Context, http.ResponseWriter, *http.Request)) http.Handler { + return &handler{api.App, h, true, false, true, false, false, false, true} } -func ApiUserRequiredActivity(h func(*Context, http.ResponseWriter, *http.Request), isUserActivity bool) http.Handler { - return &handler{h, true, false, true, isUserActivity, false, false, true} +func (api *API) ApiUserRequiredActivity(h func(*Context, http.ResponseWriter, *http.Request), isUserActivity bool) http.Handler { + return &handler{api.App, h, true, false, true, isUserActivity, false, false, true} } -func ApiUserRequiredMfa(h func(*Context, http.ResponseWriter, *http.Request)) http.Handler { - return &handler{h, true, false, true, false, false, false, false} +func (api *API) ApiUserRequiredMfa(h func(*Context, http.ResponseWriter, *http.Request)) http.Handler { + return &handler{api.App, h, true, false, true, false, false, false, false} } -func UserRequired(h func(*Context, http.ResponseWriter, *http.Request)) http.Handler { - return &handler{h, true, false, false, false, false, false, true} +func (api *API) UserRequired(h func(*Context, http.ResponseWriter, *http.Request)) http.Handler { + return &handler{api.App, h, true, false, false, false, false, false, true} } -func AppHandlerTrustRequester(h func(*Context, http.ResponseWriter, *http.Request)) http.Handler { - return &handler{h, false, false, false, false, false, true, false} +func (api *API) AppHandlerTrustRequester(h func(*Context, http.ResponseWriter, *http.Request)) http.Handler { + return &handler{api.App, h, false, false, false, false, false, true, false} } -func ApiAdminSystemRequired(h func(*Context, http.ResponseWriter, *http.Request)) http.Handler { - return &handler{h, true, true, true, false, false, false, true} +func (api *API) ApiAdminSystemRequired(h func(*Context, http.ResponseWriter, *http.Request)) http.Handler { + return &handler{api.App, h, true, true, true, false, false, false, true} } -func ApiAdminSystemRequiredTrustRequester(h func(*Context, http.ResponseWriter, *http.Request)) http.Handler { - return &handler{h, true, true, true, false, false, true, true} +func (api *API) ApiAdminSystemRequiredTrustRequester(h func(*Context, http.ResponseWriter, *http.Request)) http.Handler { + return &handler{api.App, h, true, true, true, false, false, true, true} } -func ApiAppHandlerTrustRequester(h func(*Context, http.ResponseWriter, *http.Request)) http.Handler { - return &handler{h, false, false, true, false, false, true, false} +func (api *API) ApiAppHandlerTrustRequester(h func(*Context, http.ResponseWriter, *http.Request)) http.Handler { + return &handler{api.App, h, false, false, true, false, false, true, false} } -func ApiUserRequiredTrustRequester(h func(*Context, http.ResponseWriter, *http.Request)) http.Handler { - return &handler{h, true, false, true, false, false, true, true} +func (api *API) ApiUserRequiredTrustRequester(h func(*Context, http.ResponseWriter, *http.Request)) http.Handler { + return &handler{api.App, h, true, false, true, false, false, true, true} } -func ApiAppHandlerTrustRequesterIndependent(h func(*Context, http.ResponseWriter, *http.Request)) http.Handler { - return &handler{h, false, false, true, false, true, true, false} +func (api *API) ApiAppHandlerTrustRequesterIndependent(h func(*Context, http.ResponseWriter, *http.Request)) http.Handler { + return &handler{api.App, h, false, false, true, false, true, true, false} } type handler struct { + app *app.App handleFunc func(*Context, http.ResponseWriter, *http.Request) requireUser bool requireSystemAdmin bool @@ -103,7 +104,7 @@ func (h handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { l4g.Debug("%v", r.URL.Path) c := &Context{} - c.App = app.Global() + c.App = h.app c.T, c.Locale = utils.GetTranslationsAndLocale(w, r) c.RequestId = model.NewId() c.IpAddress = utils.GetIpAddress(r) @@ -166,7 +167,7 @@ func (h handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { } if len(token) != 0 { - session, err := app.Global().GetSession(token) + session, err := c.App.GetSession(token) if err != nil { l4g.Error(utils.T("api.context.invalid_session.error"), err.Error()) @@ -207,8 +208,8 @@ func (h handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { } if c.Err == nil && h.isUserActivity && token != "" && len(c.Session.UserId) > 0 { - app.Global().SetStatusOnline(c.Session.UserId, c.Session.Id, false) - app.Global().UpdateLastActivityAtIfNeeded(c.Session) + c.App.SetStatusOnline(c.Session.UserId, c.Session.Id, false) + c.App.UpdateLastActivityAtIfNeeded(c.Session) } if c.Err == nil && (h.requireUser || h.requireSystemAdmin) { @@ -259,7 +260,7 @@ func (h handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { func (c *Context) LogAudit(extraInfo string) { audit := &model.Audit{UserId: c.Session.UserId, IpAddress: c.IpAddress, Action: c.Path, ExtraInfo: extraInfo, SessionId: c.Session.Id} - if r := <-app.Global().Srv.Store.Audit().Save(audit); r.Err != nil { + if r := <-c.App.Srv.Store.Audit().Save(audit); r.Err != nil { c.LogError(r.Err) } } @@ -271,7 +272,7 @@ func (c *Context) LogAuditWithUserId(userId, extraInfo string) { } audit := &model.Audit{UserId: userId, IpAddress: c.IpAddress, Action: c.Path, ExtraInfo: extraInfo, SessionId: c.Session.Id} - if r := <-app.Global().Srv.Store.Audit().Save(audit); r.Err != nil { + if r := <-c.App.Srv.Store.Audit().Save(audit); r.Err != nil { c.LogError(r.Err) } } @@ -315,7 +316,7 @@ func (c *Context) MfaRequired() { return } - if result := <-app.Global().Srv.Store.User().Get(c.Session.UserId); result.Err != nil { + if result := <-c.App.Srv.Store.User().Get(c.Session.UserId); result.Err != nil { c.Err = model.NewAppError("", "api.context.session_expired.app_error", nil, "MfaRequired", http.StatusUnauthorized) return } else { @@ -392,7 +393,7 @@ func (c *Context) setTeamURL(url string, valid bool) { } func (c *Context) SetTeamURLFromSession() { - if result := <-app.Global().Srv.Store.Team().Get(c.TeamId); result.Err == nil { + if result := <-c.App.Srv.Store.Team().Get(c.TeamId); result.Err == nil { c.setTeamURL(c.GetSiteURLHeader()+"/"+result.Data.(*model.Team).Name, true) } } @@ -424,6 +425,26 @@ func (c *Context) GetCurrentTeamMember() *model.TeamMember { return c.Session.GetTeamByTeamId(c.TeamId) } +func (c *Context) HandleEtag(etag string, routeName string, w http.ResponseWriter, r *http.Request) bool { + metrics := c.App.Metrics + if et := r.Header.Get(model.HEADER_ETAG_CLIENT); len(etag) > 0 { + if et == etag { + w.Header().Set(model.HEADER_ETAG_SERVER, etag) + w.WriteHeader(http.StatusNotModified) + if metrics != nil { + metrics.IncrementEtagHitCounter(routeName) + } + return true + } + } + + if metrics != nil { + metrics.IncrementEtagMissCounter(routeName) + } + + return false +} + func IsApiCall(r *http.Request) bool { return strings.Index(r.URL.Path, "/api/") == 0 } @@ -446,7 +467,7 @@ func Handle404(w http.ResponseWriter, r *http.Request) { func (c *Context) CheckTeamId() { if c.TeamId != "" && c.Session.GetTeamByTeamId(c.TeamId) == nil { if app.SessionHasPermissionTo(c.Session, model.PERMISSION_MANAGE_SYSTEM) { - if result := <-app.Global().Srv.Store.Team().Get(c.TeamId); result.Err != nil { + if result := <-c.App.Srv.Store.Team().Get(c.TeamId); result.Err != nil { c.Err = result.Err c.Err.StatusCode = http.StatusBadRequest return diff --git a/api/deprecated.go b/api/deprecated.go index 739b6658c..f62af84de 100644 --- a/api/deprecated.go +++ b/api/deprecated.go @@ -10,6 +10,6 @@ import ( // ONLY FOR APIs SCHEDULED TO BE DEPRECATED -func InitDeprecated() { +func (api *API) InitDeprecated() { l4g.Debug(utils.T("api.deprecated.init.debug")) } diff --git a/api/emoji.go b/api/emoji.go index 2b29974e3..1961ad146 100644 --- a/api/emoji.go +++ b/api/emoji.go @@ -21,13 +21,13 @@ import ( "github.com/mattermost/mattermost-server/utils" ) -func InitEmoji() { +func (api *API) InitEmoji() { l4g.Debug(utils.T("api.emoji.init.debug")) - BaseRoutes.Emoji.Handle("/list", ApiUserRequired(getEmoji)).Methods("GET") - BaseRoutes.Emoji.Handle("/create", ApiUserRequired(createEmoji)).Methods("POST") - BaseRoutes.Emoji.Handle("/delete", ApiUserRequired(deleteEmoji)).Methods("POST") - BaseRoutes.Emoji.Handle("/{id:[A-Za-z0-9_]+}", ApiUserRequiredTrustRequester(getEmojiImage)).Methods("GET") + api.BaseRoutes.Emoji.Handle("/list", api.ApiUserRequired(getEmoji)).Methods("GET") + api.BaseRoutes.Emoji.Handle("/create", api.ApiUserRequired(createEmoji)).Methods("POST") + api.BaseRoutes.Emoji.Handle("/delete", api.ApiUserRequired(deleteEmoji)).Methods("POST") + api.BaseRoutes.Emoji.Handle("/{id:[A-Za-z0-9_]+}", api.ApiUserRequiredTrustRequester(getEmojiImage)).Methods("GET") } func getEmoji(c *Context, w http.ResponseWriter, r *http.Request) { diff --git a/api/file.go b/api/file.go index 28ad5db08..28007f222 100644 --- a/api/file.go +++ b/api/file.go @@ -30,19 +30,19 @@ var UNSAFE_CONTENT_TYPES = [...]string{ "text/html", } -func InitFile() { +func (api *API) InitFile() { l4g.Debug(utils.T("api.file.init.debug")) - BaseRoutes.TeamFiles.Handle("/upload", ApiUserRequired(uploadFile)).Methods("POST") + api.BaseRoutes.TeamFiles.Handle("/upload", api.ApiUserRequired(uploadFile)).Methods("POST") - BaseRoutes.NeedFile.Handle("/get", ApiUserRequiredTrustRequester(getFile)).Methods("GET") - BaseRoutes.NeedFile.Handle("/get_thumbnail", ApiUserRequiredTrustRequester(getFileThumbnail)).Methods("GET") - BaseRoutes.NeedFile.Handle("/get_preview", ApiUserRequiredTrustRequester(getFilePreview)).Methods("GET") - BaseRoutes.NeedFile.Handle("/get_info", ApiUserRequired(getFileInfo)).Methods("GET") - BaseRoutes.NeedFile.Handle("/get_public_link", ApiUserRequired(getPublicLink)).Methods("GET") + api.BaseRoutes.NeedFile.Handle("/get", api.ApiUserRequiredTrustRequester(getFile)).Methods("GET") + api.BaseRoutes.NeedFile.Handle("/get_thumbnail", api.ApiUserRequiredTrustRequester(getFileThumbnail)).Methods("GET") + api.BaseRoutes.NeedFile.Handle("/get_preview", api.ApiUserRequiredTrustRequester(getFilePreview)).Methods("GET") + api.BaseRoutes.NeedFile.Handle("/get_info", api.ApiUserRequired(getFileInfo)).Methods("GET") + api.BaseRoutes.NeedFile.Handle("/get_public_link", api.ApiUserRequired(getPublicLink)).Methods("GET") - BaseRoutes.Public.Handle("/files/{file_id:[A-Za-z0-9]+}/get", ApiAppHandlerTrustRequesterIndependent(getPublicFile)).Methods("GET") - BaseRoutes.Public.Handle("/files/get/{team_id:[A-Za-z0-9]+}/{channel_id:[A-Za-z0-9]+}/{user_id:[A-Za-z0-9]+}/{filename:(?:[A-Za-z0-9]+/)?.+(?:\\.[A-Za-z0-9]{3,})?}", ApiAppHandlerTrustRequesterIndependent(getPublicFileOld)).Methods("GET") + api.BaseRoutes.Public.Handle("/files/{file_id:[A-Za-z0-9]+}/get", api.ApiAppHandlerTrustRequesterIndependent(getPublicFile)).Methods("GET") + api.BaseRoutes.Public.Handle("/files/get/{team_id:[A-Za-z0-9]+}/{channel_id:[A-Za-z0-9]+}/{user_id:[A-Za-z0-9]+}/{filename:(?:[A-Za-z0-9]+/)?.+(?:\\.[A-Za-z0-9]{3,})?}", api.ApiAppHandlerTrustRequesterIndependent(getPublicFileOld)).Methods("GET") } func uploadFile(c *Context, w http.ResponseWriter, r *http.Request) { diff --git a/api/general.go b/api/general.go index 09bbc75c5..015baec4e 100644 --- a/api/general.go +++ b/api/general.go @@ -15,12 +15,12 @@ import ( "github.com/mattermost/mattermost-server/utils" ) -func InitGeneral() { +func (api *API) InitGeneral() { l4g.Debug(utils.T("api.general.init.debug")) - BaseRoutes.General.Handle("/client_props", ApiAppHandler(getClientConfig)).Methods("GET") - BaseRoutes.General.Handle("/log_client", ApiAppHandler(logClient)).Methods("POST") - BaseRoutes.General.Handle("/ping", ApiAppHandler(ping)).Methods("GET") + api.BaseRoutes.General.Handle("/client_props", api.ApiAppHandler(getClientConfig)).Methods("GET") + api.BaseRoutes.General.Handle("/log_client", api.ApiAppHandler(logClient)).Methods("POST") + api.BaseRoutes.General.Handle("/ping", api.ApiAppHandler(ping)).Methods("GET") } func getClientConfig(c *Context, w http.ResponseWriter, r *http.Request) { diff --git a/api/license.go b/api/license.go index e9ba85e59..18d6a20a3 100644 --- a/api/license.go +++ b/api/license.go @@ -14,12 +14,12 @@ import ( "github.com/mattermost/mattermost-server/utils" ) -func InitLicense() { +func (api *API) InitLicense() { l4g.Debug(utils.T("api.license.init.debug")) - BaseRoutes.License.Handle("/add", ApiAdminSystemRequired(addLicense)).Methods("POST") - BaseRoutes.License.Handle("/remove", ApiAdminSystemRequired(removeLicense)).Methods("POST") - BaseRoutes.License.Handle("/client_config", ApiAppHandler(getClientLicenceConfig)).Methods("GET") + api.BaseRoutes.License.Handle("/add", api.ApiAdminSystemRequired(addLicense)).Methods("POST") + api.BaseRoutes.License.Handle("/remove", api.ApiAdminSystemRequired(removeLicense)).Methods("POST") + api.BaseRoutes.License.Handle("/client_config", api.ApiAppHandler(getClientLicenceConfig)).Methods("GET") } func addLicense(c *Context, w http.ResponseWriter, r *http.Request) { @@ -88,7 +88,7 @@ func getClientLicenceConfig(c *Context, w http.ResponseWriter, r *http.Request) useSanitizedLicense := !app.SessionHasPermissionTo(c.Session, model.PERMISSION_MANAGE_SYSTEM) etag := utils.GetClientLicenseEtag(useSanitizedLicense) - if HandleEtag(etag, "Get Client License Config", w, r) { + if c.HandleEtag(etag, "Get Client License Config", w, r) { return } diff --git a/api/oauth.go b/api/oauth.go index 6297b998c..0a26a6f98 100644 --- a/api/oauth.go +++ b/api/oauth.go @@ -13,19 +13,19 @@ import ( "github.com/mattermost/mattermost-server/utils" ) -func InitOAuth() { +func (api *API) InitOAuth() { l4g.Debug(utils.T("api.oauth.init.debug")) - BaseRoutes.OAuth.Handle("/register", ApiUserRequired(registerOAuthApp)).Methods("POST") - BaseRoutes.OAuth.Handle("/list", ApiUserRequired(getOAuthApps)).Methods("GET") - BaseRoutes.OAuth.Handle("/app/{client_id}", ApiUserRequired(getOAuthAppInfo)).Methods("GET") - BaseRoutes.OAuth.Handle("/allow", ApiUserRequired(allowOAuth)).Methods("GET") - BaseRoutes.OAuth.Handle("/authorized", ApiUserRequired(getAuthorizedApps)).Methods("GET") - BaseRoutes.OAuth.Handle("/delete", ApiUserRequired(deleteOAuthApp)).Methods("POST") - BaseRoutes.OAuth.Handle("/{id:[A-Za-z0-9]+}/deauthorize", ApiUserRequired(deauthorizeOAuthApp)).Methods("POST") - BaseRoutes.OAuth.Handle("/{id:[A-Za-z0-9]+}/regen_secret", ApiUserRequired(regenerateOAuthSecret)).Methods("POST") - BaseRoutes.OAuth.Handle("/{service:[A-Za-z0-9]+}/login", AppHandlerIndependent(loginWithOAuth)).Methods("GET") - BaseRoutes.OAuth.Handle("/{service:[A-Za-z0-9]+}/signup", AppHandlerIndependent(signupWithOAuth)).Methods("GET") + api.BaseRoutes.OAuth.Handle("/register", api.ApiUserRequired(registerOAuthApp)).Methods("POST") + api.BaseRoutes.OAuth.Handle("/list", api.ApiUserRequired(getOAuthApps)).Methods("GET") + api.BaseRoutes.OAuth.Handle("/app/{client_id}", api.ApiUserRequired(getOAuthAppInfo)).Methods("GET") + api.BaseRoutes.OAuth.Handle("/allow", api.ApiUserRequired(allowOAuth)).Methods("GET") + api.BaseRoutes.OAuth.Handle("/authorized", api.ApiUserRequired(getAuthorizedApps)).Methods("GET") + api.BaseRoutes.OAuth.Handle("/delete", api.ApiUserRequired(deleteOAuthApp)).Methods("POST") + api.BaseRoutes.OAuth.Handle("/{id:[A-Za-z0-9]+}/deauthorize", api.ApiUserRequired(deauthorizeOAuthApp)).Methods("POST") + api.BaseRoutes.OAuth.Handle("/{id:[A-Za-z0-9]+}/regen_secret", api.ApiUserRequired(regenerateOAuthSecret)).Methods("POST") + api.BaseRoutes.OAuth.Handle("/{service:[A-Za-z0-9]+}/login", api.AppHandlerIndependent(loginWithOAuth)).Methods("GET") + api.BaseRoutes.OAuth.Handle("/{service:[A-Za-z0-9]+}/signup", api.AppHandlerIndependent(signupWithOAuth)).Methods("GET") } func registerOAuthApp(c *Context, w http.ResponseWriter, r *http.Request) { diff --git a/api/post.go b/api/post.go index 60c9b59bd..703c070c5 100644 --- a/api/post.go +++ b/api/post.go @@ -18,28 +18,28 @@ const OPEN_GRAPH_METADATA_CACHE_SIZE = 10000 var openGraphDataCache = utils.NewLru(OPEN_GRAPH_METADATA_CACHE_SIZE) -func InitPost() { +func (api *API) InitPost() { l4g.Debug(utils.T("api.post.init.debug")) - BaseRoutes.ApiRoot.Handle("/get_opengraph_metadata", ApiUserRequired(getOpenGraphMetadata)).Methods("POST") - - BaseRoutes.NeedTeam.Handle("/posts/search", ApiUserRequiredActivity(searchPosts, true)).Methods("POST") - BaseRoutes.NeedTeam.Handle("/posts/flagged/{offset:[0-9]+}/{limit:[0-9]+}", ApiUserRequired(getFlaggedPosts)).Methods("GET") - BaseRoutes.NeedTeam.Handle("/posts/{post_id}", ApiUserRequired(getPostById)).Methods("GET") - BaseRoutes.NeedTeam.Handle("/pltmp/{post_id}", ApiUserRequired(getPermalinkTmp)).Methods("GET") - - BaseRoutes.Posts.Handle("/create", ApiUserRequiredActivity(createPost, true)).Methods("POST") - BaseRoutes.Posts.Handle("/update", ApiUserRequiredActivity(updatePost, true)).Methods("POST") - BaseRoutes.Posts.Handle("/page/{offset:[0-9]+}/{limit:[0-9]+}", ApiUserRequired(getPosts)).Methods("GET") - BaseRoutes.Posts.Handle("/since/{time:[0-9]+}", ApiUserRequired(getPostsSince)).Methods("GET") - - BaseRoutes.NeedPost.Handle("/get", ApiUserRequired(getPost)).Methods("GET") - BaseRoutes.NeedPost.Handle("/delete", ApiUserRequiredActivity(deletePost, true)).Methods("POST") - BaseRoutes.NeedPost.Handle("/before/{offset:[0-9]+}/{num_posts:[0-9]+}", ApiUserRequired(getPostsBefore)).Methods("GET") - BaseRoutes.NeedPost.Handle("/after/{offset:[0-9]+}/{num_posts:[0-9]+}", ApiUserRequired(getPostsAfter)).Methods("GET") - BaseRoutes.NeedPost.Handle("/get_file_infos", ApiUserRequired(getFileInfosForPost)).Methods("GET") - BaseRoutes.NeedPost.Handle("/pin", ApiUserRequired(pinPost)).Methods("POST") - BaseRoutes.NeedPost.Handle("/unpin", ApiUserRequired(unpinPost)).Methods("POST") + api.BaseRoutes.ApiRoot.Handle("/get_opengraph_metadata", api.ApiUserRequired(getOpenGraphMetadata)).Methods("POST") + + api.BaseRoutes.NeedTeam.Handle("/posts/search", api.ApiUserRequiredActivity(searchPosts, true)).Methods("POST") + api.BaseRoutes.NeedTeam.Handle("/posts/flagged/{offset:[0-9]+}/{limit:[0-9]+}", api.ApiUserRequired(getFlaggedPosts)).Methods("GET") + api.BaseRoutes.NeedTeam.Handle("/posts/{post_id}", api.ApiUserRequired(getPostById)).Methods("GET") + api.BaseRoutes.NeedTeam.Handle("/pltmp/{post_id}", api.ApiUserRequired(getPermalinkTmp)).Methods("GET") + + api.BaseRoutes.Posts.Handle("/create", api.ApiUserRequiredActivity(createPost, true)).Methods("POST") + api.BaseRoutes.Posts.Handle("/update", api.ApiUserRequiredActivity(updatePost, true)).Methods("POST") + api.BaseRoutes.Posts.Handle("/page/{offset:[0-9]+}/{limit:[0-9]+}", api.ApiUserRequired(getPosts)).Methods("GET") + api.BaseRoutes.Posts.Handle("/since/{time:[0-9]+}", api.ApiUserRequired(getPostsSince)).Methods("GET") + + api.BaseRoutes.NeedPost.Handle("/get", api.ApiUserRequired(getPost)).Methods("GET") + api.BaseRoutes.NeedPost.Handle("/delete", api.ApiUserRequiredActivity(deletePost, true)).Methods("POST") + api.BaseRoutes.NeedPost.Handle("/before/{offset:[0-9]+}/{num_posts:[0-9]+}", api.ApiUserRequired(getPostsBefore)).Methods("GET") + api.BaseRoutes.NeedPost.Handle("/after/{offset:[0-9]+}/{num_posts:[0-9]+}", api.ApiUserRequired(getPostsAfter)).Methods("GET") + api.BaseRoutes.NeedPost.Handle("/get_file_infos", api.ApiUserRequired(getFileInfosForPost)).Methods("GET") + api.BaseRoutes.NeedPost.Handle("/pin", api.ApiUserRequired(pinPost)).Methods("POST") + api.BaseRoutes.NeedPost.Handle("/unpin", api.ApiUserRequired(unpinPost)).Methods("POST") } func createPost(c *Context, w http.ResponseWriter, r *http.Request) { @@ -212,7 +212,7 @@ func getPosts(c *Context, w http.ResponseWriter, r *http.Request) { etag := c.App.GetPostsEtag(id) - if HandleEtag(etag, "Get Posts", w, r) { + if c.HandleEtag(etag, "Get Posts", w, r) { return } @@ -278,7 +278,7 @@ func getPost(c *Context, w http.ResponseWriter, r *http.Request) { if list, err := c.App.GetPostThread(postId); err != nil { c.Err = err return - } else if HandleEtag(list.Etag(), "Get Post", w, r) { + } else if c.HandleEtag(list.Etag(), "Get Post", w, r) { return } else { if !list.IsChannelId(channelId) { @@ -315,7 +315,7 @@ func getPostById(c *Context, w http.ResponseWriter, r *http.Request) { return } - if HandleEtag(list.Etag(), "Get Post By Id", w, r) { + if c.HandleEtag(list.Etag(), "Get Post By Id", w, r) { return } @@ -356,7 +356,7 @@ func getPermalinkTmp(c *Context, w http.ResponseWriter, r *http.Request) { if list, err := c.App.GetPermalinkPost(postId, c.Session.UserId); err != nil { c.Err = err return - } else if HandleEtag(list.Etag(), "Get Permalink TMP", w, r) { + } else if c.HandleEtag(list.Etag(), "Get Permalink TMP", w, r) { return } else { w.Header().Set(model.HEADER_ETAG_SERVER, list.Etag()) @@ -447,7 +447,7 @@ func getPostsBeforeOrAfter(c *Context, w http.ResponseWriter, r *http.Request, b // We can do better than this etag in this situation etag := c.App.GetPostsEtag(id) - if HandleEtag(etag, "Get Posts Before or After", w, r) { + if c.HandleEtag(etag, "Get Posts Before or After", w, r) { return } @@ -507,7 +507,7 @@ func getFileInfosForPost(c *Context, w http.ResponseWriter, r *http.Request) { if infos, err := c.App.GetFileInfosForPost(postId, false); err != nil { c.Err = err return - } else if HandleEtag(model.GetEtagForFileInfos(infos), "Get File Infos For Post", w, r) { + } else if c.HandleEtag(model.GetEtagForFileInfos(infos), "Get File Infos For Post", w, r) { return } else { if len(infos) > 0 { diff --git a/api/preference.go b/api/preference.go index 097908c72..f4d7d2842 100644 --- a/api/preference.go +++ b/api/preference.go @@ -12,14 +12,14 @@ import ( "github.com/mattermost/mattermost-server/utils" ) -func InitPreference() { +func (api *API) InitPreference() { l4g.Debug(utils.T("api.preference.init.debug")) - BaseRoutes.Preferences.Handle("/", ApiUserRequired(getAllPreferences)).Methods("GET") - BaseRoutes.Preferences.Handle("/save", ApiUserRequired(savePreferences)).Methods("POST") - BaseRoutes.Preferences.Handle("/delete", ApiUserRequired(deletePreferences)).Methods("POST") - BaseRoutes.Preferences.Handle("/{category:[A-Za-z0-9_]+}", ApiUserRequired(getPreferenceCategory)).Methods("GET") - BaseRoutes.Preferences.Handle("/{category:[A-Za-z0-9_]+}/{name:[A-Za-z0-9_]+}", ApiUserRequired(getPreference)).Methods("GET") + api.BaseRoutes.Preferences.Handle("/", api.ApiUserRequired(getAllPreferences)).Methods("GET") + api.BaseRoutes.Preferences.Handle("/save", api.ApiUserRequired(savePreferences)).Methods("POST") + api.BaseRoutes.Preferences.Handle("/delete", api.ApiUserRequired(deletePreferences)).Methods("POST") + api.BaseRoutes.Preferences.Handle("/{category:[A-Za-z0-9_]+}", api.ApiUserRequired(getPreferenceCategory)).Methods("GET") + api.BaseRoutes.Preferences.Handle("/{category:[A-Za-z0-9_]+}/{name:[A-Za-z0-9_]+}", api.ApiUserRequired(getPreference)).Methods("GET") } func getAllPreferences(c *Context, w http.ResponseWriter, r *http.Request) { diff --git a/api/reaction.go b/api/reaction.go index 9e12d99f7..28cc9ade2 100644 --- a/api/reaction.go +++ b/api/reaction.go @@ -13,12 +13,12 @@ import ( "github.com/mattermost/mattermost-server/utils" ) -func InitReaction() { +func (api *API) InitReaction() { l4g.Debug(utils.T("api.reaction.init.debug")) - BaseRoutes.NeedPost.Handle("/reactions/save", ApiUserRequired(saveReaction)).Methods("POST") - BaseRoutes.NeedPost.Handle("/reactions/delete", ApiUserRequired(deleteReaction)).Methods("POST") - BaseRoutes.NeedPost.Handle("/reactions", ApiUserRequired(listReactions)).Methods("GET") + api.BaseRoutes.NeedPost.Handle("/reactions/save", api.ApiUserRequired(saveReaction)).Methods("POST") + api.BaseRoutes.NeedPost.Handle("/reactions/delete", api.ApiUserRequired(deleteReaction)).Methods("POST") + api.BaseRoutes.NeedPost.Handle("/reactions", api.ApiUserRequired(listReactions)).Methods("GET") } func saveReaction(c *Context, w http.ResponseWriter, r *http.Request) { diff --git a/api/status.go b/api/status.go index fbd986ea3..70106ad8c 100644 --- a/api/status.go +++ b/api/status.go @@ -13,11 +13,11 @@ import ( "github.com/mattermost/mattermost-server/utils" ) -func InitStatus() { +func (api *API) InitStatus() { l4g.Debug(utils.T("api.status.init.debug")) - BaseRoutes.Users.Handle("/status", ApiUserRequired(getStatusesHttp)).Methods("GET") - BaseRoutes.Users.Handle("/status/ids", ApiUserRequired(getStatusesByIdsHttp)).Methods("POST") + api.BaseRoutes.Users.Handle("/status", api.ApiUserRequired(getStatusesHttp)).Methods("GET") + api.BaseRoutes.Users.Handle("/status/ids", api.ApiUserRequired(getStatusesByIdsHttp)).Methods("POST") } func getStatusesHttp(c *Context, w http.ResponseWriter, r *http.Request) { diff --git a/api/team.go b/api/team.go index 962d53965..8a8d3c935 100644 --- a/api/team.go +++ b/api/team.go @@ -18,34 +18,34 @@ import ( "github.com/mattermost/mattermost-server/utils" ) -func InitTeam() { +func (api *API) InitTeam() { l4g.Debug(utils.T("api.team.init.debug")) - BaseRoutes.Teams.Handle("/create", ApiUserRequired(createTeam)).Methods("POST") - BaseRoutes.Teams.Handle("/all", ApiUserRequired(getAll)).Methods("GET") - BaseRoutes.Teams.Handle("/all_team_listings", ApiUserRequired(GetAllTeamListings)).Methods("GET") - BaseRoutes.Teams.Handle("/get_invite_info", ApiAppHandler(getInviteInfo)).Methods("POST") - BaseRoutes.Teams.Handle("/find_team_by_name", ApiUserRequired(findTeamByName)).Methods("POST") - BaseRoutes.Teams.Handle("/name/{team_name:[A-Za-z0-9\\-]+}", ApiUserRequired(getTeamByName)).Methods("GET") - BaseRoutes.Teams.Handle("/members", ApiUserRequired(getMyTeamMembers)).Methods("GET") - BaseRoutes.Teams.Handle("/unread", ApiUserRequired(getMyTeamsUnread)).Methods("GET") + api.BaseRoutes.Teams.Handle("/create", api.ApiUserRequired(createTeam)).Methods("POST") + api.BaseRoutes.Teams.Handle("/all", api.ApiUserRequired(getAll)).Methods("GET") + api.BaseRoutes.Teams.Handle("/all_team_listings", api.ApiUserRequired(GetAllTeamListings)).Methods("GET") + api.BaseRoutes.Teams.Handle("/get_invite_info", api.ApiAppHandler(getInviteInfo)).Methods("POST") + api.BaseRoutes.Teams.Handle("/find_team_by_name", api.ApiUserRequired(findTeamByName)).Methods("POST") + api.BaseRoutes.Teams.Handle("/name/{team_name:[A-Za-z0-9\\-]+}", api.ApiUserRequired(getTeamByName)).Methods("GET") + api.BaseRoutes.Teams.Handle("/members", api.ApiUserRequired(getMyTeamMembers)).Methods("GET") + api.BaseRoutes.Teams.Handle("/unread", api.ApiUserRequired(getMyTeamsUnread)).Methods("GET") - BaseRoutes.NeedTeam.Handle("/me", ApiUserRequired(getMyTeam)).Methods("GET") - BaseRoutes.NeedTeam.Handle("/stats", ApiUserRequired(getTeamStats)).Methods("GET") - BaseRoutes.NeedTeam.Handle("/members/{offset:[0-9]+}/{limit:[0-9]+}", ApiUserRequired(getTeamMembers)).Methods("GET") - BaseRoutes.NeedTeam.Handle("/members/ids", ApiUserRequired(getTeamMembersByIds)).Methods("POST") - BaseRoutes.NeedTeam.Handle("/members/{user_id:[A-Za-z0-9]+}", ApiUserRequired(getTeamMember)).Methods("GET") - BaseRoutes.NeedTeam.Handle("/update", ApiUserRequired(updateTeam)).Methods("POST") - BaseRoutes.NeedTeam.Handle("/update_member_roles", ApiUserRequired(updateMemberRoles)).Methods("POST") + api.BaseRoutes.NeedTeam.Handle("/me", api.ApiUserRequired(getMyTeam)).Methods("GET") + api.BaseRoutes.NeedTeam.Handle("/stats", api.ApiUserRequired(getTeamStats)).Methods("GET") + api.BaseRoutes.NeedTeam.Handle("/members/{offset:[0-9]+}/{limit:[0-9]+}", api.ApiUserRequired(getTeamMembers)).Methods("GET") + api.BaseRoutes.NeedTeam.Handle("/members/ids", api.ApiUserRequired(getTeamMembersByIds)).Methods("POST") + api.BaseRoutes.NeedTeam.Handle("/members/{user_id:[A-Za-z0-9]+}", api.ApiUserRequired(getTeamMember)).Methods("GET") + api.BaseRoutes.NeedTeam.Handle("/update", api.ApiUserRequired(updateTeam)).Methods("POST") + api.BaseRoutes.NeedTeam.Handle("/update_member_roles", api.ApiUserRequired(updateMemberRoles)).Methods("POST") - BaseRoutes.NeedTeam.Handle("/invite_members", ApiUserRequired(inviteMembers)).Methods("POST") + api.BaseRoutes.NeedTeam.Handle("/invite_members", api.ApiUserRequired(inviteMembers)).Methods("POST") - BaseRoutes.NeedTeam.Handle("/add_user_to_team", ApiUserRequired(addUserToTeam)).Methods("POST") - BaseRoutes.NeedTeam.Handle("/remove_user_from_team", ApiUserRequired(removeUserFromTeam)).Methods("POST") + api.BaseRoutes.NeedTeam.Handle("/add_user_to_team", api.ApiUserRequired(addUserToTeam)).Methods("POST") + api.BaseRoutes.NeedTeam.Handle("/remove_user_from_team", api.ApiUserRequired(removeUserFromTeam)).Methods("POST") // These should be moved to the global admin console - BaseRoutes.NeedTeam.Handle("/import_team", ApiUserRequired(importTeam)).Methods("POST") - BaseRoutes.Teams.Handle("/add_user_to_team_from_invite", ApiUserRequiredMfa(addUserToTeamFromInvite)).Methods("POST") + api.BaseRoutes.NeedTeam.Handle("/import_team", api.ApiUserRequired(importTeam)).Methods("POST") + api.BaseRoutes.Teams.Handle("/add_user_to_team_from_invite", api.ApiUserRequiredMfa(addUserToTeamFromInvite)).Methods("POST") } func createTeam(c *Context, w http.ResponseWriter, r *http.Request) { @@ -338,7 +338,7 @@ func getMyTeam(c *Context, w http.ResponseWriter, r *http.Request) { if team, err := c.App.GetTeam(c.TeamId); err != nil { c.Err = err return - } else if HandleEtag(team.Etag(), "Get My Team", w, r) { + } else if c.HandleEtag(team.Etag(), "Get My Team", w, r) { return } else { w.Header().Set(model.HEADER_ETAG_SERVER, team.Etag()) diff --git a/api/user.go b/api/user.go index af012ac2c..5aeb2762b 100644 --- a/api/user.go +++ b/api/user.go @@ -19,55 +19,55 @@ import ( "github.com/mattermost/mattermost-server/utils" ) -func InitUser() { +func (api *API) InitUser() { l4g.Debug(utils.T("api.user.init.debug")) - BaseRoutes.Users.Handle("/create", ApiAppHandler(createUser)).Methods("POST") - BaseRoutes.Users.Handle("/update", ApiUserRequired(updateUser)).Methods("POST") - BaseRoutes.Users.Handle("/update_active", ApiUserRequired(updateActive)).Methods("POST") - BaseRoutes.Users.Handle("/update_notify", ApiUserRequired(updateUserNotify)).Methods("POST") - BaseRoutes.Users.Handle("/newpassword", ApiUserRequired(updatePassword)).Methods("POST") - BaseRoutes.Users.Handle("/send_password_reset", ApiAppHandler(sendPasswordReset)).Methods("POST") - BaseRoutes.Users.Handle("/reset_password", ApiAppHandler(resetPassword)).Methods("POST") - BaseRoutes.Users.Handle("/login", ApiAppHandler(login)).Methods("POST") - BaseRoutes.Users.Handle("/logout", ApiAppHandler(logout)).Methods("POST") - BaseRoutes.Users.Handle("/revoke_session", ApiUserRequired(revokeSession)).Methods("POST") - BaseRoutes.Users.Handle("/attach_device", ApiUserRequired(attachDeviceId)).Methods("POST") - //DEPRICATED FOR SECURITY USE APIV4 BaseRoutes.Users.Handle("/verify_email", ApiAppHandler(verifyEmail)).Methods("POST") - //DEPRICATED FOR SECURITY USE APIV4 BaseRoutes.Users.Handle("/resend_verification", ApiAppHandler(resendVerification)).Methods("POST") - BaseRoutes.Users.Handle("/newimage", ApiUserRequired(uploadProfileImage)).Methods("POST") - BaseRoutes.Users.Handle("/me", ApiUserRequired(getMe)).Methods("GET") - BaseRoutes.Users.Handle("/initial_load", ApiAppHandler(getInitialLoad)).Methods("GET") - BaseRoutes.Users.Handle("/{offset:[0-9]+}/{limit:[0-9]+}", ApiUserRequired(getProfiles)).Methods("GET") - BaseRoutes.NeedTeam.Handle("/users/{offset:[0-9]+}/{limit:[0-9]+}", ApiUserRequired(getProfilesInTeam)).Methods("GET") - BaseRoutes.NeedChannel.Handle("/users/{offset:[0-9]+}/{limit:[0-9]+}", ApiUserRequired(getProfilesInChannel)).Methods("GET") - BaseRoutes.NeedChannel.Handle("/users/not_in_channel/{offset:[0-9]+}/{limit:[0-9]+}", ApiUserRequired(getProfilesNotInChannel)).Methods("GET") - BaseRoutes.Users.Handle("/search", ApiUserRequired(searchUsers)).Methods("POST") - BaseRoutes.Users.Handle("/ids", ApiUserRequired(getProfilesByIds)).Methods("POST") - BaseRoutes.Users.Handle("/autocomplete", ApiUserRequired(autocompleteUsers)).Methods("GET") - - BaseRoutes.NeedTeam.Handle("/users/autocomplete", ApiUserRequired(autocompleteUsersInTeam)).Methods("GET") - BaseRoutes.NeedChannel.Handle("/users/autocomplete", ApiUserRequired(autocompleteUsersInChannel)).Methods("GET") - - BaseRoutes.Users.Handle("/mfa", ApiAppHandler(checkMfa)).Methods("POST") - BaseRoutes.Users.Handle("/generate_mfa_secret", ApiUserRequiredMfa(generateMfaSecret)).Methods("GET") - BaseRoutes.Users.Handle("/update_mfa", ApiUserRequiredMfa(updateMfa)).Methods("POST") - - BaseRoutes.Users.Handle("/claim/email_to_oauth", ApiAppHandler(emailToOAuth)).Methods("POST") - BaseRoutes.Users.Handle("/claim/oauth_to_email", ApiUserRequired(oauthToEmail)).Methods("POST") - BaseRoutes.Users.Handle("/claim/email_to_ldap", ApiAppHandler(emailToLdap)).Methods("POST") - BaseRoutes.Users.Handle("/claim/ldap_to_email", ApiAppHandler(ldapToEmail)).Methods("POST") - - BaseRoutes.NeedUser.Handle("/get", ApiUserRequired(getUser)).Methods("GET") - BaseRoutes.Users.Handle("/name/{username:[A-Za-z0-9_\\-.]+}", ApiUserRequired(getByUsername)).Methods("GET") - BaseRoutes.Users.Handle("/email/{email}", ApiUserRequired(getByEmail)).Methods("GET") - BaseRoutes.NeedUser.Handle("/sessions", ApiUserRequired(getSessions)).Methods("GET") - BaseRoutes.NeedUser.Handle("/audits", ApiUserRequired(getAudits)).Methods("GET") - BaseRoutes.NeedUser.Handle("/image", ApiUserRequiredTrustRequester(getProfileImage)).Methods("GET") - BaseRoutes.NeedUser.Handle("/update_roles", ApiUserRequired(updateRoles)).Methods("POST") - - BaseRoutes.Root.Handle("/login/sso/saml", AppHandlerIndependent(loginWithSaml)).Methods("GET") - BaseRoutes.Root.Handle("/login/sso/saml", AppHandlerIndependent(completeSaml)).Methods("POST") + api.BaseRoutes.Users.Handle("/create", api.ApiAppHandler(createUser)).Methods("POST") + api.BaseRoutes.Users.Handle("/update", api.ApiUserRequired(updateUser)).Methods("POST") + api.BaseRoutes.Users.Handle("/update_active", api.ApiUserRequired(updateActive)).Methods("POST") + api.BaseRoutes.Users.Handle("/update_notify", api.ApiUserRequired(updateUserNotify)).Methods("POST") + api.BaseRoutes.Users.Handle("/newpassword", api.ApiUserRequired(updatePassword)).Methods("POST") + api.BaseRoutes.Users.Handle("/send_password_reset", api.ApiAppHandler(sendPasswordReset)).Methods("POST") + api.BaseRoutes.Users.Handle("/reset_password", api.ApiAppHandler(resetPassword)).Methods("POST") + api.BaseRoutes.Users.Handle("/login", api.ApiAppHandler(login)).Methods("POST") + api.BaseRoutes.Users.Handle("/logout", api.ApiAppHandler(logout)).Methods("POST") + api.BaseRoutes.Users.Handle("/revoke_session", api.ApiUserRequired(revokeSession)).Methods("POST") + api.BaseRoutes.Users.Handle("/attach_device", api.ApiUserRequired(attachDeviceId)).Methods("POST") + //DEPRICATED FOR SECURITY USE APIV4 api.BaseRoutes.Users.Handle("/verify_email", ApiAppHandler(verifyEmail)).Methods("POST") + //DEPRICATED FOR SECURITY USE APIV4 api.BaseRoutes.Users.Handle("/resend_verification", ApiAppHandler(resendVerification)).Methods("POST") + api.BaseRoutes.Users.Handle("/newimage", api.ApiUserRequired(uploadProfileImage)).Methods("POST") + api.BaseRoutes.Users.Handle("/me", api.ApiUserRequired(getMe)).Methods("GET") + api.BaseRoutes.Users.Handle("/initial_load", api.ApiAppHandler(getInitialLoad)).Methods("GET") + api.BaseRoutes.Users.Handle("/{offset:[0-9]+}/{limit:[0-9]+}", api.ApiUserRequired(getProfiles)).Methods("GET") + api.BaseRoutes.NeedTeam.Handle("/users/{offset:[0-9]+}/{limit:[0-9]+}", api.ApiUserRequired(getProfilesInTeam)).Methods("GET") + api.BaseRoutes.NeedChannel.Handle("/users/{offset:[0-9]+}/{limit:[0-9]+}", api.ApiUserRequired(getProfilesInChannel)).Methods("GET") + api.BaseRoutes.NeedChannel.Handle("/users/not_in_channel/{offset:[0-9]+}/{limit:[0-9]+}", api.ApiUserRequired(getProfilesNotInChannel)).Methods("GET") + api.BaseRoutes.Users.Handle("/search", api.ApiUserRequired(searchUsers)).Methods("POST") + api.BaseRoutes.Users.Handle("/ids", api.ApiUserRequired(getProfilesByIds)).Methods("POST") + api.BaseRoutes.Users.Handle("/autocomplete", api.ApiUserRequired(autocompleteUsers)).Methods("GET") + + api.BaseRoutes.NeedTeam.Handle("/users/autocomplete", api.ApiUserRequired(autocompleteUsersInTeam)).Methods("GET") + api.BaseRoutes.NeedChannel.Handle("/users/autocomplete", api.ApiUserRequired(autocompleteUsersInChannel)).Methods("GET") + + api.BaseRoutes.Users.Handle("/mfa", api.ApiAppHandler(checkMfa)).Methods("POST") + api.BaseRoutes.Users.Handle("/generate_mfa_secret", api.ApiUserRequiredMfa(generateMfaSecret)).Methods("GET") + api.BaseRoutes.Users.Handle("/update_mfa", api.ApiUserRequiredMfa(updateMfa)).Methods("POST") + + api.BaseRoutes.Users.Handle("/claim/email_to_oauth", api.ApiAppHandler(emailToOAuth)).Methods("POST") + api.BaseRoutes.Users.Handle("/claim/oauth_to_email", api.ApiUserRequired(oauthToEmail)).Methods("POST") + api.BaseRoutes.Users.Handle("/claim/email_to_ldap", api.ApiAppHandler(emailToLdap)).Methods("POST") + api.BaseRoutes.Users.Handle("/claim/ldap_to_email", api.ApiAppHandler(ldapToEmail)).Methods("POST") + + api.BaseRoutes.NeedUser.Handle("/get", api.ApiUserRequired(getUser)).Methods("GET") + api.BaseRoutes.Users.Handle("/name/{username:[A-Za-z0-9_\\-.]+}", api.ApiUserRequired(getByUsername)).Methods("GET") + api.BaseRoutes.Users.Handle("/email/{email}", api.ApiUserRequired(getByEmail)).Methods("GET") + api.BaseRoutes.NeedUser.Handle("/sessions", api.ApiUserRequired(getSessions)).Methods("GET") + api.BaseRoutes.NeedUser.Handle("/audits", api.ApiUserRequired(getAudits)).Methods("GET") + api.BaseRoutes.NeedUser.Handle("/image", api.ApiUserRequiredTrustRequester(getProfileImage)).Methods("GET") + api.BaseRoutes.NeedUser.Handle("/update_roles", api.ApiUserRequired(updateRoles)).Methods("POST") + + api.BaseRoutes.Root.Handle("/login/sso/saml", api.AppHandlerIndependent(loginWithSaml)).Methods("GET") + api.BaseRoutes.Root.Handle("/login/sso/saml", api.AppHandlerIndependent(completeSaml)).Methods("POST") } func createUser(c *Context, w http.ResponseWriter, r *http.Request) { @@ -249,7 +249,7 @@ func getMe(c *Context, w http.ResponseWriter, r *http.Request) { c.RemoveSessionCookie(w, r) l4g.Error(utils.T("api.user.get_me.getting.error"), c.Session.UserId) return - } else if HandleEtag(user.Etag(utils.Cfg.PrivacySettings.ShowFullName, utils.Cfg.PrivacySettings.ShowEmailAddress), "Get Me", w, r) { + } else if c.HandleEtag(user.Etag(utils.Cfg.PrivacySettings.ShowFullName, utils.Cfg.PrivacySettings.ShowEmailAddress), "Get Me", w, r) { return } else { user.Sanitize(map[string]bool{}) @@ -323,7 +323,7 @@ func getUser(c *Context, w http.ResponseWriter, r *http.Request) { etag := user.Etag(utils.Cfg.PrivacySettings.ShowFullName, utils.Cfg.PrivacySettings.ShowEmailAddress) - if HandleEtag(etag, "Get User", w, r) { + if c.HandleEtag(etag, "Get User", w, r) { return } else { app.SanitizeProfile(user, c.IsSystemAdmin()) @@ -343,7 +343,7 @@ func getByUsername(c *Context, w http.ResponseWriter, r *http.Request) { if user, err = c.App.GetUserByUsername(username); err != nil { c.Err = err return - } else if HandleEtag(user.Etag(utils.Cfg.PrivacySettings.ShowFullName, utils.Cfg.PrivacySettings.ShowEmailAddress), "Get By Username", w, r) { + } else if c.HandleEtag(user.Etag(utils.Cfg.PrivacySettings.ShowFullName, utils.Cfg.PrivacySettings.ShowEmailAddress), "Get By Username", w, r) { return } else { sanitizeProfile(c, user) @@ -361,7 +361,7 @@ func getByEmail(c *Context, w http.ResponseWriter, r *http.Request) { if user, err := c.App.GetUserByEmail(email); err != nil { c.Err = err return - } else if HandleEtag(user.Etag(utils.Cfg.PrivacySettings.ShowFullName, utils.Cfg.PrivacySettings.ShowEmailAddress), "Get By Email", w, r) { + } else if c.HandleEtag(user.Etag(utils.Cfg.PrivacySettings.ShowFullName, utils.Cfg.PrivacySettings.ShowEmailAddress), "Get By Email", w, r) { return } else { sanitizeProfile(c, user) @@ -388,7 +388,7 @@ func getProfiles(c *Context, w http.ResponseWriter, r *http.Request) { } etag := c.App.GetUsersEtag() + params["offset"] + "." + params["limit"] - if HandleEtag(etag, "Get Profiles", w, r) { + if c.HandleEtag(etag, "Get Profiles", w, r) { return } @@ -424,7 +424,7 @@ func getProfilesInTeam(c *Context, w http.ResponseWriter, r *http.Request) { } etag := c.App.GetUsersInTeamEtag(teamId) - if HandleEtag(etag, "Get Profiles In Team", w, r) { + if c.HandleEtag(etag, "Get Profiles In Team", w, r) { return } @@ -524,7 +524,7 @@ func getAudits(c *Context, w http.ResponseWriter, r *http.Request) { } else { etag := audits.Etag() - if HandleEtag(etag, "Get Audits", w, r) { + if c.HandleEtag(etag, "Get Audits", w, r) { return } @@ -555,7 +555,7 @@ func getProfileImage(c *Context, w http.ResponseWriter, r *http.Request) { user := users[0] etag = strconv.FormatInt(user.LastPictureUpdate, 10) - if HandleEtag(etag, "Profile Image", w, r) { + if c.HandleEtag(etag, "Profile Image", w, r) { return } diff --git a/api/webhook.go b/api/webhook.go index f0c6701eb..b9ac9336d 100644 --- a/api/webhook.go +++ b/api/webhook.go @@ -12,19 +12,19 @@ import ( "github.com/mattermost/mattermost-server/utils" ) -func InitWebhook() { +func (api *API) InitWebhook() { l4g.Debug(utils.T("api.webhook.init.debug")) - BaseRoutes.Hooks.Handle("/incoming/create", ApiUserRequired(createIncomingHook)).Methods("POST") - BaseRoutes.Hooks.Handle("/incoming/update", ApiUserRequired(updateIncomingHook)).Methods("POST") - BaseRoutes.Hooks.Handle("/incoming/delete", ApiUserRequired(deleteIncomingHook)).Methods("POST") - BaseRoutes.Hooks.Handle("/incoming/list", ApiUserRequired(getIncomingHooks)).Methods("GET") + api.BaseRoutes.Hooks.Handle("/incoming/create", api.ApiUserRequired(createIncomingHook)).Methods("POST") + api.BaseRoutes.Hooks.Handle("/incoming/update", api.ApiUserRequired(updateIncomingHook)).Methods("POST") + api.BaseRoutes.Hooks.Handle("/incoming/delete", api.ApiUserRequired(deleteIncomingHook)).Methods("POST") + api.BaseRoutes.Hooks.Handle("/incoming/list", api.ApiUserRequired(getIncomingHooks)).Methods("GET") - BaseRoutes.Hooks.Handle("/outgoing/create", ApiUserRequired(createOutgoingHook)).Methods("POST") - BaseRoutes.Hooks.Handle("/outgoing/update", ApiUserRequired(updateOutgoingHook)).Methods("POST") - BaseRoutes.Hooks.Handle("/outgoing/regen_token", ApiUserRequired(regenOutgoingHookToken)).Methods("POST") - BaseRoutes.Hooks.Handle("/outgoing/delete", ApiUserRequired(deleteOutgoingHook)).Methods("POST") - BaseRoutes.Hooks.Handle("/outgoing/list", ApiUserRequired(getOutgoingHooks)).Methods("GET") + api.BaseRoutes.Hooks.Handle("/outgoing/create", api.ApiUserRequired(createOutgoingHook)).Methods("POST") + api.BaseRoutes.Hooks.Handle("/outgoing/update", api.ApiUserRequired(updateOutgoingHook)).Methods("POST") + api.BaseRoutes.Hooks.Handle("/outgoing/regen_token", api.ApiUserRequired(regenOutgoingHookToken)).Methods("POST") + api.BaseRoutes.Hooks.Handle("/outgoing/delete", api.ApiUserRequired(deleteOutgoingHook)).Methods("POST") + api.BaseRoutes.Hooks.Handle("/outgoing/list", api.ApiUserRequired(getOutgoingHooks)).Methods("GET") } func createIncomingHook(c *Context, w http.ResponseWriter, r *http.Request) { diff --git a/api/webrtc.go b/api/webrtc.go index 31cfb1def..96ff67e56 100644 --- a/api/webrtc.go +++ b/api/webrtc.go @@ -11,10 +11,10 @@ import ( "github.com/mattermost/mattermost-server/utils" ) -func InitWebrtc() { +func (api *API) InitWebrtc() { l4g.Debug(utils.T("api.webrtc.init.debug")) - BaseRoutes.Webrtc.Handle("/token", ApiUserRequired(webrtcToken)).Methods("POST") + api.BaseRoutes.Webrtc.Handle("/token", api.ApiUserRequired(webrtcToken)).Methods("POST") } func webrtcToken(c *Context, w http.ResponseWriter, r *http.Request) { diff --git a/api/websocket.go b/api/websocket.go index 4b3a9d53b..6de5741f3 100644 --- a/api/websocket.go +++ b/api/websocket.go @@ -13,9 +13,9 @@ import ( "github.com/mattermost/mattermost-server/utils" ) -func InitWebSocket() { +func (api *API) InitWebSocket() { l4g.Debug(utils.T("api.web_socket.init.debug")) - BaseRoutes.Users.Handle("/websocket", ApiAppHandlerTrustRequester(connect)).Methods("GET") + api.BaseRoutes.Users.Handle("/websocket", api.ApiAppHandlerTrustRequester(connect)).Methods("GET") } func connect(c *Context, w http.ResponseWriter, r *http.Request) { diff --git a/api4/api.go b/api4/api.go index 16c816528..9df051456 100644 --- a/api4/api.go +++ b/api4/api.go @@ -102,7 +102,10 @@ type Routes struct { Webrtc *mux.Router // 'api/v4/webrtc' } -var BaseRoutes *Routes +type API struct { + App *app.App + BaseRoutes *Routes +} func NewRouter() *mux.Router { ret := mux.NewRouter() @@ -110,108 +113,112 @@ func NewRouter() *mux.Router { return ret } -func InitApi(root *mux.Router, full bool) { - BaseRoutes = &Routes{} - BaseRoutes.Root = root - BaseRoutes.ApiRoot = root.PathPrefix(model.API_URL_SUFFIX).Subrouter() - - BaseRoutes.Users = BaseRoutes.ApiRoot.PathPrefix("/users").Subrouter() - BaseRoutes.User = BaseRoutes.ApiRoot.PathPrefix("/users/{user_id:[A-Za-z0-9]+}").Subrouter() - BaseRoutes.UserByUsername = BaseRoutes.Users.PathPrefix("/username/{username:[A-Za-z0-9\\_\\-\\.]+}").Subrouter() - BaseRoutes.UserByEmail = BaseRoutes.Users.PathPrefix("/email/{email}").Subrouter() - - BaseRoutes.Teams = BaseRoutes.ApiRoot.PathPrefix("/teams").Subrouter() - BaseRoutes.TeamsForUser = BaseRoutes.User.PathPrefix("/teams").Subrouter() - BaseRoutes.Team = BaseRoutes.Teams.PathPrefix("/{team_id:[A-Za-z0-9]+}").Subrouter() - BaseRoutes.TeamForUser = BaseRoutes.TeamsForUser.PathPrefix("/{team_id:[A-Za-z0-9]+}").Subrouter() - BaseRoutes.TeamByName = BaseRoutes.Teams.PathPrefix("/name/{team_name:[A-Za-z0-9_-]+}").Subrouter() - BaseRoutes.TeamMembers = BaseRoutes.Team.PathPrefix("/members").Subrouter() - BaseRoutes.TeamMember = BaseRoutes.TeamMembers.PathPrefix("/{user_id:[A-Za-z0-9]+}").Subrouter() - BaseRoutes.TeamMembersForUser = BaseRoutes.User.PathPrefix("/teams/members").Subrouter() - - BaseRoutes.Channels = BaseRoutes.ApiRoot.PathPrefix("/channels").Subrouter() - BaseRoutes.Channel = BaseRoutes.Channels.PathPrefix("/{channel_id:[A-Za-z0-9]+}").Subrouter() - BaseRoutes.ChannelForUser = BaseRoutes.User.PathPrefix("/channels/{channel_id:[A-Za-z0-9]+}").Subrouter() - BaseRoutes.ChannelByName = BaseRoutes.Team.PathPrefix("/channels/name/{channel_name:[A-Za-z0-9_-]+}").Subrouter() - BaseRoutes.ChannelByNameForTeamName = BaseRoutes.TeamByName.PathPrefix("/channels/name/{channel_name:[A-Za-z0-9_-]+}").Subrouter() - BaseRoutes.ChannelsForTeam = BaseRoutes.Team.PathPrefix("/channels").Subrouter() - BaseRoutes.ChannelMembers = BaseRoutes.Channel.PathPrefix("/members").Subrouter() - BaseRoutes.ChannelMember = BaseRoutes.ChannelMembers.PathPrefix("/{user_id:[A-Za-z0-9]+}").Subrouter() - BaseRoutes.ChannelMembersForUser = BaseRoutes.User.PathPrefix("/teams/{team_id:[A-Za-z0-9]+}/channels/members").Subrouter() - - BaseRoutes.Posts = BaseRoutes.ApiRoot.PathPrefix("/posts").Subrouter() - BaseRoutes.Post = BaseRoutes.Posts.PathPrefix("/{post_id:[A-Za-z0-9]+}").Subrouter() - BaseRoutes.PostsForChannel = BaseRoutes.Channel.PathPrefix("/posts").Subrouter() - BaseRoutes.PostsForUser = BaseRoutes.User.PathPrefix("/posts").Subrouter() - BaseRoutes.PostForUser = BaseRoutes.PostsForUser.PathPrefix("/{post_id:[A-Za-z0-9]+}").Subrouter() - - BaseRoutes.Files = BaseRoutes.ApiRoot.PathPrefix("/files").Subrouter() - BaseRoutes.File = BaseRoutes.Files.PathPrefix("/{file_id:[A-Za-z0-9]+}").Subrouter() - BaseRoutes.PublicFile = BaseRoutes.Root.PathPrefix("/files/{file_id:[A-Za-z0-9]+}/public").Subrouter() - - BaseRoutes.Plugins = BaseRoutes.ApiRoot.PathPrefix("/plugins").Subrouter() - BaseRoutes.Plugin = BaseRoutes.Plugins.PathPrefix("/{plugin_id:[A-Za-z0-9\\_\\-\\.]+}").Subrouter() - - BaseRoutes.Commands = BaseRoutes.ApiRoot.PathPrefix("/commands").Subrouter() - BaseRoutes.Command = BaseRoutes.Commands.PathPrefix("/{command_id:[A-Za-z0-9]+}").Subrouter() - - BaseRoutes.Hooks = BaseRoutes.ApiRoot.PathPrefix("/hooks").Subrouter() - BaseRoutes.IncomingHooks = BaseRoutes.Hooks.PathPrefix("/incoming").Subrouter() - BaseRoutes.IncomingHook = BaseRoutes.IncomingHooks.PathPrefix("/{hook_id:[A-Za-z0-9]+}").Subrouter() - BaseRoutes.OutgoingHooks = BaseRoutes.Hooks.PathPrefix("/outgoing").Subrouter() - BaseRoutes.OutgoingHook = BaseRoutes.OutgoingHooks.PathPrefix("/{hook_id:[A-Za-z0-9]+}").Subrouter() - - BaseRoutes.SAML = BaseRoutes.ApiRoot.PathPrefix("/saml").Subrouter() - - BaseRoutes.OAuth = BaseRoutes.ApiRoot.PathPrefix("/oauth").Subrouter() - BaseRoutes.OAuthApps = BaseRoutes.OAuth.PathPrefix("/apps").Subrouter() - BaseRoutes.OAuthApp = BaseRoutes.OAuthApps.PathPrefix("/{app_id:[A-Za-z0-9]+}").Subrouter() - - BaseRoutes.Compliance = BaseRoutes.ApiRoot.PathPrefix("/compliance").Subrouter() - BaseRoutes.Cluster = BaseRoutes.ApiRoot.PathPrefix("/cluster").Subrouter() - BaseRoutes.LDAP = BaseRoutes.ApiRoot.PathPrefix("/ldap").Subrouter() - BaseRoutes.Brand = BaseRoutes.ApiRoot.PathPrefix("/brand").Subrouter() - BaseRoutes.System = BaseRoutes.ApiRoot.PathPrefix("/system").Subrouter() - BaseRoutes.Preferences = BaseRoutes.User.PathPrefix("/preferences").Subrouter() - BaseRoutes.License = BaseRoutes.ApiRoot.PathPrefix("/license").Subrouter() - BaseRoutes.Public = BaseRoutes.ApiRoot.PathPrefix("/public").Subrouter() - BaseRoutes.Reactions = BaseRoutes.ApiRoot.PathPrefix("/reactions").Subrouter() - BaseRoutes.Jobs = BaseRoutes.ApiRoot.PathPrefix("/jobs").Subrouter() - BaseRoutes.Elasticsearch = BaseRoutes.ApiRoot.PathPrefix("/elasticsearch").Subrouter() - - BaseRoutes.Emojis = BaseRoutes.ApiRoot.PathPrefix("/emoji").Subrouter() - BaseRoutes.Emoji = BaseRoutes.Emojis.PathPrefix("/{emoji_id:[A-Za-z0-9]+}").Subrouter() - - BaseRoutes.ReactionByNameForPostForUser = BaseRoutes.PostForUser.PathPrefix("/reactions/{emoji_name:[A-Za-z0-9\\_\\-\\+]+}").Subrouter() - - BaseRoutes.Webrtc = BaseRoutes.ApiRoot.PathPrefix("/webrtc").Subrouter() - - BaseRoutes.OpenGraph = BaseRoutes.ApiRoot.PathPrefix("/opengraph").Subrouter() - - InitUser() - InitTeam() - InitChannel() - InitPost() - InitFile() - InitSystem() - InitWebhook() - InitPreference() - InitSaml() - InitCompliance() - InitCluster() - InitLdap() - InitElasticsearch() - InitBrand() - InitJob() - InitCommand() - InitStatus() - InitWebSocket() - InitEmoji() - InitOAuth() - InitReaction() - InitWebrtc() - InitOpenGraph() - InitPlugin() +func Init(a *app.App, root *mux.Router, full bool) *API { + api := &API{ + App: a, + BaseRoutes: &Routes{}, + } + + api.BaseRoutes.Root = root + api.BaseRoutes.ApiRoot = root.PathPrefix(model.API_URL_SUFFIX).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.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() + 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.TeamMembersForUser = api.BaseRoutes.User.PathPrefix("/teams/members").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() + api.BaseRoutes.ChannelByNameForTeamName = api.BaseRoutes.TeamByName.PathPrefix("/channels/name/{channel_name:[A-Za-z0-9_-]+}").Subrouter() + api.BaseRoutes.ChannelsForTeam = api.BaseRoutes.Team.PathPrefix("/channels").Subrouter() + api.BaseRoutes.ChannelMembers = api.BaseRoutes.Channel.PathPrefix("/members").Subrouter() + 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.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.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.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.Command = api.BaseRoutes.Commands.PathPrefix("/{command_id:[A-Za-z0-9]+}").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.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.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.Emojis = api.BaseRoutes.ApiRoot.PathPrefix("/emoji").Subrouter() + api.BaseRoutes.Emoji = api.BaseRoutes.Emojis.PathPrefix("/{emoji_id:[A-Za-z0-9]+}").Subrouter() + + api.BaseRoutes.ReactionByNameForPostForUser = api.BaseRoutes.PostForUser.PathPrefix("/reactions/{emoji_name:[A-Za-z0-9\\_\\-\\+]+}").Subrouter() + + api.BaseRoutes.Webrtc = api.BaseRoutes.ApiRoot.PathPrefix("/webrtc").Subrouter() + + api.BaseRoutes.OpenGraph = api.BaseRoutes.ApiRoot.PathPrefix("/opengraph").Subrouter() + + api.InitUser() + api.InitTeam() + api.InitChannel() + api.InitPost() + api.InitFile() + api.InitSystem() + api.InitWebhook() + api.InitPreference() + api.InitSaml() + api.InitCompliance() + api.InitCluster() + api.InitLdap() + api.InitElasticsearch() + api.InitBrand() + api.InitJob() + api.InitCommand() + api.InitStatus() + api.InitWebSocket() + api.InitEmoji() + api.InitOAuth() + api.InitReaction() + api.InitWebrtc() + api.InitOpenGraph() + api.InitPlugin() root.Handle("/api/v4/{anything:.*}", http.HandlerFunc(Handle404)) @@ -221,26 +228,8 @@ func InitApi(root *mux.Router, full bool) { app.InitEmailBatching() } -} - -func HandleEtag(etag string, routeName string, w http.ResponseWriter, r *http.Request) bool { - metrics := app.Global().Metrics - if et := r.Header.Get(model.HEADER_ETAG_CLIENT); len(etag) > 0 { - if et == etag { - w.Header().Set(model.HEADER_ETAG_SERVER, etag) - w.WriteHeader(http.StatusNotModified) - if metrics != nil { - metrics.IncrementEtagHitCounter(routeName) - } - return true - } - } - - if metrics != nil { - metrics.IncrementEtagMissCounter(routeName) - } - return false + return api } func Handle404(w http.ResponseWriter, r *http.Request) { diff --git a/api4/apitestlib.go b/api4/apitestlib.go index 9538eb99c..7b5230014 100644 --- a/api4/apitestlib.go +++ b/api4/apitestlib.go @@ -63,7 +63,7 @@ func setupTestHelper(enterprise bool) *TestHelper { th.App.Srv.Router = NewRouter() wsapi.InitRouter() th.App.StartServer() - InitApi(th.App.Srv.Router, true) + Init(th.App, th.App.Srv.Router, true) wsapi.InitApi() utils.EnableDebugLogForTest() th.App.Srv.Store.MarkSystemRanUnitTests() diff --git a/api4/brand.go b/api4/brand.go index ef4ea25b5..23bfc557d 100644 --- a/api4/brand.go +++ b/api4/brand.go @@ -12,11 +12,11 @@ import ( "github.com/mattermost/mattermost-server/utils" ) -func InitBrand() { +func (api *API) InitBrand() { l4g.Debug(utils.T("api.brand.init.debug")) - BaseRoutes.Brand.Handle("/image", ApiHandlerTrustRequester(getBrandImage)).Methods("GET") - BaseRoutes.Brand.Handle("/image", ApiSessionRequired(uploadBrandImage)).Methods("POST") + api.BaseRoutes.Brand.Handle("/image", api.ApiHandlerTrustRequester(getBrandImage)).Methods("GET") + api.BaseRoutes.Brand.Handle("/image", api.ApiSessionRequired(uploadBrandImage)).Methods("POST") } func getBrandImage(c *Context, w http.ResponseWriter, r *http.Request) { diff --git a/api4/channel.go b/api4/channel.go index 8f3f46b8c..9eaa6ec8a 100644 --- a/api4/channel.go +++ b/api4/channel.go @@ -12,41 +12,41 @@ import ( "github.com/mattermost/mattermost-server/utils" ) -func InitChannel() { +func (api *API) InitChannel() { l4g.Debug(utils.T("api.channel.init.debug")) - BaseRoutes.Channels.Handle("", ApiSessionRequired(createChannel)).Methods("POST") - BaseRoutes.Channels.Handle("/direct", ApiSessionRequired(createDirectChannel)).Methods("POST") - BaseRoutes.Channels.Handle("/group", ApiSessionRequired(createGroupChannel)).Methods("POST") - BaseRoutes.Channels.Handle("/members/{user_id:[A-Za-z0-9]+}/view", ApiSessionRequired(viewChannel)).Methods("POST") - - BaseRoutes.ChannelsForTeam.Handle("", ApiSessionRequired(getPublicChannelsForTeam)).Methods("GET") - BaseRoutes.ChannelsForTeam.Handle("/deleted", ApiSessionRequired(getDeletedChannelsForTeam)).Methods("GET") - BaseRoutes.ChannelsForTeam.Handle("/ids", ApiSessionRequired(getPublicChannelsByIdsForTeam)).Methods("POST") - BaseRoutes.ChannelsForTeam.Handle("/search", ApiSessionRequired(searchChannelsForTeam)).Methods("POST") - BaseRoutes.User.Handle("/teams/{team_id:[A-Za-z0-9]+}/channels", ApiSessionRequired(getChannelsForTeamForUser)).Methods("GET") - - BaseRoutes.Channel.Handle("", ApiSessionRequired(getChannel)).Methods("GET") - BaseRoutes.Channel.Handle("", ApiSessionRequired(updateChannel)).Methods("PUT") - BaseRoutes.Channel.Handle("/patch", ApiSessionRequired(patchChannel)).Methods("PUT") - BaseRoutes.Channel.Handle("/restore", ApiSessionRequired(restoreChannel)).Methods("POST") - BaseRoutes.Channel.Handle("", ApiSessionRequired(deleteChannel)).Methods("DELETE") - BaseRoutes.Channel.Handle("/stats", ApiSessionRequired(getChannelStats)).Methods("GET") - BaseRoutes.Channel.Handle("/pinned", ApiSessionRequired(getPinnedPosts)).Methods("GET") - - BaseRoutes.ChannelForUser.Handle("/unread", ApiSessionRequired(getChannelUnread)).Methods("GET") - - BaseRoutes.ChannelByName.Handle("", ApiSessionRequired(getChannelByName)).Methods("GET") - BaseRoutes.ChannelByNameForTeamName.Handle("", ApiSessionRequired(getChannelByNameForTeamName)).Methods("GET") - - BaseRoutes.ChannelMembers.Handle("", ApiSessionRequired(getChannelMembers)).Methods("GET") - BaseRoutes.ChannelMembers.Handle("/ids", ApiSessionRequired(getChannelMembersByIds)).Methods("POST") - BaseRoutes.ChannelMembers.Handle("", ApiSessionRequired(addChannelMember)).Methods("POST") - BaseRoutes.ChannelMembersForUser.Handle("", ApiSessionRequired(getChannelMembersForUser)).Methods("GET") - BaseRoutes.ChannelMember.Handle("", ApiSessionRequired(getChannelMember)).Methods("GET") - BaseRoutes.ChannelMember.Handle("", ApiSessionRequired(removeChannelMember)).Methods("DELETE") - BaseRoutes.ChannelMember.Handle("/roles", ApiSessionRequired(updateChannelMemberRoles)).Methods("PUT") - BaseRoutes.ChannelMember.Handle("/notify_props", ApiSessionRequired(updateChannelMemberNotifyProps)).Methods("PUT") + api.BaseRoutes.Channels.Handle("", api.ApiSessionRequired(createChannel)).Methods("POST") + api.BaseRoutes.Channels.Handle("/direct", api.ApiSessionRequired(createDirectChannel)).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.ChannelsForTeam.Handle("", api.ApiSessionRequired(getPublicChannelsForTeam)).Methods("GET") + api.BaseRoutes.ChannelsForTeam.Handle("/deleted", api.ApiSessionRequired(getDeletedChannelsForTeam)).Methods("GET") + api.BaseRoutes.ChannelsForTeam.Handle("/ids", api.ApiSessionRequired(getPublicChannelsByIdsForTeam)).Methods("POST") + api.BaseRoutes.ChannelsForTeam.Handle("/search", api.ApiSessionRequired(searchChannelsForTeam)).Methods("POST") + api.BaseRoutes.User.Handle("/teams/{team_id:[A-Za-z0-9]+}/channels", api.ApiSessionRequired(getChannelsForTeamForUser)).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("/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.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.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("/notify_props", api.ApiSessionRequired(updateChannelMemberNotifyProps)).Methods("PUT") } func createChannel(c *Context, w http.ResponseWriter, r *http.Request) { @@ -387,7 +387,7 @@ func getPinnedPosts(c *Context, w http.ResponseWriter, r *http.Request) { if posts, err := c.App.GetPinnedPosts(c.Params.ChannelId); err != nil { c.Err = err return - } else if HandleEtag(posts.Etag(), "Get Pinned Posts", w, r) { + } else if c.HandleEtag(posts.Etag(), "Get Pinned Posts", w, r) { return } else { w.Header().Set(model.HEADER_ETAG_SERVER, posts.Etag()) @@ -486,7 +486,7 @@ func getChannelsForTeamForUser(c *Context, w http.ResponseWriter, r *http.Reques if channels, err := c.App.GetChannelsForUser(c.Params.TeamId, c.Params.UserId); err != nil { c.Err = err return - } else if HandleEtag(channels.Etag(), "Get Channels", w, r) { + } else if c.HandleEtag(channels.Etag(), "Get Channels", w, r) { return } else { w.Header().Set(model.HEADER_ETAG_SERVER, channels.Etag()) diff --git a/api4/cluster.go b/api4/cluster.go index c802d2a7e..f79ef28a8 100644 --- a/api4/cluster.go +++ b/api4/cluster.go @@ -12,10 +12,10 @@ import ( "github.com/mattermost/mattermost-server/utils" ) -func InitCluster() { +func (api *API) InitCluster() { l4g.Debug(utils.T("api.cluster.init.debug")) - BaseRoutes.Cluster.Handle("/status", 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 ba15b0ff3..64426193d 100644 --- a/api4/command.go +++ b/api4/command.go @@ -15,21 +15,21 @@ import ( "github.com/mattermost/mattermost-server/utils" ) -func InitCommand() { +func (api *API) InitCommand() { l4g.Debug(utils.T("api.command.init.debug")) - BaseRoutes.Commands.Handle("", ApiSessionRequired(createCommand)).Methods("POST") - BaseRoutes.Commands.Handle("", ApiSessionRequired(listCommands)).Methods("GET") - BaseRoutes.Commands.Handle("/execute", 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") - BaseRoutes.Command.Handle("", ApiSessionRequired(updateCommand)).Methods("PUT") - BaseRoutes.Command.Handle("", ApiSessionRequired(deleteCommand)).Methods("DELETE") + api.BaseRoutes.Command.Handle("", api.ApiSessionRequired(updateCommand)).Methods("PUT") + api.BaseRoutes.Command.Handle("", api.ApiSessionRequired(deleteCommand)).Methods("DELETE") - BaseRoutes.Team.Handle("/commands/autocomplete", ApiSessionRequired(listAutocompleteCommands)).Methods("GET") - BaseRoutes.Command.Handle("/regen_token", ApiSessionRequired(regenCommandToken)).Methods("PUT") + api.BaseRoutes.Team.Handle("/commands/autocomplete", api.ApiSessionRequired(listAutocompleteCommands)).Methods("GET") + api.BaseRoutes.Command.Handle("/regen_token", api.ApiSessionRequired(regenCommandToken)).Methods("PUT") - BaseRoutes.Teams.Handle("/command_test", ApiHandler(testCommand)).Methods("POST") - BaseRoutes.Teams.Handle("/command_test", ApiHandler(testCommand)).Methods("GET") + api.BaseRoutes.Teams.Handle("/command_test", api.ApiHandler(testCommand)).Methods("POST") + api.BaseRoutes.Teams.Handle("/command_test", api.ApiHandler(testCommand)).Methods("GET") } func createCommand(c *Context, w http.ResponseWriter, r *http.Request) { diff --git a/api4/compliance.go b/api4/compliance.go index fe93834e3..7d0708efe 100644 --- a/api4/compliance.go +++ b/api4/compliance.go @@ -14,13 +14,13 @@ import ( "github.com/mssola/user_agent" ) -func InitCompliance() { +func (api *API) InitCompliance() { l4g.Debug(utils.T("api.compliance.init.debug")) - BaseRoutes.Compliance.Handle("/reports", ApiSessionRequired(createComplianceReport)).Methods("POST") - BaseRoutes.Compliance.Handle("/reports", ApiSessionRequired(getComplianceReports)).Methods("GET") - BaseRoutes.Compliance.Handle("/reports/{report_id:[A-Za-z0-9]+}", ApiSessionRequired(getComplianceReport)).Methods("GET") - BaseRoutes.Compliance.Handle("/reports/{report_id:[A-Za-z0-9]+}/download", 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/context.go b/api4/context.go index cd32bc7b1..c526f38bb 100644 --- a/api4/context.go +++ b/api4/context.go @@ -30,8 +30,9 @@ type Context struct { siteURLHeader string } -func ApiHandler(h func(*Context, http.ResponseWriter, *http.Request)) http.Handler { +func (api *API) ApiHandler(h func(*Context, http.ResponseWriter, *http.Request)) http.Handler { return &handler{ + app: api.App, handleFunc: h, requireSession: false, trustRequester: false, @@ -39,8 +40,9 @@ func ApiHandler(h func(*Context, http.ResponseWriter, *http.Request)) http.Handl } } -func ApiSessionRequired(h func(*Context, http.ResponseWriter, *http.Request)) http.Handler { +func (api *API) ApiSessionRequired(h func(*Context, http.ResponseWriter, *http.Request)) http.Handler { return &handler{ + app: api.App, handleFunc: h, requireSession: true, trustRequester: false, @@ -48,8 +50,9 @@ func ApiSessionRequired(h func(*Context, http.ResponseWriter, *http.Request)) ht } } -func ApiSessionRequiredMfa(h func(*Context, http.ResponseWriter, *http.Request)) http.Handler { +func (api *API) ApiSessionRequiredMfa(h func(*Context, http.ResponseWriter, *http.Request)) http.Handler { return &handler{ + app: api.App, handleFunc: h, requireSession: true, trustRequester: false, @@ -57,8 +60,9 @@ func ApiSessionRequiredMfa(h func(*Context, http.ResponseWriter, *http.Request)) } } -func ApiHandlerTrustRequester(h func(*Context, http.ResponseWriter, *http.Request)) http.Handler { +func (api *API) ApiHandlerTrustRequester(h func(*Context, http.ResponseWriter, *http.Request)) http.Handler { return &handler{ + app: api.App, handleFunc: h, requireSession: false, trustRequester: true, @@ -66,8 +70,9 @@ func ApiHandlerTrustRequester(h func(*Context, http.ResponseWriter, *http.Reques } } -func ApiSessionRequiredTrustRequester(h func(*Context, http.ResponseWriter, *http.Request)) http.Handler { +func (api *API) ApiSessionRequiredTrustRequester(h func(*Context, http.ResponseWriter, *http.Request)) http.Handler { return &handler{ + app: api.App, handleFunc: h, requireSession: true, trustRequester: true, @@ -76,6 +81,7 @@ func ApiSessionRequiredTrustRequester(h func(*Context, http.ResponseWriter, *htt } type handler struct { + app *app.App handleFunc func(*Context, http.ResponseWriter, *http.Request) requireSession bool trustRequester bool @@ -87,7 +93,7 @@ func (h handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { l4g.Debug("%v - %v", r.Method, r.URL.Path) c := &Context{} - c.App = app.Global() + c.App = h.app c.T, _ = utils.GetTranslationsAndLocale(w, r) c.RequestId = model.NewId() c.IpAddress = utils.GetIpAddress(r) @@ -139,7 +145,7 @@ func (h handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { } if len(token) != 0 { - session, err := app.Global().GetSession(token) + session, err := c.App.GetSession(token) if err != nil { l4g.Error(utils.T("api.context.invalid_session.error"), err.Error()) @@ -200,7 +206,7 @@ func (h handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { func (c *Context) LogAudit(extraInfo string) { audit := &model.Audit{UserId: c.Session.UserId, IpAddress: c.IpAddress, Action: c.Path, ExtraInfo: extraInfo, SessionId: c.Session.Id} - if r := <-app.Global().Srv.Store.Audit().Save(audit); r.Err != nil { + if r := <-c.App.Srv.Store.Audit().Save(audit); r.Err != nil { c.LogError(r.Err) } } @@ -212,7 +218,7 @@ func (c *Context) LogAuditWithUserId(userId, extraInfo string) { } audit := &model.Audit{UserId: userId, IpAddress: c.IpAddress, Action: c.Path, ExtraInfo: extraInfo, SessionId: c.Session.Id} - if r := <-app.Global().Srv.Store.Audit().Save(audit); r.Err != nil { + if r := <-c.App.Srv.Store.Audit().Save(audit); r.Err != nil { c.LogError(r.Err) } } @@ -260,7 +266,7 @@ func (c *Context) MfaRequired() { return } - if user, err := app.Global().GetUser(c.Session.UserId); err != nil { + if user, err := c.App.GetUser(c.Session.UserId); err != nil { c.Err = model.NewAppError("", "api.context.session_expired.app_error", nil, "MfaRequired", http.StatusUnauthorized) return } else { @@ -303,6 +309,26 @@ func (c *Context) SetInvalidUrlParam(parameter string) { c.Err = NewInvalidUrlParamError(parameter) } +func (c *Context) HandleEtag(etag string, routeName string, w http.ResponseWriter, r *http.Request) bool { + metrics := c.App.Metrics + if et := r.Header.Get(model.HEADER_ETAG_CLIENT); len(etag) > 0 { + if et == etag { + w.Header().Set(model.HEADER_ETAG_SERVER, etag) + w.WriteHeader(http.StatusNotModified) + if metrics != nil { + metrics.IncrementEtagHitCounter(routeName) + } + return true + } + } + + if metrics != nil { + metrics.IncrementEtagMissCounter(routeName) + } + + return false +} + 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 diff --git a/api4/elasticsearch.go b/api4/elasticsearch.go index cfa8292b6..2a378f54e 100644 --- a/api4/elasticsearch.go +++ b/api4/elasticsearch.go @@ -12,11 +12,11 @@ import ( "github.com/mattermost/mattermost-server/utils" ) -func InitElasticsearch() { +func (api *API) InitElasticsearch() { l4g.Debug(utils.T("api.elasticsearch.init.debug")) - BaseRoutes.Elasticsearch.Handle("/test", ApiSessionRequired(testElasticsearch)).Methods("POST") - BaseRoutes.Elasticsearch.Handle("/purge_indexes", 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 80c73c9e6..d014250d6 100644 --- a/api4/emoji.go +++ b/api4/emoji.go @@ -15,14 +15,14 @@ import ( "github.com/mattermost/mattermost-server/utils" ) -func InitEmoji() { +func (api *API) InitEmoji() { l4g.Debug(utils.T("api.emoji.init.debug")) - BaseRoutes.Emojis.Handle("", ApiSessionRequired(createEmoji)).Methods("POST") - BaseRoutes.Emojis.Handle("", ApiSessionRequired(getEmojiList)).Methods("GET") - BaseRoutes.Emoji.Handle("", ApiSessionRequired(deleteEmoji)).Methods("DELETE") - BaseRoutes.Emoji.Handle("", ApiSessionRequired(getEmoji)).Methods("GET") - BaseRoutes.Emoji.Handle("/image", ApiSessionRequiredTrustRequester(getEmojiImage)).Methods("GET") + api.BaseRoutes.Emojis.Handle("", api.ApiSessionRequired(createEmoji)).Methods("POST") + api.BaseRoutes.Emojis.Handle("", api.ApiSessionRequired(getEmojiList)).Methods("GET") + api.BaseRoutes.Emoji.Handle("", api.ApiSessionRequired(deleteEmoji)).Methods("DELETE") + api.BaseRoutes.Emoji.Handle("", api.ApiSessionRequired(getEmoji)).Methods("GET") + api.BaseRoutes.Emoji.Handle("/image", api.ApiSessionRequiredTrustRequester(getEmojiImage)).Methods("GET") } func createEmoji(c *Context, w http.ResponseWriter, r *http.Request) { diff --git a/api4/file.go b/api4/file.go index 107a41122..2c0b85ce7 100644 --- a/api4/file.go +++ b/api4/file.go @@ -43,17 +43,17 @@ var MEDIA_CONTENT_TYPES = [...]string{ "audio/wav", } -func InitFile() { +func (api *API) InitFile() { l4g.Debug(utils.T("api.file.init.debug")) - BaseRoutes.Files.Handle("", ApiSessionRequired(uploadFile)).Methods("POST") - BaseRoutes.File.Handle("", ApiSessionRequiredTrustRequester(getFile)).Methods("GET") - BaseRoutes.File.Handle("/thumbnail", ApiSessionRequiredTrustRequester(getFileThumbnail)).Methods("GET") - BaseRoutes.File.Handle("/link", ApiSessionRequired(getFileLink)).Methods("GET") - BaseRoutes.File.Handle("/preview", ApiSessionRequiredTrustRequester(getFilePreview)).Methods("GET") - BaseRoutes.File.Handle("/info", ApiSessionRequired(getFileInfo)).Methods("GET") + api.BaseRoutes.Files.Handle("", api.ApiSessionRequired(uploadFile)).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") - BaseRoutes.PublicFile.Handle("", ApiHandler(getPublicFile)).Methods("GET") + api.BaseRoutes.PublicFile.Handle("", api.ApiHandler(getPublicFile)).Methods("GET") } diff --git a/api4/job.go b/api4/job.go index 42cbdd3f7..57c604361 100644 --- a/api4/job.go +++ b/api4/job.go @@ -11,14 +11,14 @@ import ( "github.com/mattermost/mattermost-server/model" ) -func InitJob() { +func (api *API) InitJob() { l4g.Info("Initializing job API routes") - BaseRoutes.Jobs.Handle("", ApiSessionRequired(getJobs)).Methods("GET") - BaseRoutes.Jobs.Handle("", ApiSessionRequired(createJob)).Methods("POST") - BaseRoutes.Jobs.Handle("/{job_id:[A-Za-z0-9]+}", ApiSessionRequired(getJob)).Methods("GET") - BaseRoutes.Jobs.Handle("/{job_id:[A-Za-z0-9]+}/cancel", ApiSessionRequired(cancelJob)).Methods("POST") - BaseRoutes.Jobs.Handle("/type/{job_type:[A-Za-z0-9_-]+}", 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]+}/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/ldap.go b/api4/ldap.go index 6ed581783..3c5eb5ede 100644 --- a/api4/ldap.go +++ b/api4/ldap.go @@ -12,11 +12,11 @@ import ( "github.com/mattermost/mattermost-server/utils" ) -func InitLdap() { +func (api *API) InitLdap() { l4g.Debug(utils.T("api.ldap.init.debug")) - BaseRoutes.LDAP.Handle("/sync", ApiSessionRequired(syncLdap)).Methods("POST") - BaseRoutes.LDAP.Handle("/test", ApiSessionRequired(testLdap)).Methods("POST") + api.BaseRoutes.LDAP.Handle("/sync", api.ApiSessionRequired(syncLdap)).Methods("POST") + api.BaseRoutes.LDAP.Handle("/test", api.ApiSessionRequired(testLdap)).Methods("POST") } func syncLdap(c *Context, w http.ResponseWriter, r *http.Request) { diff --git a/api4/oauth.go b/api4/oauth.go index 10972fe07..c60f240f6 100644 --- a/api4/oauth.go +++ b/api4/oauth.go @@ -14,35 +14,35 @@ import ( "github.com/mattermost/mattermost-server/utils" ) -func InitOAuth() { +func (api *API) InitOAuth() { l4g.Debug(utils.T("api.oauth.init.debug")) - BaseRoutes.OAuthApps.Handle("", ApiSessionRequired(createOAuthApp)).Methods("POST") - BaseRoutes.OAuthApp.Handle("", ApiSessionRequired(updateOAuthApp)).Methods("PUT") - BaseRoutes.OAuthApps.Handle("", ApiSessionRequired(getOAuthApps)).Methods("GET") - BaseRoutes.OAuthApp.Handle("", ApiSessionRequired(getOAuthApp)).Methods("GET") - BaseRoutes.OAuthApp.Handle("/info", ApiSessionRequired(getOAuthAppInfo)).Methods("GET") - BaseRoutes.OAuthApp.Handle("", ApiSessionRequired(deleteOAuthApp)).Methods("DELETE") - BaseRoutes.OAuthApp.Handle("/regen_secret", 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") - BaseRoutes.User.Handle("/oauth/apps/authorized", ApiSessionRequired(getAuthorizedOAuthApps)).Methods("GET") + api.BaseRoutes.User.Handle("/oauth/apps/authorized", api.ApiSessionRequired(getAuthorizedOAuthApps)).Methods("GET") // API version independent OAuth 2.0 as a service provider endpoints - BaseRoutes.Root.Handle("/oauth/authorize", ApiHandlerTrustRequester(authorizeOAuthPage)).Methods("GET") - BaseRoutes.Root.Handle("/oauth/authorize", ApiSessionRequired(authorizeOAuthApp)).Methods("POST") - BaseRoutes.Root.Handle("/oauth/deauthorize", ApiSessionRequired(deauthorizeOAuthApp)).Methods("POST") - BaseRoutes.Root.Handle("/oauth/access_token", ApiHandlerTrustRequester(getAccessToken)).Methods("POST") + api.BaseRoutes.Root.Handle("/oauth/authorize", api.ApiHandlerTrustRequester(authorizeOAuthPage)).Methods("GET") + api.BaseRoutes.Root.Handle("/oauth/authorize", api.ApiSessionRequired(authorizeOAuthApp)).Methods("POST") + api.BaseRoutes.Root.Handle("/oauth/deauthorize", api.ApiSessionRequired(deauthorizeOAuthApp)).Methods("POST") + api.BaseRoutes.Root.Handle("/oauth/access_token", api.ApiHandlerTrustRequester(getAccessToken)).Methods("POST") // API version independent OAuth as a client endpoints - BaseRoutes.Root.Handle("/oauth/{service:[A-Za-z0-9]+}/complete", ApiHandler(completeOAuth)).Methods("GET") - BaseRoutes.Root.Handle("/oauth/{service:[A-Za-z0-9]+}/login", ApiHandler(loginWithOAuth)).Methods("GET") - BaseRoutes.Root.Handle("/oauth/{service:[A-Za-z0-9]+}/mobile_login", ApiHandler(mobileLoginWithOAuth)).Methods("GET") - BaseRoutes.Root.Handle("/oauth/{service:[A-Za-z0-9]+}/signup", ApiHandler(signupWithOAuth)).Methods("GET") + api.BaseRoutes.Root.Handle("/oauth/{service:[A-Za-z0-9]+}/complete", api.ApiHandler(completeOAuth)).Methods("GET") + api.BaseRoutes.Root.Handle("/oauth/{service:[A-Za-z0-9]+}/login", api.ApiHandler(loginWithOAuth)).Methods("GET") + api.BaseRoutes.Root.Handle("/oauth/{service:[A-Za-z0-9]+}/mobile_login", api.ApiHandler(mobileLoginWithOAuth)).Methods("GET") + api.BaseRoutes.Root.Handle("/oauth/{service:[A-Za-z0-9]+}/signup", api.ApiHandler(signupWithOAuth)).Methods("GET") // Old endpoints for backwards compatibility, needed to not break SSO for any old setups - BaseRoutes.Root.Handle("/api/v3/oauth/{service:[A-Za-z0-9]+}/complete", ApiHandler(completeOAuth)).Methods("GET") - BaseRoutes.Root.Handle("/signup/{service:[A-Za-z0-9]+}/complete", ApiHandler(completeOAuth)).Methods("GET") - BaseRoutes.Root.Handle("/login/{service:[A-Za-z0-9]+}/complete", ApiHandler(completeOAuth)).Methods("GET") + api.BaseRoutes.Root.Handle("/api/v3/oauth/{service:[A-Za-z0-9]+}/complete", api.ApiHandler(completeOAuth)).Methods("GET") + api.BaseRoutes.Root.Handle("/signup/{service:[A-Za-z0-9]+}/complete", api.ApiHandler(completeOAuth)).Methods("GET") + api.BaseRoutes.Root.Handle("/login/{service:[A-Za-z0-9]+}/complete", api.ApiHandler(completeOAuth)).Methods("GET") } func createOAuthApp(c *Context, w http.ResponseWriter, r *http.Request) { diff --git a/api4/openGraph.go b/api4/openGraph.go index 690631ab0..e03ecd219 100644 --- a/api4/openGraph.go +++ b/api4/openGraph.go @@ -16,10 +16,10 @@ const OPEN_GRAPH_METADATA_CACHE_SIZE = 10000 var openGraphDataCache = utils.NewLru(OPEN_GRAPH_METADATA_CACHE_SIZE) -func InitOpenGraph() { +func (api *API) InitOpenGraph() { l4g.Debug(utils.T("api.opengraph.init.debug")) - BaseRoutes.OpenGraph.Handle("", ApiSessionRequired(getOpenGraphMetadata)).Methods("POST") + api.BaseRoutes.OpenGraph.Handle("", api.ApiSessionRequired(getOpenGraphMetadata)).Methods("POST") } func getOpenGraphMetadata(c *Context, w http.ResponseWriter, r *http.Request) { diff --git a/api4/plugin.go b/api4/plugin.go index ac1620335..08dea6301 100644 --- a/api4/plugin.go +++ b/api4/plugin.go @@ -18,14 +18,14 @@ const ( MAXIMUM_PLUGIN_FILE_SIZE = 50 * 1024 * 1024 ) -func InitPlugin() { +func (api *API) InitPlugin() { l4g.Debug("EXPERIMENTAL: Initializing plugin api") - BaseRoutes.Plugins.Handle("", ApiSessionRequired(uploadPlugin)).Methods("POST") - BaseRoutes.Plugins.Handle("", ApiSessionRequired(getPlugins)).Methods("GET") - BaseRoutes.Plugin.Handle("", ApiSessionRequired(removePlugin)).Methods("DELETE") + 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") - BaseRoutes.Plugins.Handle("/webapp", ApiHandler(getWebappPlugins)).Methods("GET") + api.BaseRoutes.Plugins.Handle("/webapp", api.ApiHandler(getWebappPlugins)).Methods("GET") } diff --git a/api4/post.go b/api4/post.go index 1b60d0b4a..297c70a87 100644 --- a/api4/post.go +++ b/api4/post.go @@ -13,23 +13,23 @@ import ( "github.com/mattermost/mattermost-server/utils" ) -func InitPost() { +func (api *API) InitPost() { l4g.Debug(utils.T("api.post.init.debug")) - BaseRoutes.Posts.Handle("", ApiSessionRequired(createPost)).Methods("POST") - BaseRoutes.Post.Handle("", ApiSessionRequired(getPost)).Methods("GET") - BaseRoutes.Post.Handle("", ApiSessionRequired(deletePost)).Methods("DELETE") - BaseRoutes.Post.Handle("/thread", ApiSessionRequired(getPostThread)).Methods("GET") - BaseRoutes.Post.Handle("/files/info", ApiSessionRequired(getFileInfosForPost)).Methods("GET") - BaseRoutes.PostsForChannel.Handle("", ApiSessionRequired(getPostsForChannel)).Methods("GET") - BaseRoutes.PostsForUser.Handle("/flagged", ApiSessionRequired(getFlaggedPostsForUser)).Methods("GET") - - BaseRoutes.Team.Handle("/posts/search", ApiSessionRequired(searchPosts)).Methods("POST") - BaseRoutes.Post.Handle("", ApiSessionRequired(updatePost)).Methods("PUT") - BaseRoutes.Post.Handle("/patch", ApiSessionRequired(patchPost)).Methods("PUT") - BaseRoutes.Post.Handle("/actions/{action_id:[A-Za-z0-9]+}", ApiSessionRequired(doPostAction)).Methods("POST") - BaseRoutes.Post.Handle("/pin", ApiSessionRequired(pinPost)).Methods("POST") - BaseRoutes.Post.Handle("/unpin", ApiSessionRequired(unpinPost)).Methods("POST") + 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.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.Team.Handle("/posts/search", api.ApiSessionRequired(searchPosts)).Methods("POST") + api.BaseRoutes.Post.Handle("", api.ApiSessionRequired(updatePost)).Methods("PUT") + api.BaseRoutes.Post.Handle("/patch", api.ApiSessionRequired(patchPost)).Methods("PUT") + api.BaseRoutes.Post.Handle("/actions/{action_id:[A-Za-z0-9]+}", api.ApiSessionRequired(doPostAction)).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) { @@ -107,7 +107,7 @@ func getPostsForChannel(c *Context, w http.ResponseWriter, r *http.Request) { } else if len(afterPost) > 0 { etag = c.App.GetPostsEtag(c.Params.ChannelId) - if HandleEtag(etag, "Get Posts After", w, r) { + if c.HandleEtag(etag, "Get Posts After", w, r) { return } @@ -115,7 +115,7 @@ func getPostsForChannel(c *Context, w http.ResponseWriter, r *http.Request) { } else if len(beforePost) > 0 { etag = c.App.GetPostsEtag(c.Params.ChannelId) - if HandleEtag(etag, "Get Posts Before", w, r) { + if c.HandleEtag(etag, "Get Posts Before", w, r) { return } @@ -123,7 +123,7 @@ func getPostsForChannel(c *Context, w http.ResponseWriter, r *http.Request) { } else { etag = c.App.GetPostsEtag(c.Params.ChannelId) - if HandleEtag(etag, "Get Posts", w, r) { + if c.HandleEtag(etag, "Get Posts", w, r) { return } @@ -205,7 +205,7 @@ func getPost(c *Context, w http.ResponseWriter, r *http.Request) { } } - if HandleEtag(post.Etag(), "Get Post", w, r) { + if c.HandleEtag(post.Etag(), "Get Post", w, r) { return } else { w.Header().Set(model.HEADER_ETAG_SERVER, post.Etag()) @@ -271,7 +271,7 @@ func getPostThread(c *Context, w http.ResponseWriter, r *http.Request) { } } - if HandleEtag(list.Etag(), "Get Post Thread", w, r) { + if c.HandleEtag(list.Etag(), "Get Post Thread", w, r) { return } else { w.Header().Set(model.HEADER_ETAG_SERVER, list.Etag()) @@ -421,7 +421,7 @@ func getFileInfosForPost(c *Context, w http.ResponseWriter, r *http.Request) { if infos, err := c.App.GetFileInfosForPost(c.Params.PostId, false); err != nil { c.Err = err return - } else if HandleEtag(model.GetEtagForFileInfos(infos), "Get File Infos For Post", w, r) { + } else if c.HandleEtag(model.GetEtagForFileInfos(infos), "Get File Infos For Post", w, r) { return } else { w.Header().Set("Cache-Control", "max-age=2592000, public") diff --git a/api4/preference.go b/api4/preference.go index 41c200bd0..5ed83939a 100644 --- a/api4/preference.go +++ b/api4/preference.go @@ -12,14 +12,14 @@ import ( "github.com/mattermost/mattermost-server/utils" ) -func InitPreference() { +func (api *API) InitPreference() { l4g.Debug(utils.T("api.preference.init.debug")) - BaseRoutes.Preferences.Handle("", ApiSessionRequired(getPreferences)).Methods("GET") - BaseRoutes.Preferences.Handle("", ApiSessionRequired(updatePreferences)).Methods("PUT") - BaseRoutes.Preferences.Handle("/delete", ApiSessionRequired(deletePreferences)).Methods("POST") - BaseRoutes.Preferences.Handle("/{category:[A-Za-z0-9_]+}", ApiSessionRequired(getPreferencesByCategory)).Methods("GET") - BaseRoutes.Preferences.Handle("/{category:[A-Za-z0-9_]+}/name/{preference_name:[A-Za-z0-9_]+}", 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 aca6fc3ec..edfb1619e 100644 --- a/api4/reaction.go +++ b/api4/reaction.go @@ -12,12 +12,12 @@ import ( "github.com/mattermost/mattermost-server/utils" ) -func InitReaction() { +func (api *API) InitReaction() { l4g.Debug(utils.T("api.reaction.init.debug")) - BaseRoutes.Reactions.Handle("", ApiSessionRequired(saveReaction)).Methods("POST") - BaseRoutes.Post.Handle("/reactions", ApiSessionRequired(getReactions)).Methods("GET") - BaseRoutes.ReactionByNameForPostForUser.Handle("", ApiSessionRequired(deleteReaction)).Methods("DELETE") + 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") } func saveReaction(c *Context, w http.ResponseWriter, r *http.Request) { diff --git a/api4/saml.go b/api4/saml.go index 0fae1965b..733e8eaaa 100644 --- a/api4/saml.go +++ b/api4/saml.go @@ -13,20 +13,20 @@ import ( "github.com/mattermost/mattermost-server/utils" ) -func InitSaml() { +func (api *API) InitSaml() { l4g.Debug(utils.T("api.saml.init.debug")) - BaseRoutes.SAML.Handle("/metadata", ApiHandler(getSamlMetadata)).Methods("GET") + api.BaseRoutes.SAML.Handle("/metadata", api.ApiHandler(getSamlMetadata)).Methods("GET") - BaseRoutes.SAML.Handle("/certificate/public", ApiSessionRequired(addSamlPublicCertificate)).Methods("POST") - BaseRoutes.SAML.Handle("/certificate/private", ApiSessionRequired(addSamlPrivateCertificate)).Methods("POST") - BaseRoutes.SAML.Handle("/certificate/idp", 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") - BaseRoutes.SAML.Handle("/certificate/public", ApiSessionRequired(removeSamlPublicCertificate)).Methods("DELETE") - BaseRoutes.SAML.Handle("/certificate/private", ApiSessionRequired(removeSamlPrivateCertificate)).Methods("DELETE") - BaseRoutes.SAML.Handle("/certificate/idp", 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") - BaseRoutes.SAML.Handle("/certificate/status", ApiSessionRequired(getSamlCertificateStatus)).Methods("GET") + api.BaseRoutes.SAML.Handle("/certificate/status", api.ApiSessionRequired(getSamlCertificateStatus)).Methods("GET") } func getSamlMetadata(c *Context, w http.ResponseWriter, r *http.Request) { diff --git a/api4/status.go b/api4/status.go index a17707127..3aaa6f621 100644 --- a/api4/status.go +++ b/api4/status.go @@ -13,12 +13,12 @@ import ( "github.com/mattermost/mattermost-server/utils" ) -func InitStatus() { +func (api *API) InitStatus() { l4g.Debug(utils.T("api.status.init.debug")) - BaseRoutes.User.Handle("/status", ApiSessionRequired(getUserStatus)).Methods("GET") - BaseRoutes.Users.Handle("/status/ids", ApiSessionRequired(getUserStatusesByIds)).Methods("POST") - BaseRoutes.User.Handle("/status", ApiSessionRequired(updateUserStatus)).Methods("PUT") + 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") } func getUserStatus(c *Context, w http.ResponseWriter, r *http.Request) { diff --git a/api4/system.go b/api4/system.go index 766ea09ee..b8c927630 100644 --- a/api4/system.go +++ b/api4/system.go @@ -16,29 +16,29 @@ import ( "github.com/mattermost/mattermost-server/utils" ) -func InitSystem() { +func (api *API) InitSystem() { l4g.Debug(utils.T("api.system.init.debug")) - BaseRoutes.System.Handle("/ping", ApiHandler(getSystemPing)).Methods("GET") + api.BaseRoutes.System.Handle("/ping", api.ApiHandler(getSystemPing)).Methods("GET") - BaseRoutes.ApiRoot.Handle("/config", ApiSessionRequired(getConfig)).Methods("GET") - BaseRoutes.ApiRoot.Handle("/config", ApiSessionRequired(updateConfig)).Methods("PUT") - BaseRoutes.ApiRoot.Handle("/config/reload", ApiSessionRequired(configReload)).Methods("POST") - BaseRoutes.ApiRoot.Handle("/config/client", ApiHandler(getClientConfig)).Methods("GET") + 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/reload", api.ApiSessionRequired(configReload)).Methods("POST") + api.BaseRoutes.ApiRoot.Handle("/config/client", api.ApiHandler(getClientConfig)).Methods("GET") - BaseRoutes.ApiRoot.Handle("/license", ApiSessionRequired(addLicense)).Methods("POST") - BaseRoutes.ApiRoot.Handle("/license", ApiSessionRequired(removeLicense)).Methods("DELETE") - BaseRoutes.ApiRoot.Handle("/license/client", ApiHandler(getClientLicense)).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/client", api.ApiHandler(getClientLicense)).Methods("GET") - BaseRoutes.ApiRoot.Handle("/audits", ApiSessionRequired(getAudits)).Methods("GET") - BaseRoutes.ApiRoot.Handle("/email/test", ApiSessionRequired(testEmail)).Methods("POST") - BaseRoutes.ApiRoot.Handle("/database/recycle", ApiSessionRequired(databaseRecycle)).Methods("POST") - BaseRoutes.ApiRoot.Handle("/caches/invalidate", 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("/database/recycle", api.ApiSessionRequired(databaseRecycle)).Methods("POST") + api.BaseRoutes.ApiRoot.Handle("/caches/invalidate", api.ApiSessionRequired(invalidateCaches)).Methods("POST") - BaseRoutes.ApiRoot.Handle("/logs", ApiSessionRequired(getLogs)).Methods("GET") - BaseRoutes.ApiRoot.Handle("/logs", ApiSessionRequired(postLog)).Methods("POST") + api.BaseRoutes.ApiRoot.Handle("/logs", api.ApiSessionRequired(getLogs)).Methods("GET") + api.BaseRoutes.ApiRoot.Handle("/logs", api.ApiSessionRequired(postLog)).Methods("POST") - BaseRoutes.ApiRoot.Handle("/analytics/old", ApiSessionRequired(getAnalytics)).Methods("GET") + api.BaseRoutes.ApiRoot.Handle("/analytics/old", api.ApiSessionRequired(getAnalytics)).Methods("GET") } func getSystemPing(c *Context, w http.ResponseWriter, r *http.Request) { @@ -262,7 +262,7 @@ func getClientLicense(c *Context, w http.ResponseWriter, r *http.Request) { } etag := utils.GetClientLicenseEtag(true) - if HandleEtag(etag, "Get Client License", w, r) { + if c.HandleEtag(etag, "Get Client License", w, r) { return } diff --git a/api4/team.go b/api4/team.go index d15db6bd4..a94da2bef 100644 --- a/api4/team.go +++ b/api4/team.go @@ -19,38 +19,38 @@ const ( MAX_ADD_MEMBERS_BATCH = 20 ) -func InitTeam() { +func (api *API) InitTeam() { l4g.Debug(utils.T("api.team.init.debug")) - BaseRoutes.Teams.Handle("", ApiSessionRequired(createTeam)).Methods("POST") - BaseRoutes.Teams.Handle("", ApiSessionRequired(getAllTeams)).Methods("GET") - BaseRoutes.Teams.Handle("/search", ApiSessionRequired(searchTeams)).Methods("POST") - BaseRoutes.TeamsForUser.Handle("", ApiSessionRequired(getTeamsForUser)).Methods("GET") - BaseRoutes.TeamsForUser.Handle("/unread", ApiSessionRequired(getTeamsUnreadForUser)).Methods("GET") - - BaseRoutes.Team.Handle("", ApiSessionRequired(getTeam)).Methods("GET") - BaseRoutes.Team.Handle("", ApiSessionRequired(updateTeam)).Methods("PUT") - BaseRoutes.Team.Handle("", ApiSessionRequired(deleteTeam)).Methods("DELETE") - BaseRoutes.Team.Handle("/patch", ApiSessionRequired(patchTeam)).Methods("PUT") - BaseRoutes.Team.Handle("/stats", ApiSessionRequired(getTeamStats)).Methods("GET") - BaseRoutes.TeamMembers.Handle("", ApiSessionRequired(getTeamMembers)).Methods("GET") - BaseRoutes.TeamMembers.Handle("/ids", ApiSessionRequired(getTeamMembersByIds)).Methods("POST") - BaseRoutes.TeamMembersForUser.Handle("", ApiSessionRequired(getTeamMembersForUser)).Methods("GET") - BaseRoutes.TeamMembers.Handle("", ApiSessionRequired(addTeamMember)).Methods("POST") - BaseRoutes.Teams.Handle("/members/invite", ApiSessionRequired(addUserToTeamFromInvite)).Methods("POST") - BaseRoutes.TeamMembers.Handle("/batch", ApiSessionRequired(addTeamMembers)).Methods("POST") - BaseRoutes.TeamMember.Handle("", ApiSessionRequired(removeTeamMember)).Methods("DELETE") - - BaseRoutes.TeamForUser.Handle("/unread", ApiSessionRequired(getTeamUnread)).Methods("GET") - - BaseRoutes.TeamByName.Handle("", ApiSessionRequired(getTeamByName)).Methods("GET") - BaseRoutes.TeamMember.Handle("", ApiSessionRequired(getTeamMember)).Methods("GET") - BaseRoutes.TeamByName.Handle("/exists", ApiSessionRequired(teamExists)).Methods("GET") - BaseRoutes.TeamMember.Handle("/roles", ApiSessionRequired(updateTeamMemberRoles)).Methods("PUT") - - BaseRoutes.Team.Handle("/import", ApiSessionRequired(importTeam)).Methods("POST") - BaseRoutes.Team.Handle("/invite/email", ApiSessionRequired(inviteUsersToTeam)).Methods("POST") - BaseRoutes.Teams.Handle("/invite/{invite_id:[A-Za-z0-9]+}", ApiHandler(getInviteInfo)).Methods("GET") + api.BaseRoutes.Teams.Handle("", api.ApiSessionRequired(createTeam)).Methods("POST") + api.BaseRoutes.Teams.Handle("", api.ApiSessionRequired(getAllTeams)).Methods("GET") + api.BaseRoutes.Teams.Handle("/search", api.ApiSessionRequired(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("/stats", api.ApiSessionRequired(getTeamStats)).Methods("GET") + 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.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.Team.Handle("/import", api.ApiSessionRequired(importTeam)).Methods("POST") + api.BaseRoutes.Team.Handle("/invite/email", api.ApiSessionRequired(inviteUsersToTeam)).Methods("POST") + api.BaseRoutes.Teams.Handle("/invite/{invite_id:[A-Za-z0-9]+}", api.ApiHandler(getInviteInfo)).Methods("GET") } func createTeam(c *Context, w http.ResponseWriter, r *http.Request) { diff --git a/api4/user.go b/api4/user.go index e62091320..ea5c0f738 100644 --- a/api4/user.go +++ b/api4/user.go @@ -16,50 +16,50 @@ import ( "github.com/mattermost/mattermost-server/utils" ) -func InitUser() { +func (api *API) InitUser() { l4g.Debug(utils.T("api.user.init.debug")) - BaseRoutes.Users.Handle("", ApiHandler(createUser)).Methods("POST") - BaseRoutes.Users.Handle("", ApiSessionRequired(getUsers)).Methods("GET") - BaseRoutes.Users.Handle("/ids", ApiSessionRequired(getUsersByIds)).Methods("POST") - BaseRoutes.Users.Handle("/usernames", ApiSessionRequired(getUsersByNames)).Methods("POST") - BaseRoutes.Users.Handle("/search", ApiSessionRequired(searchUsers)).Methods("POST") - BaseRoutes.Users.Handle("/autocomplete", ApiSessionRequired(autocompleteUsers)).Methods("GET") - - BaseRoutes.User.Handle("", ApiSessionRequired(getUser)).Methods("GET") - BaseRoutes.User.Handle("/image", ApiSessionRequiredTrustRequester(getProfileImage)).Methods("GET") - BaseRoutes.User.Handle("/image", ApiSessionRequired(setProfileImage)).Methods("POST") - BaseRoutes.User.Handle("", ApiSessionRequired(updateUser)).Methods("PUT") - BaseRoutes.User.Handle("/patch", ApiSessionRequired(patchUser)).Methods("PUT") - BaseRoutes.User.Handle("", ApiSessionRequired(deleteUser)).Methods("DELETE") - BaseRoutes.User.Handle("/roles", ApiSessionRequired(updateUserRoles)).Methods("PUT") - BaseRoutes.User.Handle("/active", ApiSessionRequired(updateUserActive)).Methods("PUT") - BaseRoutes.User.Handle("/password", ApiSessionRequired(updatePassword)).Methods("PUT") - BaseRoutes.Users.Handle("/password/reset", ApiHandler(resetPassword)).Methods("POST") - BaseRoutes.Users.Handle("/password/reset/send", ApiHandler(sendPasswordReset)).Methods("POST") - BaseRoutes.Users.Handle("/email/verify", ApiHandler(verifyUserEmail)).Methods("POST") - BaseRoutes.Users.Handle("/email/verify/send", ApiHandler(sendVerificationEmail)).Methods("POST") - - BaseRoutes.Users.Handle("/mfa", ApiHandler(checkUserMfa)).Methods("POST") - BaseRoutes.User.Handle("/mfa", ApiSessionRequiredMfa(updateUserMfa)).Methods("PUT") - BaseRoutes.User.Handle("/mfa/generate", ApiSessionRequiredMfa(generateMfaSecret)).Methods("POST") - - BaseRoutes.Users.Handle("/login", ApiHandler(login)).Methods("POST") - BaseRoutes.Users.Handle("/login/switch", ApiHandler(switchAccountType)).Methods("POST") - BaseRoutes.Users.Handle("/logout", ApiHandler(logout)).Methods("POST") - - BaseRoutes.UserByUsername.Handle("", ApiSessionRequired(getUserByUsername)).Methods("GET") - BaseRoutes.UserByEmail.Handle("", ApiSessionRequired(getUserByEmail)).Methods("GET") - - BaseRoutes.User.Handle("/sessions", ApiSessionRequired(getSessions)).Methods("GET") - BaseRoutes.User.Handle("/sessions/revoke", ApiSessionRequired(revokeSession)).Methods("POST") - BaseRoutes.Users.Handle("/sessions/device", ApiSessionRequired(attachDeviceId)).Methods("PUT") - BaseRoutes.User.Handle("/audits", ApiSessionRequired(getUserAudits)).Methods("GET") - - BaseRoutes.User.Handle("/tokens", ApiSessionRequired(createUserAccessToken)).Methods("POST") - BaseRoutes.User.Handle("/tokens", ApiSessionRequired(getUserAccessTokens)).Methods("GET") - BaseRoutes.Users.Handle("/tokens/{token_id:[A-Za-z0-9]+}", ApiSessionRequired(getUserAccessToken)).Methods("GET") - BaseRoutes.Users.Handle("/tokens/revoke", ApiSessionRequired(revokeUserAccessToken)).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("/search", api.ApiSessionRequired(searchUsers)).Methods("POST") + api.BaseRoutes.Users.Handle("/autocomplete", api.ApiSessionRequired(autocompleteUsers)).Methods("GET") + + api.BaseRoutes.User.Handle("", api.ApiSessionRequired(getUser)).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("", 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.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.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("/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.User.Handle("/sessions", api.ApiSessionRequired(getSessions)).Methods("GET") + api.BaseRoutes.User.Handle("/sessions/revoke", api.ApiSessionRequired(revokeSession)).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(getUserAccessTokens)).Methods("GET") + 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") } func createUser(c *Context, w http.ResponseWriter, r *http.Request) { @@ -113,7 +113,7 @@ func getUser(c *Context, w http.ResponseWriter, r *http.Request) { etag := user.Etag(utils.Cfg.PrivacySettings.ShowFullName, utils.Cfg.PrivacySettings.ShowEmailAddress) - if HandleEtag(etag, "Get User", w, r) { + if c.HandleEtag(etag, "Get User", w, r) { return } else { if c.Session.UserId == user.Id { @@ -145,7 +145,7 @@ func getUserByUsername(c *Context, w http.ResponseWriter, r *http.Request) { etag := user.Etag(utils.Cfg.PrivacySettings.ShowFullName, utils.Cfg.PrivacySettings.ShowEmailAddress) - if HandleEtag(etag, "Get User", w, r) { + if c.HandleEtag(etag, "Get User", w, r) { return } else { app.SanitizeProfile(user, c.IsSystemAdmin()) @@ -173,7 +173,7 @@ func getUserByEmail(c *Context, w http.ResponseWriter, r *http.Request) { etag := user.Etag(utils.Cfg.PrivacySettings.ShowFullName, utils.Cfg.PrivacySettings.ShowEmailAddress) - if HandleEtag(etag, "Get User", w, r) { + if c.HandleEtag(etag, "Get User", w, r) { return } else { app.SanitizeProfile(user, c.IsSystemAdmin()) @@ -199,7 +199,7 @@ func getProfileImage(c *Context, w http.ResponseWriter, r *http.Request) { user := users[0] etag := strconv.FormatInt(user.LastPictureUpdate, 10) - if HandleEtag(etag, "Get Profile Image", w, r) { + if c.HandleEtag(etag, "Get Profile Image", w, r) { return } @@ -322,7 +322,7 @@ func getUsers(c *Context, w http.ResponseWriter, r *http.Request) { } etag = c.App.GetUsersNotInTeamEtag(inTeamId) - if HandleEtag(etag, "Get Users Not in Team", w, r) { + if c.HandleEtag(etag, "Get Users Not in Team", w, r) { return } @@ -339,7 +339,7 @@ func getUsers(c *Context, w http.ResponseWriter, r *http.Request) { profiles, err = c.App.GetNewUsersForTeamPage(inTeamId, c.Params.Page, c.Params.PerPage, c.IsSystemAdmin()) } else { etag = c.App.GetUsersInTeamEtag(inTeamId) - if HandleEtag(etag, "Get Users in Team", w, r) { + if c.HandleEtag(etag, "Get Users in Team", w, r) { return } @@ -356,7 +356,7 @@ func getUsers(c *Context, w http.ResponseWriter, r *http.Request) { // No permission check required etag = c.App.GetUsersEtag() - if HandleEtag(etag, "Get Users", w, r) { + if c.HandleEtag(etag, "Get Users", w, r) { return } profiles, err = c.App.GetUsersPage(c.Params.Page, c.Params.PerPage, c.IsSystemAdmin()) diff --git a/api4/webhook.go b/api4/webhook.go index c86fa3253..39d0cbff4 100644 --- a/api4/webhook.go +++ b/api4/webhook.go @@ -15,27 +15,27 @@ import ( "github.com/mattermost/mattermost-server/utils" ) -func InitWebhook() { +func (api *API) InitWebhook() { l4g.Debug(utils.T("api.webhook.init.debug")) - BaseRoutes.IncomingHooks.Handle("", ApiSessionRequired(createIncomingHook)).Methods("POST") - BaseRoutes.IncomingHooks.Handle("", ApiSessionRequired(getIncomingHooks)).Methods("GET") - BaseRoutes.IncomingHook.Handle("", ApiSessionRequired(getIncomingHook)).Methods("GET") - BaseRoutes.IncomingHook.Handle("", ApiSessionRequired(updateIncomingHook)).Methods("PUT") - BaseRoutes.IncomingHook.Handle("", 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") - BaseRoutes.OutgoingHooks.Handle("", ApiSessionRequired(createOutgoingHook)).Methods("POST") - BaseRoutes.OutgoingHooks.Handle("", ApiSessionRequired(getOutgoingHooks)).Methods("GET") - BaseRoutes.OutgoingHook.Handle("", ApiSessionRequired(getOutgoingHook)).Methods("GET") - BaseRoutes.OutgoingHook.Handle("", ApiSessionRequired(updateOutgoingHook)).Methods("PUT") - BaseRoutes.OutgoingHook.Handle("", ApiSessionRequired(deleteOutgoingHook)).Methods("DELETE") - BaseRoutes.OutgoingHook.Handle("/regen_token", 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") - BaseRoutes.Root.Handle("/hooks/commands/{id:[A-Za-z0-9]+}", ApiHandler(commandWebhook)).Methods("POST") - BaseRoutes.Root.Handle("/hooks/{id:[A-Za-z0-9]+}", ApiHandler(incomingWebhook)).Methods("POST") + api.BaseRoutes.Root.Handle("/hooks/commands/{id:[A-Za-z0-9]+}", api.ApiHandler(commandWebhook)).Methods("POST") + api.BaseRoutes.Root.Handle("/hooks/{id:[A-Za-z0-9]+}", api.ApiHandler(incomingWebhook)).Methods("POST") // Old endpoint for backwards compatibility - BaseRoutes.Root.Handle("/api/v3/teams/{team_id:[A-Za-z0-9]+}/hooks/{id:[A-Za-z0-9]+}", ApiHandler(incomingWebhook)).Methods("POST") + api.BaseRoutes.Root.Handle("/api/v3/teams/{team_id:[A-Za-z0-9]+}/hooks/{id:[A-Za-z0-9]+}", api.ApiHandler(incomingWebhook)).Methods("POST") } func createIncomingHook(c *Context, w http.ResponseWriter, r *http.Request) { diff --git a/api4/webrtc.go b/api4/webrtc.go index a9f80fb7b..bf418d5e8 100644 --- a/api4/webrtc.go +++ b/api4/webrtc.go @@ -11,10 +11,10 @@ import ( "github.com/mattermost/mattermost-server/utils" ) -func InitWebrtc() { +func (api *API) InitWebrtc() { l4g.Debug(utils.T("api.webrtc.init.debug")) - BaseRoutes.Webrtc.Handle("/token", ApiSessionRequired(webrtcToken)).Methods("GET") + api.BaseRoutes.Webrtc.Handle("/token", api.ApiSessionRequired(webrtcToken)).Methods("GET") } func webrtcToken(c *Context, w http.ResponseWriter, r *http.Request) { diff --git a/api4/websocket.go b/api4/websocket.go index fbc1ea9cc..7dfe3d61c 100644 --- a/api4/websocket.go +++ b/api4/websocket.go @@ -13,10 +13,10 @@ import ( "github.com/mattermost/mattermost-server/utils" ) -func InitWebSocket() { +func (api *API) InitWebSocket() { l4g.Debug(utils.T("api.web_socket.init.debug")) - BaseRoutes.ApiRoot.Handle("/websocket", ApiHandlerTrustRequester(connectWebSocket)).Methods("GET") + api.BaseRoutes.ApiRoot.Handle("/websocket", api.ApiHandlerTrustRequester(connectWebSocket)).Methods("GET") } func connectWebSocket(c *Context, w http.ResponseWriter, r *http.Request) { diff --git a/cmd/platform/server.go b/cmd/platform/server.go index 60d3804e4..55854dfe4 100644 --- a/cmd/platform/server.go +++ b/cmd/platform/server.go @@ -81,10 +81,10 @@ func runServer(configFileLocation string) { } wsapi.InitRouter() - api4.InitApi(a.Srv.Router, false) - api.InitApi(a.Srv.Router) + api4.Init(a, a.Srv.Router, false) + api3 := api.Init(a, a.Srv.Router) wsapi.InitApi() - web.InitWeb() + web.Init(api3) if !utils.IsLicensed() && len(utils.Cfg.SqlSettings.DataSourceReplicas) > 1 { l4g.Warn(utils.T("store.sql.read_replicas_not_licensed.critical")) @@ -108,7 +108,7 @@ func runServer(configFileLocation string) { // If we allow testing then listen for manual testing URL hits if utils.Cfg.ServiceSettings.EnableTesting { - manualtesting.InitManualTesting() + manualtesting.Init(api3) } setDiagnosticId(a) diff --git a/cmd/platform/test.go b/cmd/platform/test.go index a7b89f40f..fd8777a46 100644 --- a/cmd/platform/test.go +++ b/cmd/platform/test.go @@ -53,8 +53,8 @@ func webClientTestsCmdF(cmd *cobra.Command, args []string) error { utils.InitTranslations(utils.Cfg.LocalizationSettings) a.Srv.Router = api.NewRouter() wsapi.InitRouter() - api4.InitApi(a.Srv.Router, false) - api.InitApi(a.Srv.Router) + api4.Init(a, a.Srv.Router, false) + api.Init(a, a.Srv.Router) wsapi.InitApi() setupClientTests() a.StartServer() @@ -73,8 +73,8 @@ func serverForWebClientTestsCmdF(cmd *cobra.Command, args []string) error { utils.InitTranslations(utils.Cfg.LocalizationSettings) a.Srv.Router = api.NewRouter() wsapi.InitRouter() - api4.InitApi(a.Srv.Router, false) - api.InitApi(a.Srv.Router) + api4.Init(a, a.Srv.Router, false) + api.Init(a, a.Srv.Router) wsapi.InitApi() setupClientTests() a.StartServer() diff --git a/manualtesting/manual_testing.go b/manualtesting/manual_testing.go index dc5674edd..33cf94cbf 100644 --- a/manualtesting/manual_testing.go +++ b/manualtesting/manual_testing.go @@ -28,8 +28,8 @@ type TestEnvironment struct { Request *http.Request } -func InitManualTesting() { - app.Global().Srv.Router.Handle("/manualtest", api.AppHandler(manualTest)).Methods("GET") +func Init(api3 *api.API) { + api3.BaseRoutes.Root.Handle("/manualtest", api3.AppHandler(manualTest)).Methods("GET") } func manualTest(c *api.Context, w http.ResponseWriter, r *http.Request) { @@ -153,9 +153,9 @@ func manualTest(c *api.Context, w http.ResponseWriter, r *http.Request) { } } -func getChannelID(channelname string, teamid string, userid string) (id string, err bool) { +func getChannelID(a *app.App, channelname string, teamid string, userid string) (id string, err bool) { // Grab all the channels - result := <-app.Global().Srv.Store.Channel().GetChannels(teamid, userid) + result := <-a.Srv.Store.Channel().GetChannels(teamid, userid) if result.Err != nil { l4g.Debug(utils.T("manaultesting.get_channel_id.unable.debug")) return "", false diff --git a/manualtesting/test_autolink.go b/manualtesting/test_autolink.go index 2e5f9c6e7..2614a9e4b 100644 --- a/manualtesting/test_autolink.go +++ b/manualtesting/test_autolink.go @@ -24,7 +24,7 @@ https://medium.com/@slackhq/11-useful-tips-for-getting-the-most-of-slack-5dfb3d1 func testAutoLink(env TestEnvironment) *model.AppError { l4g.Info(utils.T("manaultesting.test_autolink.info")) - channelID, err := getChannelID(model.DEFAULT_CHANNEL, env.CreatedTeamId, env.CreatedUserId) + channelID, err := getChannelID(env.Context.App, model.DEFAULT_CHANNEL, env.CreatedTeamId, env.CreatedUserId) if err != true { return model.NewAppError("/manualtest", "manaultesting.test_autolink.unable.app_error", nil, "", http.StatusInternalServerError) } diff --git a/web/web.go b/web/web.go index 2f9e111bd..77a0c107a 100644 --- a/web/web.go +++ b/web/web.go @@ -11,16 +11,15 @@ import ( l4g "github.com/alecthomas/log4go" "github.com/mattermost/mattermost-server/api" - "github.com/mattermost/mattermost-server/app" "github.com/mattermost/mattermost-server/model" "github.com/mattermost/mattermost-server/utils" "github.com/mssola/user_agent" ) -func InitWeb() { +func Init(api3 *api.API) { l4g.Debug(utils.T("web.init.debug")) - mainrouter := app.Global().Srv.Router + mainrouter := api3.BaseRoutes.Root if *utils.Cfg.ServiceSettings.WebserverMode != "disabled" { staticDir, _ := utils.FindDir(model.CLIENT_DIR) @@ -36,7 +35,7 @@ func InitWeb() { mainrouter.PathPrefix("/static/plugins/").Handler(pluginHandler) mainrouter.PathPrefix("/static/").Handler(staticHandler) - mainrouter.Handle("/{anything:.*}", api.AppHandlerIndependent(root)).Methods("GET") + mainrouter.Handle("/{anything:.*}", api3.AppHandlerIndependent(root)).Methods("GET") } } diff --git a/web/web_test.go b/web/web_test.go index 2bf92151f..ba47f831a 100644 --- a/web/web_test.go +++ b/web/web_test.go @@ -27,9 +27,9 @@ func Setup() *app.App { a.InitStores() a.Srv.Router = api.NewRouter() a.StartServer() - api4.InitApi(a.Srv.Router, false) - api.InitApi(a.Srv.Router) - InitWeb() + api4.Init(a, a.Srv.Router, false) + api3 := api.Init(a, a.Srv.Router) + Init(api3) URL = "http://localhost" + *utils.Cfg.ServiceSettings.ListenAddress ApiClient = model.NewClient(URL) -- cgit v1.2.3-1-g7c22