server.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  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. case "/":
  101. s.handleMailbox(w, r)
  102. case "/mailbox":
  103. s.handleMailbox(w, r)
  104. case "/setRead":
  105. s.handleSetRead(w, r)
  106. case "/remove":
  107. s.handleRemove(w, r)
  108. case "/messageList":
  109. s.handleMessageList(w, r)
  110. default:
  111. s.error(http.StatusBadRequest, "Invalid request", w, r)
  112. }
  113. }
  114. }
  115. func (s *Server) handleLogin(w http.ResponseWriter, r *http.Request) {
  116. //Check passed in form login/password pair first
  117. if err := r.ParseForm(); err == nil {
  118. user := r.FormValue("user")
  119. password := r.FormValue("password")
  120. token, ok := s.authenticator.Authenticate(user, password)
  121. if ok {
  122. s.login(user, token, w, r)
  123. return
  124. }
  125. }
  126. //Check if user already logged in and entered login page accidently
  127. if s.authenticator.Verify(s.extractAuth(w, r)) {
  128. http.Redirect(w, r, "/mailbox", http.StatusTemporaryRedirect)
  129. return
  130. }
  131. //Otherwise make sure user logged out and show login page
  132. s.logout(w, r)
  133. fmt.Fprint(w, s.templater.ExecuteLogin(&struct {
  134. Version string
  135. }{common.Version}))
  136. }
  137. func (s *Server) handleLogout(w http.ResponseWriter, r *http.Request) {
  138. s.logout(w, r)
  139. http.Redirect(w, r, "/login", http.StatusTemporaryRedirect)
  140. }
  141. func (s *Server) handleMessageDetails(w http.ResponseWriter, r *http.Request) {
  142. //TODO: Not implemented yet. Need database mail storage implemented first
  143. user, token := s.extractAuth(w, r)
  144. if !s.authenticator.Verify(user, token) {
  145. fmt.Fprint(w, "")
  146. return
  147. }
  148. messageId := r.FormValue("messageId")
  149. mail, err := s.storage.GetMail(user, messageId)
  150. if err != nil {
  151. s.error(http.StatusInternalServerError, "Unable to read message", w, r)
  152. return
  153. }
  154. s.storage.SetRead(user, messageId, true)
  155. fmt.Fprint(w, s.templater.ExecuteDetails(&struct {
  156. From string
  157. To string
  158. Subject string
  159. Text template.HTML
  160. MessageId string
  161. Read bool
  162. }{
  163. From: mail.Header.From,
  164. To: mail.Header.To,
  165. Subject: mail.Header.Subject,
  166. Text: template.HTML(mail.Body.RichText),
  167. MessageId: messageId,
  168. }))
  169. }
  170. func (s *Server) handleStatusLine(w http.ResponseWriter, r *http.Request) {
  171. //TODO: Not implemented yet. Need database mail storage implemented first
  172. user, token := s.extractAuth(w, r)
  173. if !s.authenticator.Verify(user, token) {
  174. fmt.Fprint(w, "")
  175. return
  176. }
  177. info, err := s.storage.GetUserInfo(user)
  178. if err != nil {
  179. s.error(http.StatusInternalServerError, "Could not read user info", w, r)
  180. return
  181. }
  182. unread, total, err := s.storage.GetEmailStats(user, user)
  183. if err != nil {
  184. s.error(http.StatusInternalServerError, "Could not read user stats", w, r)
  185. return
  186. }
  187. fmt.Fprint(w, s.templater.ExecuteStatusLine(&struct {
  188. Name string
  189. Unread int
  190. Total int
  191. }{
  192. Name: info.FullName,
  193. Unread: unread,
  194. Total: total,
  195. }))
  196. }
  197. func (s *Server) handleMailbox(w http.ResponseWriter, r *http.Request) {
  198. user, token := s.extractAuth(w, r)
  199. if !s.authenticator.Verify(user, token) {
  200. s.logout(w, r)
  201. http.Redirect(w, r, "/login", http.StatusTemporaryRedirect)
  202. return
  203. }
  204. mailList, err := s.storage.MailList(user, user, "Inbox", common.Frame{Skip: 0, Limit: 0})
  205. if err != nil {
  206. s.error(http.StatusInternalServerError, "Couldn't read email database", w, r)
  207. return
  208. }
  209. fmt.Fprint(w, s.templater.ExecuteIndex(&struct {
  210. Folders template.HTML
  211. MailList template.HTML
  212. Version template.HTML
  213. }{
  214. MailList: template.HTML(s.templater.ExecuteMailList(mailList)),
  215. Folders: "Folders",
  216. Version: common.Version,
  217. }))
  218. }
  219. func (s *Server) handleSetRead(w http.ResponseWriter, r *http.Request) {
  220. user, token := s.extractAuth(w, r)
  221. if !s.authenticator.Verify(user, token) {
  222. s.logout(w, r)
  223. s.error(http.StatusUnauthorized, "Unknown user credentials", w, r)
  224. return
  225. }
  226. read := r.FormValue("read") == "true"
  227. messageId := r.FormValue("messageId")
  228. fmt.Printf("SetRead %s, %s, %v\n", user, messageId, read)
  229. s.storage.SetRead(user, messageId, read)
  230. w.WriteHeader(http.StatusOK)
  231. fmt.Fprint(w, "Test")
  232. }
  233. func (s *Server) handleRemove(w http.ResponseWriter, r *http.Request) {
  234. user, token := s.extractAuth(w, r)
  235. if !s.authenticator.Verify(user, token) {
  236. s.logout(w, r)
  237. s.error(http.StatusUnauthorized, "Unknown user credentials", w, r)
  238. return
  239. }
  240. messageId := r.FormValue("messageId")
  241. s.storage.RemoveMail(user, messageId)
  242. }
  243. func (s *Server) handleMessageList(w http.ResponseWriter, r *http.Request) {
  244. user, token := s.extractAuth(w, r)
  245. if !s.authenticator.Verify(user, token) {
  246. s.logout(w, r)
  247. http.Redirect(w, r, "/login", http.StatusTemporaryRedirect)
  248. return
  249. }
  250. mailList, err := s.storage.MailList(user, user, "Inbox", common.Frame{Skip: 0, Limit: 0})
  251. if err != nil {
  252. s.error(http.StatusInternalServerError, "Couldn't read email database", w, r)
  253. return
  254. }
  255. fmt.Fprint(w, s.templater.ExecuteMailList(mailList))
  256. }
  257. func (s *Server) logout(w http.ResponseWriter, r *http.Request) {
  258. fmt.Println("logout")
  259. session, _ := s.sessionStore.Get(r, CookieSessionToken)
  260. session.Values["user"] = ""
  261. session.Values["token"] = ""
  262. session.Save(r, w)
  263. }
  264. func (s *Server) login(user, token string, w http.ResponseWriter, r *http.Request) {
  265. session, _ := s.sessionStore.Get(r, CookieSessionToken)
  266. session.Values["user"] = user
  267. session.Values["token"] = token
  268. session.Save(r, w)
  269. http.Redirect(w, r, "/mailbox", http.StatusTemporaryRedirect)
  270. }
  271. func (s *Server) error(code int, text string, w http.ResponseWriter, r *http.Request) {
  272. w.WriteHeader(code)
  273. fmt.Fprint(w, s.templater.ExecuteError(&struct {
  274. Code int
  275. Text string
  276. Version string
  277. }{
  278. Code: code,
  279. Text: text,
  280. Version: common.Version,
  281. }))
  282. }
  283. func (s *Server) extractAuth(w http.ResponseWriter, r *http.Request) (user, token string) {
  284. session, err := s.sessionStore.Get(r, CookieSessionToken)
  285. if err != nil {
  286. log.Printf("Unable to read user session %s\n", err)
  287. return
  288. }
  289. user, _ = session.Values["user"].(string)
  290. token, _ = session.Values["token"].(string)
  291. return
  292. }