server.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  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. "strconv"
  31. auth "git.semlanik.org/semlanik/gostfix/auth"
  32. common "git.semlanik.org/semlanik/gostfix/common"
  33. db "git.semlanik.org/semlanik/gostfix/db"
  34. utils "git.semlanik.org/semlanik/gostfix/utils"
  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. templater *Templater
  56. sessionStore *sessions.CookieStore
  57. storage *db.Storage
  58. Notifier *webNotifier
  59. }
  60. func NewServer() *Server {
  61. storage, err := db.NewStorage()
  62. if err != nil {
  63. log.Fatalf("Unable to intialize mail storage %s", err)
  64. return nil
  65. }
  66. s := &Server{
  67. authenticator: auth.NewAuthenticator(),
  68. templater: NewTemplater("data/templates"),
  69. fileServer: http.FileServer(http.Dir("data")),
  70. sessionStore: sessions.NewCookieStore(make([]byte, 32)),
  71. storage: storage,
  72. Notifier: NewWebNotifier(),
  73. }
  74. return s
  75. }
  76. func (s *Server) Run() {
  77. http.Handle("/", s)
  78. log.Fatal(http.ListenAndServe(":65200", nil))
  79. }
  80. func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  81. fmt.Println(r.URL.Path)
  82. if utils.StartsWith(r.URL.Path, "/css/") ||
  83. utils.StartsWith(r.URL.Path, "/assets/") ||
  84. utils.StartsWith(r.URL.Path, "/js/") {
  85. s.fileServer.ServeHTTP(w, r)
  86. } else if cap := utils.RegExpUtilsInstance().MailboxFinder.FindStringSubmatch(r.URL.Path); len(cap) == 3 {
  87. user, token := s.extractAuth(w, r)
  88. if !s.authenticator.Verify(user, token) {
  89. s.logout(w, r)
  90. http.Redirect(w, r, "/login", http.StatusTemporaryRedirect)
  91. return
  92. }
  93. mailbox, err := strconv.Atoi(cap[1])
  94. if err != nil || mailbox < 0 {
  95. http.Redirect(w, r, "/m0", http.StatusTemporaryRedirect)
  96. return
  97. }
  98. path := cap[2]
  99. s.handleMailboxRequest(path, user, mailbox, w, r)
  100. } else {
  101. switch r.URL.Path {
  102. case "/login":
  103. s.handleLogin(w, r)
  104. case "/logout":
  105. s.handleLogout(w, r)
  106. case "/mail":
  107. fallthrough
  108. case "/setRead":
  109. fallthrough
  110. case "/remove":
  111. fallthrough
  112. case "/restore":
  113. fallthrough
  114. case "/delete":
  115. s.handleMailRequest(w, r)
  116. default:
  117. http.Redirect(w, r, "/m0", http.StatusTemporaryRedirect)
  118. }
  119. }
  120. }
  121. func (s *Server) handleLogin(w http.ResponseWriter, r *http.Request) {
  122. //Check passed in form login/password pair first
  123. if err := r.ParseForm(); err == nil {
  124. user := r.FormValue("user")
  125. password := r.FormValue("password")
  126. token, ok := s.authenticator.Authenticate(user, password)
  127. if ok {
  128. s.login(user, token, w, r)
  129. return
  130. }
  131. }
  132. //Check if user already logged in and entered login page accidently
  133. if s.authenticator.Verify(s.extractAuth(w, r)) {
  134. http.Redirect(w, r, "/m0", http.StatusTemporaryRedirect)
  135. return
  136. }
  137. //Otherwise make sure user logged out and show login page
  138. s.logout(w, r)
  139. fmt.Fprint(w, s.templater.ExecuteLogin(&struct {
  140. Version string
  141. }{common.Version}))
  142. }
  143. func (s *Server) handleLogout(w http.ResponseWriter, r *http.Request) {
  144. s.logout(w, r)
  145. http.Redirect(w, r, "/login", http.StatusTemporaryRedirect)
  146. }
  147. func (s *Server) logout(w http.ResponseWriter, r *http.Request) {
  148. fmt.Println("logout")
  149. session, _ := s.sessionStore.Get(r, CookieSessionToken)
  150. s.storage.RemoveToken(session.Values["user"].(string), session.Values["token"].(string))
  151. session.Values["user"] = ""
  152. session.Values["token"] = ""
  153. session.Save(r, w)
  154. }
  155. func (s *Server) login(user, token string, w http.ResponseWriter, r *http.Request) {
  156. session, _ := s.sessionStore.Get(r, CookieSessionToken)
  157. session.Values["user"] = user
  158. session.Values["token"] = token
  159. session.Save(r, w)
  160. http.Redirect(w, r, "/m0", http.StatusTemporaryRedirect)
  161. }
  162. func (s *Server) error(code int, text string, w http.ResponseWriter) {
  163. w.WriteHeader(code)
  164. fmt.Fprint(w, s.templater.ExecuteError(&struct {
  165. Code int
  166. Text string
  167. Version string
  168. }{
  169. Code: code,
  170. Text: text,
  171. Version: common.Version,
  172. }))
  173. }
  174. func (s *Server) extractAuth(w http.ResponseWriter, r *http.Request) (user, token string) {
  175. session, err := s.sessionStore.Get(r, CookieSessionToken)
  176. if err != nil {
  177. log.Printf("Unable to read user session %s\n", err)
  178. return
  179. }
  180. user, _ = session.Values["user"].(string)
  181. token, _ = session.Values["token"].(string)
  182. return
  183. }