Skip to content

Commit

Permalink
Merge pull request #869 from code-corps/fix-canaryless-policies
Browse files Browse the repository at this point in the history
Fixed issue with policies not relying on canary
  • Loading branch information
begedin committed Aug 29, 2017
2 parents 68b2436 + 27e14fb commit 8f41c86
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 7 deletions.
12 changes: 6 additions & 6 deletions lib/code_corps/policy/policy.ex
Original file line number Diff line number Diff line change
Expand Up @@ -15,17 +15,17 @@ defmodule CodeCorps.Policy do
The resource can be a record, when performing an action on an existing record,
or it can be a map of parameters, when creating a new record.
"""
@spec authorize(User.t, atom, map | struct) :: {:ok, :authorized} | {:error, :not_authorized}
def authorize(%User{} = user, action, resource) do
case user |> can?(action, resource) do
@spec authorize(User.t, atom, struct, map) :: {:ok, :authorized} | {:error, :not_authorized}
def authorize(%User{} = user, action, struct, %{} = params \\ %{}) do
case user |> can?(action, struct, params) do
true -> {:ok, :authorized}
false -> {:error, :not_authorized}
end
end

@spec can?(User.t, atom, map | struct) :: boolean
defp can?(%User{} = user, :update, %Comment{} = comment), do: Policy.Comment.update?(user, comment)
defp can?(%User{} = user, :create, %{} = params), do: Policy.Comment.create?(user, params)
@spec can?(User.t, atom, struct, map) :: boolean
defp can?(%User{} = user, :create, %Comment{}, %{} = params), do: Policy.Comment.create?(user, params)
defp can?(%User{} = user, :update, %Comment{} = comment, %{}), do: Policy.Comment.update?(user, comment)

defimpl Canada.Can, for: User do
# NOTE: Canary sets an :unauthorized and a :not_found handler on a config level
Expand Down
2 changes: 1 addition & 1 deletion lib/code_corps_web/controllers/comment_controller.ex
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ defmodule CodeCorpsWeb.CommentController do
@spec create(Plug.Conn.t, map) :: Conn.t
def create(%Conn{} = conn, %{} = params) do
with %User{} = current_user <- conn |> Guardian.Plug.current_resource,
{:ok, :authorized} <- current_user |> Policy.authorize(:create, params),
{:ok, :authorized} <- current_user |> Policy.authorize(:create, %Comment{}, params),
{:ok, %Comment{} = comment} <- %Comment{} |> Comment.create_changeset(params) |> Repo.insert do
conn |> put_status(:created) |> render("show.json-api", data: comment)
end
Expand Down

0 comments on commit 8f41c86

Please sign in to comment.