riverrun / openmaize

No longer maintained - was an Authentication library for Plug-based applications in Elixir
Other
206 stars 30 forks source link

Howto: Allow access for admin and for own user #15

Closed farao closed 8 years ago

farao commented 8 years ago

Hi!

Thanks for this great project! This is rather a question than an issue but I didn't know where to ask it. What I would like to do is restricting editing of a user to the admin (in any case) and to the user itself (but not other users). I found plug :authorize_id for the latter but how can I express that this should only be applied if the user has the role "user" and if it's an "admin" then the check should not be in place...?

How can you combine those two anyways? I couldn't find it in the docs nor in the example project.

Marius

farao commented 8 years ago

Hm, maybe I should make it clearer. My goal is that: (a) a user with role "user" can edit/delete/show only his own profile (b) a user with role "admin" can edit/delete/show all users I have a pretty standard user_controller & model and only want to add the plugs in the controller so that it represents the behaviour above.

riverrun commented 8 years ago

You can do this by customizing the authorize_id plug, like this:

Openmaize.AccessControl

plug :authorize, roles: ["admin", "user"]
plug :custom_auth when action in [:show, :edit, :delete]

defp custom_auth(conn, opts) do
  if conn.assigns.current_user.role == "admin" do
    conn
  else
    authorize_id(conn, opts)
  end
end

Thanks for raising the issue. I should add an example like this in the documentation somewhere. Let me know if you have any further questions.

riverrun commented 8 years ago

There is now an example of this in the documentation for the AccessControl module.

farao commented 8 years ago

Thanks for your help!