From 6deab827acffae584644e052af992d4fa6803f89 Mon Sep 17 00:00:00 2001 From: "byte[]" Date: Mon, 14 Sep 2020 20:02:43 -0400 Subject: [PATCH] store filter_id in a long-lived cookie (derpibooru/philomena#139) --- .../controllers/filter/current_controller.ex | 5 ++-- .../plugs/current_filter_plug.ex | 25 ++++++++++++++++--- 2 files changed, 24 insertions(+), 6 deletions(-) diff --git a/lib/philomena_web/controllers/filter/current_controller.ex b/lib/philomena_web/controllers/filter/current_controller.ex index 646e9161..362dbab6 100644 --- a/lib/philomena_web/controllers/filter/current_controller.ex +++ b/lib/philomena_web/controllers/filter/current_controller.ex @@ -1,6 +1,8 @@ defmodule PhilomenaWeb.Filter.CurrentController do use PhilomenaWeb, :controller + @cookie_opts [max_age: 788_923_800, same_site: "Lax"] + alias Philomena.{Filters, Filters.Filter, Users.User} alias Philomena.Repo @@ -24,8 +26,7 @@ defmodule PhilomenaWeb.Filter.CurrentController do end defp update_filter(conn, nil, filter) do - conn - |> put_session(:filter_id, filter.id) + put_resp_cookie(conn, "filter_id", Integer.to_string(filter.id), @cookie_opts) end defp update_filter(conn, user, filter) do diff --git a/lib/philomena_web/plugs/current_filter_plug.ex b/lib/philomena_web/plugs/current_filter_plug.ex index a9264910..81ea7184 100644 --- a/lib/philomena_web/plugs/current_filter_plug.ex +++ b/lib/philomena_web/plugs/current_filter_plug.ex @@ -9,7 +9,7 @@ defmodule PhilomenaWeb.CurrentFilterPlug do # Assign current filter def call(conn, _opts) do - conn = fetch_session(conn) + conn = fetch_cookies(conn) user = conn.assigns.current_user {filter, forced_filter} = @@ -21,9 +21,7 @@ defmodule PhilomenaWeb.CurrentFilterPlug do {user.current_filter, user.forced_filter} else - filter_id = conn |> get_session(:filter_id) - - filter = if filter_id, do: Repo.get(Filter, filter_id) + filter = load_and_authorize_filter(conn.cookies, user) {filter || Filters.default_filter(), nil} end @@ -45,4 +43,23 @@ defmodule PhilomenaWeb.CurrentFilterPlug do end defp maybe_set_default_filter(user), do: user + + defp load_and_authorize_filter(%{"filter_id" => filter_id}, user) do + Filter + |> Repo.get(filter_id) + |> case do + nil -> + nil + + filter -> + case Canada.Can.can?(user, :show, filter) do + true -> filter + false -> nil + end + end + end + + defp load_and_authorize_filter(_cookies, _user) do + nil + end end