flash.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. // Copyright (C) 2019-2023 Nicola Murino
  2. //
  3. // This program is free software: you can redistribute it and/or modify
  4. // it under the terms of the GNU Affero General Public License as published
  5. // by the Free Software Foundation, version 3.
  6. //
  7. // This program is distributed in the hope that it will be useful,
  8. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. // GNU Affero General Public License for more details.
  11. //
  12. // You should have received a copy of the GNU Affero General Public License
  13. // along with this program. If not, see <https://www.gnu.org/licenses/>.
  14. package httpd
  15. import (
  16. "encoding/base64"
  17. "net/http"
  18. "time"
  19. )
  20. const (
  21. flashCookieName = "message"
  22. )
  23. func setFlashMessage(w http.ResponseWriter, r *http.Request, value string) {
  24. http.SetCookie(w, &http.Cookie{
  25. Name: flashCookieName,
  26. Value: base64.URLEncoding.EncodeToString([]byte(value)),
  27. Path: "/",
  28. Expires: time.Now().Add(60 * time.Second),
  29. MaxAge: 60,
  30. HttpOnly: true,
  31. Secure: isTLS(r),
  32. SameSite: http.SameSiteLaxMode,
  33. })
  34. w.Header().Add("Cache-Control", `no-cache="Set-Cookie"`)
  35. }
  36. func getFlashMessage(w http.ResponseWriter, r *http.Request) string {
  37. cookie, err := r.Cookie(flashCookieName)
  38. if err != nil {
  39. return ""
  40. }
  41. http.SetCookie(w, &http.Cookie{
  42. Name: flashCookieName,
  43. Value: "",
  44. Path: "/",
  45. Expires: time.Unix(0, 0),
  46. MaxAge: -1,
  47. HttpOnly: true,
  48. Secure: isTLS(r),
  49. SameSite: http.SameSiteLaxMode,
  50. })
  51. message, err := base64.URLEncoding.DecodeString(cookie.Value)
  52. if err != nil {
  53. return ""
  54. }
  55. return string(message)
  56. }