|
| 1 | +defmodule Authorizer.Policies.AdminAllowed do |
| 2 | + @moduledoc """ |
| 3 | + Authorization policy to ensure that an subject is an admin. |
| 4 | + """ |
| 5 | + |
| 6 | + require Logger |
| 7 | + |
| 8 | + alias Authorizer.Ports.ResourceManager |
| 9 | + alias Plug.Conn |
| 10 | + |
| 11 | + @behaviour Authorizer.Policies.Behaviour |
| 12 | + |
| 13 | + @subject_types ~w(user application) |
| 14 | + |
| 15 | + @impl true |
| 16 | + def info do |
| 17 | + """ |
| 18 | + Ensures that a specific subject is allowed to do an admin action. |
| 19 | + In order to succeed it has to have `is_admin` set as `true`. |
| 20 | + """ |
| 21 | + end |
| 22 | + |
| 23 | + @impl true |
| 24 | + def validate(%Conn{private: %{session: session}} = context) when is_map(session) do |
| 25 | + case session do |
| 26 | + %{subject_id: id, subject_type: type} when is_binary(id) and type in @subject_types -> |
| 27 | + Logger.debug("Policity #{__MODULE__} validated with success") |
| 28 | + {:ok, context} |
| 29 | + |
| 30 | + _any -> |
| 31 | + Logger.error("Policy #{__MODULE__} failed on validation because session is invalid") |
| 32 | + {:error, :unauthorized} |
| 33 | + end |
| 34 | + end |
| 35 | + |
| 36 | + def validate(%Conn{private: %{session: _}}) do |
| 37 | + Logger.error("Policy #{__MODULE__} failed on validation because session was not found") |
| 38 | + {:error, :unauthorized} |
| 39 | + end |
| 40 | + |
| 41 | + @impl true |
| 42 | + def execute(%Conn{private: %{session: session}}, opts \\ []) |
| 43 | + when is_map(session) and is_list(opts) do |
| 44 | + # We look for the identity on shared context first |
| 45 | + identity = Keyword.get(opts, :identity) |
| 46 | + |
| 47 | + with {:identity, {:ok, identity}} <- {:identity, get_identity(identity || session)}, |
| 48 | + {:admin?, true} <- {:admin?, identity.is_admin} do |
| 49 | + Logger.debug("Policy #{__MODULE__} execution succeeded") |
| 50 | + {:ok, Keyword.put(opts, :identity, identity)} |
| 51 | + else |
| 52 | + {:identity, error} -> |
| 53 | + Logger.error("Policy #{__MODULE__} failed to get identity", error: inspect(error)) |
| 54 | + {:error, :unauthorized} |
| 55 | + |
| 56 | + {:admin?, false} -> |
| 57 | + Logger.error("Policy #{__MODULE__} failed because subject is not an admin") |
| 58 | + {:error, :unauthorized} |
| 59 | + end |
| 60 | + end |
| 61 | + |
| 62 | + defp get_identity(%{subject_id: subject_id, subject_type: "user"}), |
| 63 | + do: ResourceManager.get_identity(%{id: subject_id, username: nil}) |
| 64 | + |
| 65 | + defp get_identity(%{subject_id: subject_id, subject_type: "application"}), |
| 66 | + do: ResourceManager.get_identity(%{id: subject_id, client_id: nil}) |
| 67 | + |
| 68 | + defp get_identity(%{status: _} = identity), do: {:ok, identity} |
| 69 | +end |
0 commit comments