store filter_id in a long-lived cookie (derpibooru/philomena#139)

This commit is contained in:
byte[] 2020-09-14 20:02:43 -04:00
parent 218607b208
commit 6deab827ac
2 changed files with 24 additions and 6 deletions

View file

@ -1,6 +1,8 @@
defmodule PhilomenaWeb.Filter.CurrentController do defmodule PhilomenaWeb.Filter.CurrentController do
use PhilomenaWeb, :controller use PhilomenaWeb, :controller
@cookie_opts [max_age: 788_923_800, same_site: "Lax"]
alias Philomena.{Filters, Filters.Filter, Users.User} alias Philomena.{Filters, Filters.Filter, Users.User}
alias Philomena.Repo alias Philomena.Repo
@ -24,8 +26,7 @@ defmodule PhilomenaWeb.Filter.CurrentController do
end end
defp update_filter(conn, nil, filter) do defp update_filter(conn, nil, filter) do
conn put_resp_cookie(conn, "filter_id", Integer.to_string(filter.id), @cookie_opts)
|> put_session(:filter_id, filter.id)
end end
defp update_filter(conn, user, filter) do defp update_filter(conn, user, filter) do

View file

@ -9,7 +9,7 @@ defmodule PhilomenaWeb.CurrentFilterPlug do
# Assign current filter # Assign current filter
def call(conn, _opts) do def call(conn, _opts) do
conn = fetch_session(conn) conn = fetch_cookies(conn)
user = conn.assigns.current_user user = conn.assigns.current_user
{filter, forced_filter} = {filter, forced_filter} =
@ -21,9 +21,7 @@ defmodule PhilomenaWeb.CurrentFilterPlug do
{user.current_filter, user.forced_filter} {user.current_filter, user.forced_filter}
else else
filter_id = conn |> get_session(:filter_id) filter = load_and_authorize_filter(conn.cookies, user)
filter = if filter_id, do: Repo.get(Filter, filter_id)
{filter || Filters.default_filter(), nil} {filter || Filters.default_filter(), nil}
end end
@ -45,4 +43,23 @@ defmodule PhilomenaWeb.CurrentFilterPlug do
end end
defp maybe_set_default_filter(user), do: user 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 end