server.go 6.5 KB

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