server.go 8.6 KB

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