handlers.go 10 KB

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