server.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  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. func NewEmail() *common.Mail {
  53. return &common.Mail{
  54. Header: &common.MailHeader{},
  55. Body: &common.MailBody{},
  56. }
  57. }
  58. type Server struct {
  59. authenticator *auth.Authenticator
  60. fileServer http.Handler
  61. templater *Templater
  62. sessionStore *sessions.CookieStore
  63. storage *db.Storage
  64. }
  65. func NewServer() *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. s := &Server{
  72. authenticator: auth.NewAuthenticator(),
  73. templater: NewTemplater("data/templates"),
  74. fileServer: http.FileServer(http.Dir("data")),
  75. sessionStore: sessions.NewCookieStore(make([]byte, 32)),
  76. storage: storage,
  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 "/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) handleLogin(w http.ResponseWriter, r *http.Request) {
  126. //Check passed in form login/password pair first
  127. if err := r.ParseForm(); err == nil {
  128. user := r.FormValue("user")
  129. password := r.FormValue("password")
  130. token, ok := s.authenticator.Authenticate(user, password)
  131. if ok {
  132. s.login(user, token, w, r)
  133. return
  134. }
  135. }
  136. //Check if user already logged in and entered login page accidently
  137. if s.authenticator.Verify(s.extractAuth(w, r)) {
  138. http.Redirect(w, r, "/m0", http.StatusTemporaryRedirect)
  139. return
  140. }
  141. //Otherwise make sure user logged out and show login page
  142. s.logout(w, r)
  143. fmt.Fprint(w, s.templater.ExecuteLogin(&struct {
  144. Version string
  145. }{common.Version}))
  146. }
  147. func (s *Server) handleLogout(w http.ResponseWriter, r *http.Request) {
  148. s.logout(w, r)
  149. http.Redirect(w, r, "/login", http.StatusTemporaryRedirect)
  150. }
  151. func (s *Server) logout(w http.ResponseWriter, r *http.Request) {
  152. fmt.Println("logout")
  153. session, _ := s.sessionStore.Get(r, CookieSessionToken)
  154. s.storage.RemoveToken(session.Values["user"].(string), session.Values["token"].(string))
  155. session.Values["user"] = ""
  156. session.Values["token"] = ""
  157. session.Save(r, w)
  158. }
  159. func (s *Server) login(user, token string, w http.ResponseWriter, r *http.Request) {
  160. session, _ := s.sessionStore.Get(r, CookieSessionToken)
  161. session.Values["user"] = user
  162. session.Values["token"] = token
  163. session.Save(r, w)
  164. http.Redirect(w, r, "/m0", http.StatusTemporaryRedirect)
  165. }
  166. func (s *Server) error(code int, text string, w http.ResponseWriter) {
  167. w.WriteHeader(code)
  168. fmt.Fprint(w, s.templater.ExecuteError(&struct {
  169. Code int
  170. Text string
  171. Version string
  172. }{
  173. Code: code,
  174. Text: text,
  175. Version: common.Version,
  176. }))
  177. }
  178. func (s *Server) extractAuth(w http.ResponseWriter, r *http.Request) (user, token string) {
  179. session, err := s.sessionStore.Get(r, CookieSessionToken)
  180. if err != nil {
  181. log.Printf("Unable to read user session %s\n", err)
  182. return
  183. }
  184. user, _ = session.Values["user"].(string)
  185. token, _ = session.Values["token"].(string)
  186. return
  187. }