Marsel.V
Marsel.V

Reputation: 1044

plug opts and when

How to connect a plug with attributes and expression when in Phoenix controller?

now it looks like this: plug(MyappWeb.Plugs.Auth when action in [:show])

I have to add: mykey: "my_value" I tried different syntax variants, but none worked

plug(MyappWeb.Plugs.Auth, %{mykey: "my_value"} when action in [:show]) plug(MyappWeb.Plugs.Auth when action in [:show], %{mykey: "my_value"})

Upvotes: 1

Views: 214

Answers (1)

guitarman
guitarman

Reputation: 3310

The problem are the round brackets.

In my project I did the same thing to check wether the current logged in user has a special role. So I needed to define such static options.

I have a plug method (def has_role_from_list(conn, options) do) which receives the conn object and a keyword list in options.

In my controller I call the plug method and I provide the accepted roles as a keyword list:
plug :has_role_from_list, [roles: ["match-editor", "team-editor"]]

If I would have to restrict the plug call to some actions I'm free to define it like so: plug :has_role_from_list, [roles: ["match-editor", "team-editor"]] when action in [:create, :update]

The point is, that the round brackets of the plug macro call in your controller should include the parameters for the macro only. In my example it would look like this: plug(:has_role_from_list, [roles: ["match-editor", "team-editor"]]) when action in [:create, :update]

Upvotes: 1

Related Questions