Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Catch constraint errors on role delete #1344

Merged
merged 1 commit into from
Feb 10, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions lib/cog/models/role.ex
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ defmodule Cog.Models.Role do
If no params are provided, an invalid changeset is returned
with no validation performed.
"""
def changeset(model), do: changeset(model, :empty)
def changeset(model, params \\ %{})

@doc """
Creates a changeset based on the `model` to validate a delete
Expand All @@ -34,7 +34,8 @@ defmodule Cog.Models.Role do
def changeset(model, :delete) do
%{Changeset.change(model) | action: :delete}
|> protect_admin_role

|> group_roles_constraint
|> role_permissions_constraint
end

@doc """
Expand Down
2 changes: 1 addition & 1 deletion lib/cog/repository/roles.ex
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ defmodule Cog.Repository.Roles do
def delete(%Role{name: unquote(Cog.Util.Misc.admin_role)=name}),
do: {:error, {:protected_role, name}}
def delete(%Role{}=role),
do: Repo.delete(role)
do: role |> Role.changeset(:delete) |> Repo.delete

def all,
do: Repo.all(Role) |> preload
Expand Down
9 changes: 9 additions & 0 deletions test/controllers/v1/role_controller_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,15 @@ defmodule Cog.V1.RoleController.Test do
assert %Ecto.NoResultsError{} = error
end

test "delete fails when role still granted permissions", %{authed: user} do
role = role("admin")
permission = permission("site:world")
Permittable.grant_to(role, permission)
conn = api_request(user, :delete, "/v1/roles/#{role.id}")
body = json_response(conn, 422)
assert %{"id" => ["cannot delete role that has been granted permissions"]} = body["errors"]
end

test "cannot list roles without permission", %{unauthed: user} do
conn = api_request(user, :get, "/v1/roles")
assert conn.halted
Expand Down
2 changes: 1 addition & 1 deletion web/controllers/v1/role_controller.ex
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ defmodule Cog.V1.RoleController do
end

def delete(conn, %{"id" => id}) do
case Roles.by_id!(id) |> Roles.delete() do
case id |> Roles.by_id! |> Roles.delete do
{:ok, _} ->
send_resp(conn, :no_content, "")
{:error, changed} ->
Expand Down