server.go 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  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. template "html/template"
  29. "log"
  30. "net/http"
  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 {
  91. switch r.URL.Path {
  92. case "/login":
  93. s.handleLogin(w, r)
  94. case "/logout":
  95. s.handleLogout(w, r)
  96. case "/messageDetails":
  97. s.handleMessageDetails(w, r)
  98. case "/statusLine":
  99. s.handleStatusLine(w, r)
  100. default:
  101. s.handleMailbox(w, r)
  102. }
  103. }
  104. }
  105. func (s *Server) handleLogin(w http.ResponseWriter, r *http.Request) {
  106. //Check passed in form login/password pair first
  107. if err := r.ParseForm(); err == nil {
  108. user := r.FormValue("user")
  109. password := r.FormValue("password")
  110. token, ok := s.authenticator.Authenticate(user, password)
  111. if ok {
  112. s.login(user, token, w, r)
  113. return
  114. }
  115. }
  116. //Check if user already logged in and entered login page accidently
  117. if s.authenticator.Verify(s.extractAuth(w, r)) {
  118. http.Redirect(w, r, "/mailbox", http.StatusTemporaryRedirect)
  119. return
  120. }
  121. //Otherwise make sure user logged out and show login page
  122. s.logout(w, r)
  123. fmt.Fprint(w, s.templater.ExecuteLogin(&struct {
  124. Version string
  125. }{common.Version}))
  126. }
  127. func (s *Server) handleLogout(w http.ResponseWriter, r *http.Request) {
  128. s.logout(w, r)
  129. http.Redirect(w, r, "/login", http.StatusTemporaryRedirect)
  130. }
  131. func (s *Server) handleMessageDetails(w http.ResponseWriter, r *http.Request) {
  132. //TODO: Not implemented yet. Need database mail storage implemented first
  133. user, token := s.extractAuth(w, r)
  134. if !s.authenticator.Verify(user, token) {
  135. fmt.Fprint(w, "")
  136. return
  137. }
  138. fmt.Fprint(w, s.templater.ExecuteDetails(""))
  139. }
  140. func (s *Server) handleStatusLine(w http.ResponseWriter, r *http.Request) {
  141. //TODO: Not implemented yet. Need database mail storage implemented first
  142. user, token := s.extractAuth(w, r)
  143. if !s.authenticator.Verify(user, token) {
  144. fmt.Fprint(w, "")
  145. return
  146. }
  147. fmt.Fprint(w, s.templater.ExecuteStatusLine(&struct {
  148. Name string
  149. Read int
  150. Unread int
  151. }{
  152. Name: "No name", //TODO: read from database
  153. Read: 0, //TODO: read from database
  154. Unread: 0, //TODO: read from database
  155. }))
  156. }
  157. func (s *Server) handleMailbox(w http.ResponseWriter, r *http.Request) {
  158. user, token := s.extractAuth(w, r)
  159. if !s.authenticator.Verify(user, token) {
  160. s.logout(w, r)
  161. http.Redirect(w, r, "/login", http.StatusTemporaryRedirect)
  162. return
  163. }
  164. mailList, err := s.storage.MailList(user, user, "Inbox")
  165. if err != nil {
  166. s.error(http.StatusInternalServerError, "Couldn't read email database", w, r)
  167. return
  168. }
  169. fmt.Fprint(w, s.templater.ExecuteIndex(&struct {
  170. Folders template.HTML
  171. MailList template.HTML
  172. Version template.HTML
  173. }{
  174. MailList: template.HTML(s.templater.ExecuteMailList(mailList)),
  175. Folders: "Folders",
  176. Version: common.Version,
  177. }))
  178. }
  179. func (s *Server) logout(w http.ResponseWriter, r *http.Request) {
  180. fmt.Println("logout")
  181. session, _ := s.sessionStore.Get(r, CookieSessionToken)
  182. session.Values["user"] = ""
  183. session.Values["token"] = ""
  184. session.Save(r, w)
  185. }
  186. func (s *Server) login(user, token string, w http.ResponseWriter, r *http.Request) {
  187. session, _ := s.sessionStore.Get(r, CookieSessionToken)
  188. session.Values["user"] = user
  189. session.Values["token"] = token
  190. session.Save(r, w)
  191. http.Redirect(w, r, "/mailbox", http.StatusTemporaryRedirect)
  192. }
  193. func (s *Server) error(code int, text string, w http.ResponseWriter, r *http.Request) {
  194. w.WriteHeader(code)
  195. fmt.Fprint(w, s.templater.ExecuteError(&struct {
  196. Code int
  197. Text string
  198. Version string
  199. }{
  200. Code: code,
  201. Text: "Unable to access your mailbox. Please contact Administrator.",
  202. Version: common.Version,
  203. }))
  204. }
  205. func (s *Server) extractAuth(w http.ResponseWriter, r *http.Request) (user, token string) {
  206. session, err := s.sessionStore.Get(r, CookieSessionToken)
  207. if err != nil {
  208. log.Printf("Unable to read user session %s\n", err)
  209. return
  210. }
  211. user, _ = session.Values["user"].(string)
  212. token, _ = session.Values["token"].(string)
  213. return
  214. }