cpjk / canary

:hatching_chick: Elixir authorization and resource-loading library for Plug applications.
MIT License
474 stars 51 forks source link

How to restrict a user to see/update/delete his own posts only? #66

Closed acrolink closed 7 years ago

acrolink commented 7 years ago

I have this:

    def can?(%User{ id: user_id }, action, %Post{ user_id: user_id })
    when action in [:show], do: true

But this does not prevent users from seeing other user's posts.

cpjk commented 7 years ago

I would do something like

def can?(%User{ id: user_id_1 }, action, %Post{ user_id: user_id_2 }) 
  when action in [:show] do
  user_id_1 == user_id_2
end
acrolink commented 7 years ago

Thanks @cpjk

I have tried your suggestion but it does not work. A user can still view all posts (those who belong to him and those belonging to other users), Here is the code:

defmodule Entre.Abilities do
  alias Entre.Accounts.User
  alias Entre.Content.Post
  defimpl Canada.Can, for: User do
    def can?(%User{ id: user_id }, action, %Post{ user_id: post_user_id })
    when action in [:show], do:
    user_id == post_user_id

    def can?(%User{ id: user_id }, _, _), do: false
  end
end

I have a question, how does the code understand that it is the show action that is being called? What do I need to write inside the show action in PostsController ?

Anyway, this is the PostController:

defmodule Entre.Web.PostController do
  use Entre.Web, :controller
  alias Entre.Content

  plug :load_and_authorize_resource, model: Content.Post

# other actions ..

  def show(conn, %{"id" => id}) do
    post = Content.get_post!(id)
    render(conn, "show.html", post: post)
  end

# other actions ..
end