settings.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. package pages
  2. import (
  3. "errors"
  4. "io"
  5. "net/http"
  6. "regexp"
  7. session "codeberg.org/vnpower/pixivfe/v2/core/config"
  8. httpc "codeberg.org/vnpower/pixivfe/v2/core/http"
  9. "github.com/gofiber/fiber/v2"
  10. )
  11. func setToken(c *fiber.Ctx) error {
  12. // Parse the value from the form
  13. token := c.FormValue("token")
  14. if token != "" {
  15. URL := httpc.GetNewestFromFollowingURL("all", "1")
  16. _, err := httpc.UnwrapWebAPIRequest(URL, token)
  17. if err != nil {
  18. return errors.New("Cannot authorize with supplied token.")
  19. }
  20. // Make a test request to verify the token.
  21. // THE TEST URL IS NSFW!
  22. req, _ := http.NewRequest("GET", "https://www.pixiv.net/en/artworks/115365120", nil)
  23. req.Header.Add("User-Agent", "Mozilla/5.0")
  24. req.AddCookie(&http.Cookie{
  25. Name: "PHPSESSID",
  26. Value: token,
  27. })
  28. resp, err := http.DefaultClient.Do(req)
  29. if err != nil {
  30. return errors.New("Cannot authorize with supplied token.")
  31. }
  32. body, err := io.ReadAll(resp.Body)
  33. if err != nil {
  34. return errors.New("Cannot parse the response from Pixiv. Please report this issue.")
  35. }
  36. // CSRF token
  37. r := regexp.MustCompile(`"token":"([0-9a-f]+)"`)
  38. csrf := r.FindStringSubmatch(string(body))[1]
  39. if csrf == "" {
  40. return errors.New("Cannot authorize with supplied token.")
  41. }
  42. // Set the tokens
  43. if err := session.SetSessionValue(c, "Token", token); err != nil {
  44. return err
  45. }
  46. if err := session.SetSessionValue(c, "CSRF", csrf); err != nil {
  47. return err
  48. }
  49. return nil
  50. }
  51. return errors.New("You submitted an empty/invalid form.")
  52. }
  53. func setImageServer(c *fiber.Ctx) error {
  54. // Parse the value from the form
  55. token := c.FormValue("image-proxy")
  56. if token != "" {
  57. if err := session.SetSessionValue(c, "ImageProxy", token); err != nil {
  58. return err
  59. }
  60. return nil
  61. }
  62. return errors.New("You submitted an empty/invalid form.")
  63. }
  64. func setLogout(c *fiber.Ctx) error {
  65. session.RemoveSessionValue(c, "Token")
  66. return nil
  67. }
  68. func SettingsPage(c *fiber.Ctx) error {
  69. return c.Render("pages/settings", fiber.Map{})
  70. }
  71. func SettingsPost(c *fiber.Ctx) error {
  72. t := c.Params("type")
  73. var err error
  74. switch t {
  75. case "image_server":
  76. err = setImageServer(c)
  77. case "token":
  78. err = setToken(c)
  79. case "logout":
  80. err = setLogout(c)
  81. default:
  82. err = errors.New("No such methods available.")
  83. }
  84. if err != nil {
  85. return err
  86. }
  87. c.Redirect("/")
  88. return nil
  89. }