handlers.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  1. package main
  2. import (
  3. "crypto/subtle"
  4. "net/http"
  5. "net/url"
  6. "path"
  7. "regexp"
  8. "strconv"
  9. "github.com/labstack/echo"
  10. "github.com/labstack/echo/middleware"
  11. )
  12. const (
  13. // stdInputMaxLen is the maximum allowed length for a standard input field.
  14. stdInputMaxLen = 200
  15. sortAsc = "asc"
  16. sortDesc = "desc"
  17. )
  18. type okResp struct {
  19. Data interface{} `json:"data"`
  20. }
  21. // pagination represents a query's pagination (limit, offset) related values.
  22. type pagination struct {
  23. PerPage int `json:"per_page"`
  24. Page int `json:"page"`
  25. Offset int `json:"offset"`
  26. Limit int `json:"limit"`
  27. }
  28. var (
  29. reUUID = regexp.MustCompile("^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$")
  30. reLangCode = regexp.MustCompile("[^a-zA-Z_0-9\\-]")
  31. )
  32. // registerHandlers registers HTTP handlers.
  33. func initHTTPHandlers(e *echo.Echo, app *App) {
  34. // Group of private handlers with BasicAuth.
  35. var g *echo.Group
  36. if len(app.constants.AdminUsername) == 0 ||
  37. len(app.constants.AdminPassword) == 0 {
  38. g = e.Group("")
  39. } else {
  40. g = e.Group("", middleware.BasicAuth(basicAuth))
  41. }
  42. // Admin JS app views.
  43. // /admin/static/* file server is registered in initHTTPServer().
  44. g.GET("/", func(c echo.Context) error {
  45. return c.Redirect(http.StatusPermanentRedirect, path.Join(adminRoot, ""))
  46. })
  47. g.GET(path.Join(adminRoot, ""), handleAdminPage)
  48. g.GET(path.Join(adminRoot, "/*"), handleAdminPage)
  49. // API endpoints.
  50. g.GET("/api/health", handleHealthCheck)
  51. g.GET("/api/config", handleGetServerConfig)
  52. g.GET("/api/lang/:lang", handleGetI18nLang)
  53. g.GET("/api/dashboard/charts", handleGetDashboardCharts)
  54. g.GET("/api/dashboard/counts", handleGetDashboardCounts)
  55. g.GET("/api/settings", handleGetSettings)
  56. g.PUT("/api/settings", handleUpdateSettings)
  57. g.POST("/api/admin/reload", handleReloadApp)
  58. g.GET("/api/logs", handleGetLogs)
  59. g.GET("/api/subscribers/:id", handleGetSubscriber)
  60. g.GET("/api/subscribers/:id/export", handleExportSubscriberData)
  61. g.GET("/api/subscribers/:id/bounces", handleGetSubscriberBounces)
  62. g.DELETE("/api/subscribers/:id/bounces", handleDeleteSubscriberBounces)
  63. g.POST("/api/subscribers", handleCreateSubscriber)
  64. g.PUT("/api/subscribers/:id", handleUpdateSubscriber)
  65. g.POST("/api/subscribers/:id/optin", handleSubscriberSendOptin)
  66. g.PUT("/api/subscribers/blocklist", handleBlocklistSubscribers)
  67. g.PUT("/api/subscribers/:id/blocklist", handleBlocklistSubscribers)
  68. g.PUT("/api/subscribers/lists/:id", handleManageSubscriberLists)
  69. g.PUT("/api/subscribers/lists", handleManageSubscriberLists)
  70. g.DELETE("/api/subscribers/:id", handleDeleteSubscribers)
  71. g.DELETE("/api/subscribers", handleDeleteSubscribers)
  72. g.GET("/api/bounces", handleGetBounces)
  73. g.DELETE("/api/bounces", handleDeleteBounces)
  74. g.DELETE("/api/bounces/:id", handleDeleteBounces)
  75. // Subscriber operations based on arbitrary SQL queries.
  76. // These aren't very REST-like.
  77. g.POST("/api/subscribers/query/delete", handleDeleteSubscribersByQuery)
  78. g.PUT("/api/subscribers/query/blocklist", handleBlocklistSubscribersByQuery)
  79. g.PUT("/api/subscribers/query/lists", handleManageSubscriberListsByQuery)
  80. g.GET("/api/subscribers", handleQuerySubscribers)
  81. g.GET("/api/subscribers/export",
  82. middleware.GzipWithConfig(middleware.GzipConfig{Level: 9})(handleExportSubscribers))
  83. g.GET("/api/import/subscribers", handleGetImportSubscribers)
  84. g.GET("/api/import/subscribers/logs", handleGetImportSubscriberStats)
  85. g.POST("/api/import/subscribers", handleImportSubscribers)
  86. g.DELETE("/api/import/subscribers", handleStopImportSubscribers)
  87. g.GET("/api/lists", handleGetLists)
  88. g.GET("/api/lists/:id", handleGetLists)
  89. g.POST("/api/lists", handleCreateList)
  90. g.PUT("/api/lists/:id", handleUpdateList)
  91. g.DELETE("/api/lists/:id", handleDeleteLists)
  92. g.GET("/api/campaigns", handleGetCampaigns)
  93. g.GET("/api/campaigns/running/stats", handleGetRunningCampaignStats)
  94. g.GET("/api/campaigns/:id", handleGetCampaigns)
  95. g.GET("/api/campaigns/analytics/:type", handleGetCampaignViewAnalytics)
  96. g.GET("/api/campaigns/:id/preview", handlePreviewCampaign)
  97. g.POST("/api/campaigns/:id/preview", handlePreviewCampaign)
  98. g.POST("/api/campaigns/:id/content", handleCampaignContent)
  99. g.POST("/api/campaigns/:id/text", handlePreviewCampaign)
  100. g.POST("/api/campaigns/:id/test", handleTestCampaign)
  101. g.POST("/api/campaigns", handleCreateCampaign)
  102. g.PUT("/api/campaigns/:id", handleUpdateCampaign)
  103. g.PUT("/api/campaigns/:id/status", handleUpdateCampaignStatus)
  104. g.DELETE("/api/campaigns/:id", handleDeleteCampaign)
  105. g.GET("/api/media", handleGetMedia)
  106. g.POST("/api/media", handleUploadMedia)
  107. g.DELETE("/api/media/:id", handleDeleteMedia)
  108. g.GET("/api/templates", handleGetTemplates)
  109. g.GET("/api/templates/:id", handleGetTemplates)
  110. g.GET("/api/templates/:id/preview", handlePreviewTemplate)
  111. g.POST("/api/templates/preview", handlePreviewTemplate)
  112. g.POST("/api/templates", handleCreateTemplate)
  113. g.PUT("/api/templates/:id", handleUpdateTemplate)
  114. g.PUT("/api/templates/:id/default", handleTemplateSetDefault)
  115. g.DELETE("/api/templates/:id", handleDeleteTemplate)
  116. if app.constants.BounceWebhooksEnabled {
  117. // Private authenticated bounce endpoint.
  118. g.POST("/webhooks/bounce", handleBounceWebhook)
  119. // Public bounce endpoints for webservices like SES.
  120. e.POST("/webhooks/service/:service", handleBounceWebhook)
  121. }
  122. // Public subscriber facing views.
  123. e.GET("/subscription/form", handleSubscriptionFormPage)
  124. e.POST("/subscription/form", handleSubscriptionForm)
  125. e.GET("/subscription/:campUUID/:subUUID", noIndex(validateUUID(subscriberExists(handleSubscriptionPage),
  126. "campUUID", "subUUID")))
  127. e.POST("/subscription/:campUUID/:subUUID", validateUUID(subscriberExists(handleSubscriptionPage),
  128. "campUUID", "subUUID"))
  129. e.GET("/subscription/optin/:subUUID", noIndex(validateUUID(subscriberExists(handleOptinPage), "subUUID")))
  130. e.POST("/subscription/optin/:subUUID", validateUUID(subscriberExists(handleOptinPage), "subUUID"))
  131. e.POST("/subscription/export/:subUUID", validateUUID(subscriberExists(handleSelfExportSubscriberData),
  132. "subUUID"))
  133. e.POST("/subscription/wipe/:subUUID", validateUUID(subscriberExists(handleWipeSubscriberData),
  134. "subUUID"))
  135. e.GET("/link/:linkUUID/:campUUID/:subUUID", noIndex(validateUUID(handleLinkRedirect,
  136. "linkUUID", "campUUID", "subUUID")))
  137. e.GET("/campaign/:campUUID/:subUUID", noIndex(validateUUID(handleViewCampaignMessage,
  138. "campUUID", "subUUID")))
  139. e.GET("/campaign/:campUUID/:subUUID/px.png", noIndex(validateUUID(handleRegisterCampaignView,
  140. "campUUID", "subUUID")))
  141. // Public health API endpoint.
  142. e.GET("/health", handleHealthCheck)
  143. }
  144. // handleAdminPage is the root handler that renders the Javascript admin frontend.
  145. func handleAdminPage(c echo.Context) error {
  146. app := c.Get("app").(*App)
  147. b, err := app.fs.Read(path.Join(adminRoot, "/index.html"))
  148. if err != nil {
  149. return echo.NewHTTPError(http.StatusInternalServerError, err.Error())
  150. }
  151. return c.HTMLBlob(http.StatusOK, b)
  152. }
  153. // handleHealthCheck is a healthcheck endpoint that returns a 200 response.
  154. func handleHealthCheck(c echo.Context) error {
  155. return c.JSON(http.StatusOK, okResp{true})
  156. }
  157. // basicAuth middleware does an HTTP BasicAuth authentication for admin handlers.
  158. func basicAuth(username, password string, c echo.Context) (bool, error) {
  159. app := c.Get("app").(*App)
  160. // Auth is disabled.
  161. if len(app.constants.AdminUsername) == 0 &&
  162. len(app.constants.AdminPassword) == 0 {
  163. return true, nil
  164. }
  165. if subtle.ConstantTimeCompare([]byte(username), app.constants.AdminUsername) == 1 &&
  166. subtle.ConstantTimeCompare([]byte(password), app.constants.AdminPassword) == 1 {
  167. return true, nil
  168. }
  169. return false, nil
  170. }
  171. // validateUUID middleware validates the UUID string format for a given set of params.
  172. func validateUUID(next echo.HandlerFunc, params ...string) echo.HandlerFunc {
  173. return func(c echo.Context) error {
  174. app := c.Get("app").(*App)
  175. for _, p := range params {
  176. if !reUUID.MatchString(c.Param(p)) {
  177. return c.Render(http.StatusBadRequest, tplMessage,
  178. makeMsgTpl(app.i18n.T("public.errorTitle"), "",
  179. app.i18n.T("globals.messages.invalidUUID")))
  180. }
  181. }
  182. return next(c)
  183. }
  184. }
  185. // subscriberExists middleware checks if a subscriber exists given the UUID
  186. // param in a request.
  187. func subscriberExists(next echo.HandlerFunc, params ...string) echo.HandlerFunc {
  188. return func(c echo.Context) error {
  189. var (
  190. app = c.Get("app").(*App)
  191. subUUID = c.Param("subUUID")
  192. )
  193. var exists bool
  194. if err := app.queries.SubscriberExists.Get(&exists, 0, subUUID); err != nil {
  195. app.log.Printf("error checking subscriber existence: %v", err)
  196. return c.Render(http.StatusInternalServerError, tplMessage,
  197. makeMsgTpl(app.i18n.T("public.errorTitle"), "",
  198. app.i18n.T("public.errorProcessingRequest")))
  199. }
  200. if !exists {
  201. return c.Render(http.StatusNotFound, tplMessage,
  202. makeMsgTpl(app.i18n.T("public.notFoundTitle"), "",
  203. app.i18n.T("public.subNotFound")))
  204. }
  205. return next(c)
  206. }
  207. }
  208. // noIndex adds the HTTP header requesting robots to not crawl the page.
  209. func noIndex(next echo.HandlerFunc, params ...string) echo.HandlerFunc {
  210. return func(c echo.Context) error {
  211. c.Response().Header().Set("X-Robots-Tag", "noindex")
  212. return next(c)
  213. }
  214. }
  215. // getPagination takes form values and extracts pagination values from it.
  216. func getPagination(q url.Values, perPage int) pagination {
  217. var (
  218. page, _ = strconv.Atoi(q.Get("page"))
  219. pp = q.Get("per_page")
  220. )
  221. if pp == "all" {
  222. // No limit.
  223. perPage = 0
  224. } else {
  225. ppi, _ := strconv.Atoi(pp)
  226. if ppi > 0 {
  227. perPage = ppi
  228. }
  229. }
  230. if page < 1 {
  231. page = 0
  232. } else {
  233. page--
  234. }
  235. return pagination{
  236. Page: page + 1,
  237. PerPage: perPage,
  238. Offset: page * perPage,
  239. Limit: perPage,
  240. }
  241. }
  242. // copyEchoCtx returns a copy of the the current echo.Context in a request
  243. // with the given params set for the active handler to proxy the request
  244. // to another handler without mutating its context.
  245. func copyEchoCtx(c echo.Context, params map[string]string) echo.Context {
  246. var (
  247. keys = make([]string, 0, len(params))
  248. vals = make([]string, 0, len(params))
  249. )
  250. for k, v := range params {
  251. keys = append(keys, k)
  252. vals = append(vals, v)
  253. }
  254. b := c.Echo().NewContext(c.Request(), c.Response())
  255. b.Set("app", c.Get("app").(*App))
  256. b.SetParamNames(keys...)
  257. b.SetParamValues(vals...)
  258. return b
  259. }