diff --git a/lib/microwaveprop/rover.ex b/lib/microwaveprop/rover.ex index 958a0171..0c59396d 100644 --- a/lib/microwaveprop/rover.ex +++ b/lib/microwaveprop/rover.ex @@ -168,6 +168,13 @@ defmodule Microwaveprop.Rover do end end + defp fetch_owned_location(%User{is_admin: true}, id) do + case Repo.get(Location, id) do + %Location{} = loc -> {:ok, loc} + _ -> {:error, :not_found} + end + end + defp fetch_owned_location(%User{id: user_id}, id) do case Repo.get(Location, id) do %Location{user_id: ^user_id} = loc -> {:ok, loc} diff --git a/lib/microwaveprop_web/live/rover_locations_live.ex b/lib/microwaveprop_web/live/rover_locations_live.ex index c01a8c9a..2fc8d69e 100644 --- a/lib/microwaveprop_web/live/rover_locations_live.ex +++ b/lib/microwaveprop_web/live/rover_locations_live.ex @@ -83,20 +83,19 @@ defmodule MicrowavepropWeb.RoverLocationsLive do end def handle_event("edit", %{"id" => id}, socket) do - case current_user(socket) do - %User{id: user_id} -> - case Repo.get(Location, id) do - %Location{user_id: ^user_id} = loc -> - cs = Location.changeset(loc, %{}) - grid = Maidenhead.from_latlon(loc.lat, loc.lon, 6) - {:noreply, assign(socket, form: to_form(cs), editing_id: id, grid_input: grid)} + user = current_user(socket) - _ -> - {:noreply, put_flash(socket, :error, "You can only edit your own locations.")} - end - - _ -> + cond do + is_nil(user) -> {:noreply, put_flash(socket, :error, "Sign in to edit a location.")} + + loc = editable_location(user, id) -> + cs = Location.changeset(loc, %{}) + grid = Maidenhead.from_latlon(loc.lat, loc.lon, 6) + {:noreply, assign(socket, form: to_form(cs), editing_id: id, grid_input: grid)} + + true -> + {:noreply, put_flash(socket, :error, "You can only edit your own locations.")} end end @@ -184,6 +183,17 @@ defmodule MicrowavepropWeb.RoverLocationsLive do defp location_for_edit(_), do: %Location{} + defp editable_location(%User{is_admin: true}, id) do + Repo.get(Location, id) + end + + defp editable_location(%User{id: user_id}, id) do + case Repo.get(Location, id) do + %Location{user_id: ^user_id} = loc -> loc + _ -> nil + end + end + defp blank_form(_user) do %Location{} |> Location.changeset(%{}) |> to_form() end @@ -254,16 +264,15 @@ defmodule MicrowavepropWeb.RoverLocationsLive do end end - defp owner?(_scope, %{user_id: nil}), do: false - - defp owner?(scope, %{user_id: uid}) do + defp can_modify?(scope, %{user_id: uid}) do case scope_user(%{current_scope: scope}) do - %User{id: ^uid} -> true + %User{is_admin: true} -> true + %User{id: ^uid} when not is_nil(uid) -> true _ -> false end end - defp owner?(_, _), do: false + defp can_modify?(_, _), do: false defp actions_for(scope) do [ @@ -274,10 +283,10 @@ defmodule MicrowavepropWeb.RoverLocationsLive do end defp row_actions(record, scope) do - assigns = %{record: record, owner?: owner?(scope, record)} + assigns = %{record: record, can_modify?: can_modify?(scope, record)} ~H""" -