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
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

View file

@ -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