server.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  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. "html/template"
  29. "log"
  30. "net/http"
  31. "strconv"
  32. auth "git.semlanik.org/semlanik/gostfix/auth"
  33. common "git.semlanik.org/semlanik/gostfix/common"
  34. "git.semlanik.org/semlanik/gostfix/config"
  35. db "git.semlanik.org/semlanik/gostfix/db"
  36. utils "git.semlanik.org/semlanik/gostfix/utils"
  37. sessions "github.com/gorilla/sessions"
  38. )
  39. const (
  40. StateHeaderScan = iota
  41. StateBodyScan
  42. StateContentScan
  43. )
  44. const (
  45. AtLeastOneHeaderMask = 1 << iota
  46. FromHeaderMask
  47. DateHeaderMask
  48. ToHeaderMask
  49. AllHeaderMask = 15
  50. )
  51. const (
  52. CookieSessionToken = "gostfix_session"
  53. )
  54. type Server struct {
  55. authenticator *auth.Authenticator
  56. fileServer http.Handler
  57. templater *Templater
  58. sessionStore *sessions.CookieStore
  59. storage *db.Storage
  60. Notifier *webNotifier
  61. scanner common.Scanner
  62. }
  63. func NewServer(scanner common.Scanner) *Server {
  64. storage, err := db.NewStorage()
  65. if err != nil {
  66. log.Fatalf("Unable to intialize mail storage %s", err)
  67. return nil
  68. }
  69. authenticator, err := auth.NewAuthenticator()
  70. if err != nil {
  71. log.Fatalf("Unable to intialize authenticator %s", err)
  72. return nil
  73. }
  74. s := &Server{
  75. authenticator: authenticator,
  76. templater: NewTemplater("data/templates"),
  77. fileServer: http.FileServer(http.Dir("data")),
  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(":65200", nil))
  88. }
  89. func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  90. fmt.Println(r.URL.Path)
  91. if utils.StartsWith(r.URL.Path, "/css/") ||
  92. utils.StartsWith(r.URL.Path, "/assets/") ||
  93. utils.StartsWith(r.URL.Path, "/js/") {
  94. s.fileServer.ServeHTTP(w, r)
  95. } else if cap := utils.RegExpUtilsInstance().MailboxFinder.FindStringSubmatch(r.URL.Path); len(cap) == 3 {
  96. user, token := s.extractAuth(w, r)
  97. if !s.authenticator.Verify(user, token) {
  98. s.logout(w, r)
  99. http.Redirect(w, r, "/login", http.StatusTemporaryRedirect)
  100. return
  101. }
  102. mailbox, err := strconv.Atoi(cap[1])
  103. if err != nil || mailbox < 0 {
  104. http.Redirect(w, r, "/m0", http.StatusTemporaryRedirect)
  105. return
  106. }
  107. path := cap[2]
  108. s.handleMailboxRequest(path, user, mailbox, w, r)
  109. } else {
  110. switch r.URL.Path {
  111. case "/login":
  112. s.handleLogin(w, r)
  113. case "/logout":
  114. s.handleLogout(w, r)
  115. case "/register":
  116. s.handleRegister(w, r)
  117. case "/checkEmail":
  118. s.handleCheckEmail(w, r)
  119. case "/mail":
  120. fallthrough
  121. case "/setRead":
  122. fallthrough
  123. case "/remove":
  124. fallthrough
  125. case "/restore":
  126. fallthrough
  127. case "/delete":
  128. s.handleMailRequest(w, r)
  129. case "/settings":
  130. fallthrough
  131. case "/update":
  132. fallthrough
  133. case "/admin":
  134. s.handleSecureZone(w, r)
  135. default:
  136. http.Redirect(w, r, "/m0", http.StatusTemporaryRedirect)
  137. }
  138. }
  139. }
  140. func (s *Server) handleRegister(w http.ResponseWriter, r *http.Request) {
  141. // if session, err := s.sessionStore.Get(r, CookieSessionToken); err == nil && session.Values["user"] != nil && session.Values["token"] != nil {
  142. // http.Redirect(w, r, "/m0", http.StatusTemporaryRedirect)
  143. // return
  144. // }
  145. if !config.ConfigInstance().RegistrationEnabled {
  146. s.error(http.StatusNotImplemented, "Registration is disabled on this server", w)
  147. return
  148. }
  149. if err := r.ParseForm(); err == nil {
  150. user := r.FormValue("user")
  151. password := r.FormValue("password")
  152. fullName := r.FormValue("fullName")
  153. if user != "" && password != "" && fullName != "" {
  154. ok, email := s.checkEmail(user)
  155. if ok && len(password) < 128 && len(fullName) < 128 && utils.RegExpUtilsInstance().FullNameChecker.MatchString(fullName) {
  156. err := s.storage.AddUser(email, password, fullName)
  157. if err != nil {
  158. log.Println(err.Error())
  159. s.error(http.StatusInternalServerError, "Unable to create user", w)
  160. return
  161. }
  162. s.scanner.Reconfigure()
  163. token, _ := s.authenticator.Login(email, password)
  164. s.login(email, token, w, r)
  165. return
  166. }
  167. }
  168. }
  169. fmt.Fprint(w, s.templater.ExecuteRegister(&struct {
  170. Version string
  171. Domain string
  172. }{common.Version, config.ConfigInstance().MyDomain}))
  173. }
  174. func (s *Server) handleLogin(w http.ResponseWriter, r *http.Request) {
  175. //Check passed in form login/password pair first
  176. if err := r.ParseForm(); err == nil {
  177. user := r.FormValue("user")
  178. password := r.FormValue("password")
  179. token, ok := s.authenticator.Login(user, password)
  180. if ok {
  181. s.login(user, token, w, r)
  182. return
  183. }
  184. }
  185. //Check if user already logged in and entered login page accidently
  186. if s.authenticator.Verify(s.extractAuth(w, r)) {
  187. http.Redirect(w, r, "/m0", http.StatusTemporaryRedirect)
  188. return
  189. }
  190. var signupTemplate template.HTML
  191. if config.ConfigInstance().RegistrationEnabled {
  192. signupTemplate = template.HTML(s.templater.ExecuteSignup(""))
  193. } else {
  194. signupTemplate = ""
  195. }
  196. //Otherwise make sure user logged out and show login page
  197. s.logout(w, r)
  198. fmt.Fprint(w, s.templater.ExecuteLogin(&struct {
  199. Version string
  200. Signup template.HTML
  201. }{common.Version, signupTemplate}))
  202. }
  203. func (s *Server) handleLogout(w http.ResponseWriter, r *http.Request) {
  204. s.logout(w, r)
  205. http.Redirect(w, r, "/login", http.StatusTemporaryRedirect)
  206. }
  207. func (s *Server) handleCheckEmail(w http.ResponseWriter, r *http.Request) {
  208. if err := r.ParseForm(); err == nil {
  209. if ok, _ := s.checkEmail(r.FormValue("user")); ok {
  210. w.Write([]byte{0})
  211. return
  212. }
  213. s.error(http.StatusNotAcceptable, "Email exists", w)
  214. return
  215. }
  216. s.error(http.StatusBadRequest, "Invalid arguments", w)
  217. return
  218. }
  219. func (s *Server) checkEmail(user string) (bool, string) {
  220. email := user + "@" + config.ConfigInstance().MyDomain
  221. return utils.RegExpUtilsInstance().EmailChecker.MatchString(email) && !s.storage.CheckEmailExists(email), email
  222. }
  223. func (s *Server) logout(w http.ResponseWriter, r *http.Request) {
  224. session, err := s.sessionStore.Get(r, CookieSessionToken)
  225. if err == nil {
  226. if session.Values["user"] != nil && session.Values["token"] != nil {
  227. s.authenticator.Logout(session.Values["user"].(string), session.Values["token"].(string))
  228. }
  229. session.Values["user"] = ""
  230. session.Values["token"] = ""
  231. session.Save(r, w)
  232. }
  233. }
  234. func (s *Server) login(user, token string, w http.ResponseWriter, r *http.Request) {
  235. session, _ := s.sessionStore.Get(r, CookieSessionToken)
  236. session.Values["user"] = user
  237. session.Values["token"] = token
  238. session.Save(r, w)
  239. http.Redirect(w, r, "/m0", http.StatusTemporaryRedirect)
  240. }
  241. func (s *Server) error(code int, text string, w http.ResponseWriter) {
  242. w.WriteHeader(code)
  243. fmt.Fprint(w, s.templater.ExecuteError(&struct {
  244. Code int
  245. Text string
  246. Version string
  247. }{
  248. Code: code,
  249. Text: text,
  250. Version: common.Version,
  251. }))
  252. }
  253. func (s *Server) extractAuth(w http.ResponseWriter, r *http.Request) (user, token string) {
  254. session, err := s.sessionStore.Get(r, CookieSessionToken)
  255. if err != nil {
  256. log.Printf("Unable to read user session %s\n", err)
  257. return
  258. }
  259. user, _ = session.Values["user"].(string)
  260. token, _ = session.Values["token"].(string)
  261. return
  262. }