server.go 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  1. /*
  2. * MIT License
  3. *
  4. * Copyright (c) 2020 Alexey Edelev <semlanik@gmail.com>
  5. *
  6. * This file is part of gostfix project https://git.semlanik.org/semlanik/gostfix
  7. *
  8. * Permission is hereby granted, free of charge, to any person obtaining a copy of this
  9. * software and associated documentation files (the "Software"), to deal in the Software
  10. * without restriction, including without limitation the rights to use, copy, modify,
  11. * merge, publish, distribute, sublicense, and/or sell copies of the Software, and
  12. * to permit persons to whom the Software is furnished to do so, subject to the following
  13. * conditions:
  14. *
  15. * The above copyright notice and this permission notice shall be included in all copies
  16. * or substantial portions of the Software.
  17. *
  18. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
  19. * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
  20. * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
  21. * FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  22. * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  23. * DEALINGS IN THE SOFTWARE.
  24. */
  25. package web
  26. import (
  27. "fmt"
  28. "log"
  29. "net/http"
  30. "strings"
  31. auth "git.semlanik.org/semlanik/gostfix/auth"
  32. common "git.semlanik.org/semlanik/gostfix/common"
  33. "git.semlanik.org/semlanik/gostfix/config"
  34. db "git.semlanik.org/semlanik/gostfix/db"
  35. service "git.semlanik.org/semlanik/gostfix/service"
  36. sessions "github.com/gorilla/sessions"
  37. )
  38. const (
  39. StateHeaderScan = iota
  40. StateBodyScan
  41. StateContentScan
  42. )
  43. const (
  44. AtLeastOneHeaderMask = 1 << iota
  45. FromHeaderMask
  46. DateHeaderMask
  47. ToHeaderMask
  48. AllHeaderMask = 15
  49. )
  50. const (
  51. CookieSessionToken = "gostfix_session"
  52. )
  53. type Server struct {
  54. authenticator *auth.Authenticator
  55. fileServer http.Handler
  56. attachmentsServer http.Handler
  57. templater *Templater
  58. sessionStore *sessions.CookieStore
  59. storage *db.Storage
  60. notifier *webNotifier
  61. scanner common.Scanner
  62. watcher service.NanoServiceWatcher
  63. httpServer *http.Server
  64. }
  65. func NewServer(scanner common.Scanner, watcher service.NanoServiceWatcher) *Server {
  66. storage, err := db.NewStorage()
  67. if err != nil {
  68. log.Fatalf("Unable to intialize mail storage %s", err)
  69. return nil
  70. }
  71. authenticator, err := auth.NewAuthenticator()
  72. if err != nil {
  73. log.Fatalf("Unable to intialize authenticator %s", err)
  74. return nil
  75. }
  76. s := &Server{
  77. authenticator: authenticator,
  78. templater: NewTemplater("data/templates"),
  79. fileServer: http.FileServer(http.Dir("data")),
  80. attachmentsServer: http.StripPrefix("/attachment/", http.FileServer(http.Dir(config.ConfigInstance().AttachmentsPath))),
  81. sessionStore: sessions.NewCookieStore(make([]byte, 32)),
  82. storage: storage,
  83. notifier: NewWebNotifier(),
  84. scanner: scanner,
  85. watcher: watcher,
  86. }
  87. s.notifier.server = s
  88. s.storage.RegisterNotifier(s.notifier)
  89. s.httpServer = &http.Server{
  90. Addr: ":" + config.ConfigInstance().WebPort,
  91. Handler: s,
  92. }
  93. return s
  94. }
  95. func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  96. log.Printf("%s %s", r.Method, r.URL.Path)
  97. urlParts := strings.Split(r.URL.Path, "/")[1:]
  98. if len(urlParts) == 0 || urlParts[0] == "" {
  99. http.Redirect(w, r, "/m/0", http.StatusTemporaryRedirect)
  100. return
  101. }
  102. switch urlParts[0] {
  103. case "css":
  104. fallthrough
  105. case "assets":
  106. fallthrough
  107. case "js":
  108. s.fileServer.ServeHTTP(w, r)
  109. case "login":
  110. s.handleLogin(w, r)
  111. case "logout":
  112. s.handleLogout(w, r)
  113. case "register":
  114. s.handleRegister(w, r)
  115. case "checkEmail":
  116. s.handleCheckEmail(w, r)
  117. default:
  118. s.handleSecure(w, r, urlParts)
  119. }
  120. }
  121. func (s *Server) handleSecure(w http.ResponseWriter, r *http.Request, urlParts []string) {
  122. user, token := s.extractAuth(w, r)
  123. if !s.authenticator.Verify(user, token) {
  124. if r.Method == "GET" && urlParts[0] == "m" {
  125. http.Redirect(w, r, "/login", http.StatusTemporaryRedirect)
  126. } else {
  127. s.error(http.StatusUnauthorized, "You are not allowed to access this function", w)
  128. }
  129. return
  130. }
  131. switch urlParts[0] {
  132. case "m":
  133. s.handleMailboxRequest(w, r, user, urlParts)
  134. case "attachment":
  135. if len(urlParts) == 2 {
  136. s.handleAttachment(w, r, user, urlParts[1])
  137. } else {
  138. s.error(http.StatusBadRequest, "Invalid attachments request", w)
  139. }
  140. case "mail":
  141. if len(urlParts) == 2 {
  142. s.handleMailRequest(w, r, user, urlParts[1])
  143. }
  144. case "settings":
  145. s.handleSettings(w, r, user)
  146. case "admin":
  147. s.handleSecureZone(w, r, user)
  148. case "s":
  149. s.handleSecureZone(w, r, user)
  150. default:
  151. http.Redirect(w, r, "/m/0", http.StatusTemporaryRedirect)
  152. }
  153. }
  154. func (s *Server) handleAttachment(w http.ResponseWriter, r *http.Request, user, attachment string) {
  155. if user == "" {
  156. log.Printf("User could not be empty. Invalid usage of handleMailRequest")
  157. panic(nil)
  158. }
  159. if r.Method != "GET" {
  160. s.error(http.StatusNotImplemented, "You only may download attachments", w)
  161. return
  162. }
  163. if !s.storage.CheckAttachment(user, attachment) {
  164. s.error(http.StatusNotFound, "Attachment not found", w)
  165. return
  166. }
  167. s.attachmentsServer.ServeHTTP(w, r)
  168. }
  169. func (s *Server) extractAuth(w http.ResponseWriter, r *http.Request) (user, token string) {
  170. session, err := s.sessionStore.Get(r, CookieSessionToken)
  171. if err != nil {
  172. log.Printf("Unable to read user session %s\n", err)
  173. return
  174. }
  175. user, _ = session.Values["user"].(string)
  176. token, _ = session.Values["token"].(string)
  177. return
  178. }
  179. func (s *Server) error(code int, text string, w http.ResponseWriter) {
  180. w.WriteHeader(code)
  181. fmt.Fprint(w, s.templater.ExecuteError(&struct {
  182. Code int
  183. Text string
  184. Version string
  185. }{
  186. Code: code,
  187. Text: text,
  188. Version: common.Version,
  189. }))
  190. }