Elixir permissions via condition

Hello every one, so I’m a little bit lost in my new project, I need to create an API who who have to manage some users, and I have 3 type of User ( employee, Manager, General_Manager) on the API the employee can only see his dashboard and can add his working date, the manager can manage multiple user they working time and can delete update … And General_Manager have all right…

But i don’t succed to implement permissions in my API, I see there is many way, like Guardian, but i’m not good enough to use it :confused:

So wonder if it is possible to add some basic condition in the user controler like

if (user.role == Manager) do 
  {:ok, nil}
else 
  {:error, unauthorized}
end

for exemple with the delete Def in user_controller what would it look likes ?

this is DELETE in user_controller.ex

def delete(conn, %{"id" => id}) do
  user = Result.get_user!(id)
  with {:ok, %User{}} <- Result.delete_user(user) do
    send_resp(conn, :no_content, "")
  end
end

and this is DELETE in Result.ex

def delete_user(%User{} = user) do
  Repo.delete(user)
end

Thank you very much, and sry if i made some mistake I’m new to elixir !

You can write plug like:

defmodule Check.Permissions do
  def init(opts), do: opts

  def call(conn, _opts) do
    user = get_current_user(conn)

    if user.role == Manager do
      conn
    else
      conn
      |> handle_invalid_user(user)
      |> Plug.Conn.halt()
    end
  end
end

Thank you very much for the answer, but I’m very new to it and I don’t understand how your module will understand what method i would Like to manage.

If I understand what you are wrote, you create a new elixir module Check.permissions and u call the current user and if user.role == manager … what is Invalid at this moment I don’t understand anymore SRY :confused:

A Plug is a module that takes a connection as input and returns a connection (or stop the connection).

You can use it to modify the connection, and You can use it at various level.

In the router, or in a controller, or for one action of a controller etc.

I recommend the docs, as this is a really important piece to understand in the Phoenix stack.

1 Like