Skip to content

Commit

Permalink
Add optional default_authorize callback
Browse files Browse the repository at this point in the history
This allows setting the `authorize: ...` value for all fields if none was set.

This allows for an easier adoption for APIs that might previously not
have any role-based authorization. Defaulting to their default role,
for instance, :admin, and only adding `authorize: ...` where authorization
can be relaxed.
  • Loading branch information
jeroenvisser101 committed Jul 15, 2020
1 parent 11324ac commit f86fd56
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 2 deletions.
5 changes: 4 additions & 1 deletion lib/authorization.ex
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ defmodule Rajska.Authorization do

@callback context_user_authorized?(context, scoped_struct, rule) :: boolean()

@callback default_authorize(context, scoped_struct) :: role() | nil

@optional_callbacks get_current_user: 1,
get_ip: 1,
get_user_role: 1,
Expand All @@ -38,5 +40,6 @@ defmodule Rajska.Authorization do
has_user_access?: 3,
unauthorized_message: 1,
context_role_authorized?: 2,
context_user_authorized?: 3
context_user_authorized?: 3,
default_authorize: 2
end
7 changes: 7 additions & 0 deletions lib/middlewares/object_authorization.ex
Original file line number Diff line number Diff line change
Expand Up @@ -88,10 +88,17 @@ defmodule Rajska.ObjectAuthorization do
defp authorize_object(object, fields, resolution) do
object
|> Type.meta(:authorize)
|> default_authorize(resolution.context, object)
|> authorized?(resolution.context, object)
|> put_result(fields, resolution, object)
end

defp default_authorize(nil, context, object) do
Rajska.apply_auth_mod(context, :default_authorize, [context, object])
end

defp default_authorize(authorize, _context, _object), do: authorize

defp authorized?(nil, _, object), do: raise "No meta authorize defined for object #{inspect object.identifier}"

defp authorized?(permission, context, _object) do
Expand Down
5 changes: 4 additions & 1 deletion lib/rajska.ex
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,8 @@ defmodule Rajska do
defmacro __using__(opts \\ []) do
super_role = Keyword.get(opts, :super_role, :admin)
valid_roles = Keyword.get(opts, :valid_roles, [super_role])
default_rule = Keyword.get(opts, :default_rule, :default)
default_rule = Keyword.get(opts, :default_rule, :default)
default_authorize = Keyword.get(opts, :default_authorize, nil)

quote do
@behaviour Authorization
Expand Down Expand Up @@ -130,6 +131,8 @@ defmodule Rajska do
|> get_current_user()
|> has_user_access?(scoped_struct, rule)
end

def default_authorize(_context, _object), do: unquote(default_authorize)

defoverridable Authorization
end
Expand Down

0 comments on commit f86fd56

Please sign in to comment.