server.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  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. sessions "github.com/gorilla/sessions"
  36. )
  37. const (
  38. StateHeaderScan = iota
  39. StateBodyScan
  40. StateContentScan
  41. )
  42. const (
  43. AtLeastOneHeaderMask = 1 << iota
  44. FromHeaderMask
  45. DateHeaderMask
  46. ToHeaderMask
  47. AllHeaderMask = 15
  48. )
  49. const (
  50. CookieSessionToken = "gostfix_session"
  51. )
  52. type Server struct {
  53. authenticator *auth.Authenticator
  54. fileServer http.Handler
  55. attachmentsServer http.Handler
  56. templater *Templater
  57. sessionStore *sessions.CookieStore
  58. storage *db.Storage
  59. notifier *webNotifier
  60. scanner common.Scanner
  61. }
  62. func NewServer(scanner common.Scanner) *Server {
  63. storage, err := db.NewStorage()
  64. if err != nil {
  65. log.Fatalf("Unable to intialize mail storage %s", err)
  66. return nil
  67. }
  68. authenticator, err := auth.NewAuthenticator()
  69. if err != nil {
  70. log.Fatalf("Unable to intialize authenticator %s", err)
  71. return nil
  72. }
  73. s := &Server{
  74. authenticator: authenticator,
  75. templater: NewTemplater("data/templates"),
  76. fileServer: http.FileServer(http.Dir("data")),
  77. attachmentsServer: http.StripPrefix("/attachment/", http.FileServer(http.Dir(config.ConfigInstance().AttachmentsPath))),
  78. sessionStore: sessions.NewCookieStore(make([]byte, 32)),
  79. storage: storage,
  80. notifier: NewWebNotifier(),
  81. scanner: scanner,
  82. }
  83. s.notifier.server = s
  84. s.storage.RegisterNotifier(s.notifier)
  85. return s
  86. }
  87. func (s *Server) Run() {
  88. http.Handle("/", s)
  89. log.Fatal(http.ListenAndServe(":"+config.ConfigInstance().WebPort, nil))
  90. }
  91. func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  92. log.Printf("%s %s", r.Method, r.URL.Path)
  93. urlParts := strings.Split(r.URL.Path, "/")[1:]
  94. if len(urlParts) == 0 || urlParts[0] == "" {
  95. http.Redirect(w, r, "/m/0", http.StatusTemporaryRedirect)
  96. return
  97. }
  98. switch urlParts[0] {
  99. case "css":
  100. fallthrough
  101. case "assets":
  102. fallthrough
  103. case "js":
  104. s.fileServer.ServeHTTP(w, r)
  105. case "login":
  106. s.handleLogin(w, r)
  107. case "logout":
  108. s.handleLogout(w, r)
  109. case "register":
  110. s.handleRegister(w, r)
  111. case "checkEmail":
  112. s.handleCheckEmail(w, r)
  113. default:
  114. s.handleSecure(w, r, urlParts)
  115. }
  116. }
  117. func (s *Server) handleSecure(w http.ResponseWriter, r *http.Request, urlParts []string) {
  118. user, token := s.extractAuth(w, r)
  119. if !s.authenticator.Verify(user, token) {
  120. if r.Method == "GET" && urlParts[0] == "m" {
  121. http.Redirect(w, r, "/login", http.StatusTemporaryRedirect)
  122. } else {
  123. s.error(http.StatusUnauthorized, "You are not allowed to access this function", w)
  124. }
  125. return
  126. }
  127. switch urlParts[0] {
  128. case "m":
  129. s.handleMailboxRequest(w, r, user, urlParts)
  130. case "attachment":
  131. if len(urlParts) == 2 {
  132. s.handleAttachment(w, r, user, urlParts[1])
  133. } else {
  134. s.error(http.StatusBadRequest, "Invalid attachments request", w)
  135. }
  136. case "mail":
  137. if len(urlParts) == 2 {
  138. s.handleMailRequest(w, r, user, urlParts[1])
  139. }
  140. case "settings":
  141. s.handleSettings(w, r, user)
  142. case "admin":
  143. s.handleSecureZone(w, r, user)
  144. default:
  145. http.Redirect(w, r, "/m/0", http.StatusTemporaryRedirect)
  146. }
  147. }
  148. func (s *Server) handleAttachment(w http.ResponseWriter, r *http.Request, user, attachment string) {
  149. if user == "" {
  150. log.Printf("User could not be empty. Invalid usage of handleMailRequest")
  151. panic(nil)
  152. }
  153. if r.Method != "GET" {
  154. s.error(http.StatusNotImplemented, "You only may download attachments", w)
  155. return
  156. }
  157. if !s.storage.CheckAttachment(user, attachment) {
  158. s.error(http.StatusNotFound, "Attachment not found", w)
  159. return
  160. }
  161. s.attachmentsServer.ServeHTTP(w, r)
  162. }
  163. func (s *Server) extractAuth(w http.ResponseWriter, r *http.Request) (user, token string) {
  164. session, err := s.sessionStore.Get(r, CookieSessionToken)
  165. if err != nil {
  166. log.Printf("Unable to read user session %s\n", err)
  167. return
  168. }
  169. user, _ = session.Values["user"].(string)
  170. token, _ = session.Values["token"].(string)
  171. return
  172. }
  173. func (s *Server) error(code int, text string, w http.ResponseWriter) {
  174. w.WriteHeader(code)
  175. fmt.Fprint(w, s.templater.ExecuteError(&struct {
  176. Code int
  177. Text string
  178. Version string
  179. }{
  180. Code: code,
  181. Text: text,
  182. Version: common.Version,
  183. }))
  184. }