server.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  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. s := &Server{
  70. authenticator: auth.NewAuthenticator(),
  71. templater: NewTemplater("data/templates"),
  72. fileServer: http.FileServer(http.Dir("data")),
  73. sessionStore: sessions.NewCookieStore(make([]byte, 32)),
  74. storage: storage,
  75. Notifier: NewWebNotifier(),
  76. scanner: scanner,
  77. }
  78. return s
  79. }
  80. func (s *Server) Run() {
  81. http.Handle("/", s)
  82. log.Fatal(http.ListenAndServe(":65200", nil))
  83. }
  84. func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  85. fmt.Println(r.URL.Path)
  86. if utils.StartsWith(r.URL.Path, "/css/") ||
  87. utils.StartsWith(r.URL.Path, "/assets/") ||
  88. utils.StartsWith(r.URL.Path, "/js/") {
  89. s.fileServer.ServeHTTP(w, r)
  90. } else if cap := utils.RegExpUtilsInstance().MailboxFinder.FindStringSubmatch(r.URL.Path); len(cap) == 3 {
  91. user, token := s.extractAuth(w, r)
  92. if !s.authenticator.Verify(user, token) {
  93. s.logout(w, r)
  94. http.Redirect(w, r, "/login", http.StatusTemporaryRedirect)
  95. return
  96. }
  97. mailbox, err := strconv.Atoi(cap[1])
  98. if err != nil || mailbox < 0 {
  99. http.Redirect(w, r, "/m0", http.StatusTemporaryRedirect)
  100. return
  101. }
  102. path := cap[2]
  103. s.handleMailboxRequest(path, user, mailbox, w, r)
  104. } else {
  105. switch r.URL.Path {
  106. case "/login":
  107. s.handleLogin(w, r)
  108. case "/logout":
  109. s.handleLogout(w, r)
  110. case "/register":
  111. s.handleRegister(w, r)
  112. case "/checkEmail":
  113. s.handleCheckEmail(w, r)
  114. case "/mail":
  115. fallthrough
  116. case "/setRead":
  117. fallthrough
  118. case "/remove":
  119. fallthrough
  120. case "/restore":
  121. fallthrough
  122. case "/delete":
  123. s.handleMailRequest(w, r)
  124. default:
  125. http.Redirect(w, r, "/m0", http.StatusTemporaryRedirect)
  126. }
  127. }
  128. }
  129. func (s *Server) handleRegister(w http.ResponseWriter, r *http.Request) {
  130. if !config.ConfigInstance().RegistrationEnabled {
  131. s.error(http.StatusNotImplemented, "Registration is disabled on this server", w)
  132. return
  133. }
  134. if err := r.ParseForm(); err == nil {
  135. user := r.FormValue("user")
  136. password := r.FormValue("password")
  137. fullname := r.FormValue("fullname")
  138. if user != "" && password != "" && fullname != "" {
  139. ok, email := s.checkEmail(user)
  140. if ok && len(password) < 128 && len(fullname) < 128 && utils.RegExpUtilsInstance().FullnameChecker.MatchString(fullname) {
  141. err := s.storage.AddUser(email, password, fullname)
  142. if err != nil {
  143. log.Println(err.Error())
  144. s.error(http.StatusInternalServerError, "Unable to create user", w)
  145. return
  146. }
  147. s.scanner.Reconfigure()
  148. token, _ := s.authenticator.Authenticate(email, password)
  149. s.login(email, token, w, r)
  150. return
  151. }
  152. }
  153. }
  154. fmt.Fprint(w, s.templater.ExecuteRegister(&struct {
  155. Version string
  156. Domain string
  157. }{common.Version, config.ConfigInstance().MyDomain}))
  158. }
  159. func (s *Server) handleLogin(w http.ResponseWriter, r *http.Request) {
  160. //Check passed in form login/password pair first
  161. if err := r.ParseForm(); err == nil {
  162. user := r.FormValue("user")
  163. password := r.FormValue("password")
  164. token, ok := s.authenticator.Authenticate(user, password)
  165. if ok {
  166. s.login(user, token, w, r)
  167. return
  168. }
  169. }
  170. //Check if user already logged in and entered login page accidently
  171. if s.authenticator.Verify(s.extractAuth(w, r)) {
  172. http.Redirect(w, r, "/m0", http.StatusTemporaryRedirect)
  173. return
  174. }
  175. var signupTemplate template.HTML
  176. if config.ConfigInstance().RegistrationEnabled {
  177. signupTemplate = template.HTML(s.templater.ExecuteSignup(""))
  178. } else {
  179. signupTemplate = ""
  180. }
  181. //Otherwise make sure user logged out and show login page
  182. s.logout(w, r)
  183. fmt.Fprint(w, s.templater.ExecuteLogin(&struct {
  184. Version string
  185. Signup template.HTML
  186. }{common.Version, signupTemplate}))
  187. }
  188. func (s *Server) handleLogout(w http.ResponseWriter, r *http.Request) {
  189. s.logout(w, r)
  190. http.Redirect(w, r, "/login", http.StatusTemporaryRedirect)
  191. }
  192. func (s *Server) handleCheckEmail(w http.ResponseWriter, r *http.Request) {
  193. if err := r.ParseForm(); err == nil {
  194. if ok, _ := s.checkEmail(r.FormValue("user")); ok {
  195. w.Write([]byte{0})
  196. return
  197. }
  198. s.error(http.StatusNotAcceptable, "Email exists", w)
  199. return
  200. }
  201. s.error(http.StatusBadRequest, "Invalid arguments", w)
  202. return
  203. }
  204. func (s *Server) checkEmail(user string) (bool, string) {
  205. email := user + "@" + config.ConfigInstance().MyDomain
  206. return utils.RegExpUtilsInstance().EmailChecker.MatchString(email) && !s.storage.CheckEmailExists(email), email
  207. }
  208. func (s *Server) logout(w http.ResponseWriter, r *http.Request) {
  209. fmt.Println("logout")
  210. session, err := s.sessionStore.Get(r, CookieSessionToken)
  211. if err == nil {
  212. if session.Values["user"] != nil && session.Values["token"] != nil {
  213. s.storage.RemoveToken(session.Values["user"].(string), session.Values["token"].(string))
  214. }
  215. session.Values["user"] = ""
  216. session.Values["token"] = ""
  217. session.Save(r, w)
  218. }
  219. }
  220. func (s *Server) login(user, token string, w http.ResponseWriter, r *http.Request) {
  221. session, _ := s.sessionStore.Get(r, CookieSessionToken)
  222. session.Values["user"] = user
  223. session.Values["token"] = token
  224. session.Save(r, w)
  225. http.Redirect(w, r, "/m0", http.StatusTemporaryRedirect)
  226. }
  227. func (s *Server) error(code int, text string, w http.ResponseWriter) {
  228. w.WriteHeader(code)
  229. fmt.Fprint(w, s.templater.ExecuteError(&struct {
  230. Code int
  231. Text string
  232. Version string
  233. }{
  234. Code: code,
  235. Text: text,
  236. Version: common.Version,
  237. }))
  238. }
  239. func (s *Server) extractAuth(w http.ResponseWriter, r *http.Request) (user, token string) {
  240. session, err := s.sessionStore.Get(r, CookieSessionToken)
  241. if err != nil {
  242. log.Printf("Unable to read user session %s\n", err)
  243. return
  244. }
  245. user, _ = session.Values["user"].(string)
  246. token, _ = session.Values["token"].(string)
  247. return
  248. }