server.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  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. return s
  84. }
  85. func (s *Server) Run() {
  86. http.Handle("/", s)
  87. log.Fatal(http.ListenAndServe(":"+config.ConfigInstance().WebPort, nil))
  88. }
  89. func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  90. log.Printf("%s %s", r.Method, r.URL.Path)
  91. urlParts := strings.Split(r.URL.Path, "/")[1:]
  92. if len(urlParts) == 0 || urlParts[0] == "" {
  93. http.Redirect(w, r, "/m/0", http.StatusTemporaryRedirect)
  94. return
  95. }
  96. switch urlParts[0] {
  97. case "css":
  98. fallthrough
  99. case "assets":
  100. fallthrough
  101. case "js":
  102. s.fileServer.ServeHTTP(w, r)
  103. case "login":
  104. s.handleLogin(w, r)
  105. case "logout":
  106. s.handleLogout(w, r)
  107. case "register":
  108. s.handleRegister(w, r)
  109. case "checkEmail":
  110. s.handleCheckEmail(w, r)
  111. default:
  112. s.handleSecure(w, r, urlParts)
  113. }
  114. }
  115. func (s *Server) handleSecure(w http.ResponseWriter, r *http.Request, urlParts []string) {
  116. user, token := s.extractAuth(w, r)
  117. if !s.authenticator.Verify(user, token) {
  118. if r.Method == "GET" && urlParts[0] == "m" {
  119. http.Redirect(w, r, "/login", http.StatusTemporaryRedirect)
  120. } else {
  121. s.error(http.StatusUnauthorized, "You are not allowed to access this function", w)
  122. }
  123. return
  124. }
  125. switch urlParts[0] {
  126. case "m":
  127. s.handleMailboxRequest(w, r, user, urlParts)
  128. case "attachment":
  129. if len(urlParts) == 2 {
  130. s.handleAttachment(w, r, user, urlParts[1])
  131. } else {
  132. s.error(http.StatusBadRequest, "Invalid attachments request", w)
  133. }
  134. case "mail":
  135. if len(urlParts) == 2 {
  136. s.handleMailRequest(w, r, user, urlParts[1])
  137. } else {
  138. //TODO: return mail list here
  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. }