cookie.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. // User Settings (Using Browser Cookies)
  2. package core
  3. import (
  4. "time"
  5. "github.com/gofiber/fiber/v2"
  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 = "__Host-pixivfe-Token"
  10. Cookie_CSRF CookieName = "__Host-pixivfe-CSRF"
  11. Cookie_ImageProxy CookieName = "__Host-pixivfe-ImageProxy"
  12. Cookie_ShowArtR18 CookieName = "__Host-pixivfe-ShowArtR18"
  13. Cookie_ShowArtR18G CookieName = "__Host-pixivfe-ShowArtR18G"
  14. Cookie_ShowArtAI CookieName = "__Host-pixivfe-ShowArtAI"
  15. )
  16. // Go can't make this a const...
  17. var AllCookieNames []CookieName = []CookieName{
  18. Cookie_Token,
  19. Cookie_CSRF,
  20. Cookie_ImageProxy,
  21. }
  22. func GetCookie(c *fiber.Ctx, name CookieName, defaultValue ...string) string {
  23. return c.Cookies(string(name), defaultValue...)
  24. }
  25. func SetCookie(c *fiber.Ctx, name CookieName, value string) {
  26. cookie := fiber.Cookie{
  27. Name: string(name),
  28. Value: value,
  29. Path: "/",
  30. // expires in 30 days from now
  31. Expires: c.Context().Time().Add(30 * (24 * time.Hour)),
  32. HTTPOnly: true,
  33. Secure: true,
  34. SameSite: fiber.CookieSameSiteStrictMode, // bye-bye cross site forgery
  35. }
  36. c.Cookie(&cookie)
  37. }
  38. var CookieExpireDelete = time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC)
  39. func ClearCookie(c *fiber.Ctx, name CookieName) {
  40. cookie := fiber.Cookie{
  41. Name: string(name),
  42. Value: "",
  43. Path: "/",
  44. // expires in 30 days from now
  45. Expires: CookieExpireDelete,
  46. HTTPOnly: true,
  47. Secure: true,
  48. SameSite: fiber.CookieSameSiteStrictMode,
  49. }
  50. c.Cookie(&cookie)
  51. }
  52. func ClearAllCookies(c *fiber.Ctx) {
  53. for _, name := range AllCookieNames {
  54. ClearCookie(c, name)
  55. }
  56. }