cookie.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. // User Settings (Using Browser Cookies)
  2. package session
  3. import (
  4. "time"
  5. "net/http"
  6. )
  7. type CookieName string
  8. const ( // the __Host thing force it to be secure and same-origin (no subdomain) >> https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie
  9. Cookie_Token CookieName = "pixivfe-Token"
  10. Cookie_CSRF CookieName = "pixivfe-CSRF"
  11. Cookie_ImageProxy CookieName = "pixivfe-ImageProxy"
  12. Cookie_NovelFontType CookieName = "pixivfe-NovelFontType"
  13. Cookie_NovelViewMode CookieName = "pixivfe-NovelViewMode"
  14. Cookie_ThumbnailToNewTab CookieName = "pixivfe-ThumbnailToNewTab"
  15. Cookie_ArtworkPreview CookieName = "pixivfe-ArtworkPreview"
  16. Cookie_ShowArtR18 CookieName = "pixivfe-ShowArtR18"
  17. Cookie_ShowArtR18G CookieName = "pixivfe-ShowArtR18G"
  18. Cookie_ShowArtAI CookieName = "pixivfe-ShowArtAI"
  19. )
  20. // Go can't make this a const...
  21. var AllCookieNames []CookieName = []CookieName{
  22. Cookie_Token,
  23. Cookie_CSRF,
  24. Cookie_ImageProxy,
  25. Cookie_NovelFontType,
  26. Cookie_NovelViewMode,
  27. Cookie_ThumbnailToNewTab,
  28. Cookie_ArtworkPreview,
  29. Cookie_ShowArtR18,
  30. Cookie_ShowArtR18G,
  31. Cookie_ShowArtAI,
  32. }
  33. func GetCookie(r *http.Request, name CookieName) string {
  34. cookie, err := r.Cookie(string(name))
  35. if err != nil {
  36. return ""
  37. }
  38. return cookie.Value
  39. }
  40. func SetCookie(w http.ResponseWriter, name CookieName, value string) {
  41. http.SetCookie(w, &http.Cookie{
  42. Name: string(name),
  43. Value: value,
  44. Path: "/",
  45. // expires in 30 days from now
  46. Expires: time.Now().Add(30 * (24 * time.Hour)),
  47. HttpOnly: true,
  48. Secure: true,
  49. SameSite: http.SameSiteStrictMode, // bye-bye cross site forgery
  50. })
  51. }
  52. var CookieExpireDelete = time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC)
  53. func ClearCookie(w http.ResponseWriter, name CookieName) {
  54. http.SetCookie(w, &http.Cookie{
  55. Name: string(name),
  56. Value: "",
  57. Path: "/",
  58. // expires in 30 days from now
  59. Expires: CookieExpireDelete,
  60. HttpOnly: true,
  61. Secure: true,
  62. SameSite: http.SameSiteStrictMode,
  63. })
  64. }
  65. func ClearAllCookies(w http.ResponseWriter) {
  66. for _, name := range AllCookieNames {
  67. ClearCookie(w, name)
  68. }
  69. }