Skip to content

Commit f86fd56

Browse files
Add optional default_authorize callback
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.
1 parent 11324ac commit f86fd56

File tree

3 files changed

+15
-2
lines changed

3 files changed

+15
-2
lines changed

lib/authorization.ex

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,8 @@ defmodule Rajska.Authorization do
3030

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

33+
@callback default_authorize(context, scoped_struct) :: role() | nil
34+
3335
@optional_callbacks get_current_user: 1,
3436
get_ip: 1,
3537
get_user_role: 1,
@@ -38,5 +40,6 @@ defmodule Rajska.Authorization do
3840
has_user_access?: 3,
3941
unauthorized_message: 1,
4042
context_role_authorized?: 2,
41-
context_user_authorized?: 3
43+
context_user_authorized?: 3,
44+
default_authorize: 2
4245
end

lib/middlewares/object_authorization.ex

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,10 +88,17 @@ defmodule Rajska.ObjectAuthorization do
8888
defp authorize_object(object, fields, resolution) do
8989
object
9090
|> Type.meta(:authorize)
91+
|> default_authorize(resolution.context, object)
9192
|> authorized?(resolution.context, object)
9293
|> put_result(fields, resolution, object)
9394
end
9495

96+
defp default_authorize(nil, context, object) do
97+
Rajska.apply_auth_mod(context, :default_authorize, [context, object])
98+
end
99+
100+
defp default_authorize(authorize, _context, _object), do: authorize
101+
95102
defp authorized?(nil, _, object), do: raise "No meta authorize defined for object #{inspect object.identifier}"
96103

97104
defp authorized?(permission, context, _object) do

lib/rajska.ex

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,8 @@ defmodule Rajska do
6565
defmacro __using__(opts \\ []) do
6666
super_role = Keyword.get(opts, :super_role, :admin)
6767
valid_roles = Keyword.get(opts, :valid_roles, [super_role])
68-
default_rule = Keyword.get(opts, :default_rule, :default)
68+
default_rule = Keyword.get(opts, :default_rule, :default)
69+
default_authorize = Keyword.get(opts, :default_authorize, nil)
6970

7071
quote do
7172
@behaviour Authorization
@@ -130,6 +131,8 @@ defmodule Rajska do
130131
|> get_current_user()
131132
|> has_user_access?(scoped_struct, rule)
132133
end
134+
135+
def default_authorize(_context, _object), do: unquote(default_authorize)
133136

134137
defoverridable Authorization
135138
end

0 commit comments

Comments
 (0)