Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save 5alamander/669b34edd9f9e676702f11f17ab1999e to your computer and use it in GitHub Desktop.
Save 5alamander/669b34edd9f9e676702f11f17ab1999e to your computer and use it in GitHub Desktop.
Use new fun toys or not?
defmodule ElixirJobBoard.Plugs.AuthorizeJobPoster do
import Plug.Conn
import Phoenix.Controller, only: [put_flash: 3, redirect: 2]
alias ElixirJobBoard.Repo
alias ElixirJobBoard.User
alias ElixirJobBoard.Job
def init(opts), do: opts
def call(conn, _opts) do
user = get_user_assigned_this_request(conn)
job = get_job_from_params(conn)
check_jobs_user(conn, job, user)
end
defp check_jobs_user(conn, nil, nil), do: redirect_to_root(conn)
defp check_jobs_user(conn, _, nil), do: redirect_to_root(conn)
defp check_jobs_user(conn, nil, _), do: redirect_to_root(conn)
defp check_jobs_user(conn, job, user) do
if job.user_id != user.id do
redirect_to_root(conn)
else
conn
end
end
defp redirect_to_root(conn) do
conn
|> put_flash(:info, "You are not authorized to edit that job.")
|> redirect(to: "/")
|> halt
end
defp get_user_assigned_this_request(conn) do
conn.assigns[:current_user]
end
defp get_job_from_params(conn) do
conn = fetch_query_params(conn)
Repo.get(Job, Enum.at(conn.path_info, 1))
end
end
defmodule ElixirJobBoard.Plugs.AuthorizeJobPoster do
import Plug.Conn
import Phoenix.Controller, only: [put_flash: 3, redirect: 2]
alias ElixirJobBoard.Repo
alias ElixirJobBoard.User
alias ElixirJobBoard.Job
def init(opts), do: opts
def call(conn, _opts) do
user = get_user_assigned_this_request(conn)
job = get_job_from_params(conn)
if job == nil || user == nil || job.user_id != user.id do
conn
|> put_flash(:info, "You are not authorized to edit that job.")
|> redirect(to: "/")
|> halt
else
conn
end
end
defp get_user_assigned_this_request(conn) do
conn.assigns[:current_user]
end
defp get_job_from_params(conn) do
conn = fetch_query_params(conn)
Repo.get(Job, Enum.at(conn.path_info, 1))
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment