Last active
December 19, 2018 13:08
-
-
Save johannesE/607e75a083c3c22062f8f4eb0c69f2a5 to your computer and use it in GitHub Desktop.
Plug to check that a user modifies only his files.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule AppWeb.BelongsToPlug do | |
@moduledoc """ | |
This plug makes sure that a user modifies only his resources based on the user_id of the model. | |
""" | |
def init(options), do: options | |
def call(conn = %Plug.Conn{method: "DELETE"}, _options) do | |
raise "This Plug should not be used for deletion checking because it's impossible to figure out what model(s) the user wishes to delete." | |
end | |
def call(conn, _options) do | |
user_id = conn.assigns.current_user.id | |
model = Map.values(conn.params) |> List.last | |
case model["user_id"] do | |
^user_id -> conn # The model belongs to the user | |
nil -> conn # No user has been assigned or the model has no user_id | |
_ -> auth_error(conn) | |
end | |
end | |
defp auth_error(conn) do | |
conn | |
|> Phoenix.Controller.put_flash(:error, "You can't access that page!") | |
|> Phoenix.Controller.redirect(to: "/") | |
|> Plug.Conn.halt # You want to stop it from reaching controller code! | |
# If you have an API, use something like this. | |
# conn | |
# |> Plug.Conn.halt | |
# |> put_view(AppWeb.SomeView) | |
# |> put_status(401) | |
# |> render("message.json", message: "Authentication required.") | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment