server.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  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 "/delete":
  117. s.handleMailRequest(w, r)
  118. default:
  119. http.Redirect(w, r, "/m0", http.StatusTemporaryRedirect)
  120. }
  121. }
  122. }
  123. func (s *Server) handleLogin(w http.ResponseWriter, r *http.Request) {
  124. //Check passed in form login/password pair first
  125. if err := r.ParseForm(); err == nil {
  126. user := r.FormValue("user")
  127. password := r.FormValue("password")
  128. token, ok := s.authenticator.Authenticate(user, password)
  129. if ok {
  130. s.login(user, token, w, r)
  131. return
  132. }
  133. }
  134. //Check if user already logged in and entered login page accidently
  135. if s.authenticator.Verify(s.extractAuth(w, r)) {
  136. http.Redirect(w, r, "/m0", http.StatusTemporaryRedirect)
  137. return
  138. }
  139. //Otherwise make sure user logged out and show login page
  140. s.logout(w, r)
  141. fmt.Fprint(w, s.templater.ExecuteLogin(&struct {
  142. Version string
  143. }{common.Version}))
  144. }
  145. func (s *Server) handleLogout(w http.ResponseWriter, r *http.Request) {
  146. s.logout(w, r)
  147. http.Redirect(w, r, "/login", http.StatusTemporaryRedirect)
  148. }
  149. func (s *Server) logout(w http.ResponseWriter, r *http.Request) {
  150. fmt.Println("logout")
  151. session, _ := s.sessionStore.Get(r, CookieSessionToken)
  152. session.Values["user"] = ""
  153. session.Values["token"] = ""
  154. session.Save(r, w)
  155. }
  156. func (s *Server) login(user, token string, w http.ResponseWriter, r *http.Request) {
  157. session, _ := s.sessionStore.Get(r, CookieSessionToken)
  158. session.Values["user"] = user
  159. session.Values["token"] = token
  160. session.Save(r, w)
  161. http.Redirect(w, r, "/m0", http.StatusTemporaryRedirect)
  162. }
  163. func (s *Server) error(code int, text string, w http.ResponseWriter) {
  164. w.WriteHeader(code)
  165. fmt.Fprint(w, s.templater.ExecuteError(&struct {
  166. Code int
  167. Text string
  168. Version string
  169. }{
  170. Code: code,
  171. Text: text,
  172. Version: common.Version,
  173. }))
  174. }
  175. func (s *Server) extractAuth(w http.ResponseWriter, r *http.Request) (user, token string) {
  176. session, err := s.sessionStore.Get(r, CookieSessionToken)
  177. if err != nil {
  178. log.Printf("Unable to read user session %s\n", err)
  179. return
  180. }
  181. user, _ = session.Values["user"].(string)
  182. token, _ = session.Values["token"].(string)
  183. return
  184. }