smpallen99 / ex_admin

ExAdmin is an auto administration package for Elixir and the Phoenix Framework
MIT License
1.2k stars 275 forks source link

Get current_user in the context of the form #430

Closed cdesch closed 6 years ago

cdesch commented 6 years ago

How do you get the current_user in the context of the form?


 form user do
      inputs "User Details" do

        input user, :first_name
        input user, :last_name
        input user, :email
        input user, :mobile
        input user, :status
        if current_user.role == 3 do
           inputs do
             input user, :role, collection: [{0, "Customer"}, {1, "Merchant"}, {2, "Support"}, {3, "Admin"}]
           end
        end

        input user, :registration_complete
        input user, :password, type: :password
        input user, :password_confirmation, type: :password
      end
    end
  end

If you wanted to only render or authorize one field in the form, how do I get the current_user from the form itself?

cdesch commented 6 years ago

I was able to do it with conn


  form user do
      inputs "User Details" do

        input user, :first_name
        input user, :last_name
        input user, :email
        input user, :mobile
        input user, :status
        current_user = MyApp.Authentication.current_user(conn)
        if current_user.role == 3 do
          input user, :role, collection: [{0, "Customer"}, {1, "Merchant"}, {2, "Support"}, {3, "Admin"}]
        else
          input user, :role, collection: [{0, "Customer"}, {1, "Merchant"}]
        end
        input user, :birthdate, options: [year: [prompt: "Year"], month: [prompt: "Month"], day: [prompt: "Day"]]

        input user, :password, type: :password
        input user, :password_confirmation, type: :password
      end

It would be kind of cool if I could do that with the input with something like authorize_attributes from the ExAdmin Resource Controller.


defimpl ExAdmin.Authorization, for: MyApp.User do
  def authorize_query(_resource, _conn, query, _action, _id), do: query
  def authorize_action(_resource, conn, action),
    do: Authz.authorize_actions(action, Auth.current_user(conn),
          only: [:index, :show, :edit, :create, :new, :update])
  def authorize_attribute(_resource, _conn, attribute)  do
    IO.puts "some authz"
  end

end

Or maybe a helper/macro where instead of input user, :first_name, I could do authorized_input user, :first_name.