This project brings a declaritive, organized approach to managing access control in Django REST Framework projects. Each ViewSet or function-based view can be assigned an explicit policy for the exposed resource(s). No more digging through views or seralizers to understand access logic -- it's all in one place in a format that less technical stakeholders can understand. If you're familiar with other declaritive access models, such as AWS' IAM, the syntax will be familiar.
In short, you can start expressing your access rules like this:
class ArticleAccessPolicy(AccessPolicy):
statements = [
{
"action": ["list", "retrieve"],
"principal": "*",
"effect": "allow"
},
{
"action": ["publish", "unpublish"],
"principal": ["group:editor"],
"effect": "allow"
}
]
This project has complete test coverage and the base AccessPolicy
class is only ~150 lines of code: there's no magic here.
Documentation: https://rsinger86.github.io/drf-access-policy
Source Code: https://github.com/rsinger86/drf-access-policy
- Fixes case where object has no
action_map
. Thanks @oguzhancelikarslan! - Added missing info to docs. Thanks @hardntrash!
- Workaround for quirk resulting in
action
not always being set. Thanks @oguzhancelikarslan!
- Allows using HTTP method placeholders in
action
element of statements to match request.- For example,
"action": ["<method:post>"]
will match all POST requests.
- For example,
- Uses
user.pk
instead ofuser.id
in user principal check, for compatibility with non-id
primary keys. - Fixes to documentation. Thanks @oguzhancelikarslan!
- Replaces references to "delete" action with "destroy" in docs/tests, to be consistent with DRF's ViewSet actions. Thanks @greenled!
- Only call database-hitting
get_user_group_values
if needed in private method. Thanks KillianMeersman! - Use
prefetch_related_objects
to ensure that user's groups aren't fetched more than once. Thanks filwaline!
- Tox config updates and typo fixes in docs.
- Add option to define re-usable custom conditions/permissions in a module that can be referenced by multiple policies.
- Fixes readme format for Pypy display.
- Allow passing arguments to condition methods, via condition values formatted as
{method_name}:{arg_value}
.
- Adds special
<safe_methods>
action key that matches when the current request is an HTTP read-only method: HEAD, GET, OPTIONS.
- Adds special
authenticated
andanonymous
principal keys to match any authenticated user and any non-authenticated user, respectively. Thanks @bogdandm for discussion/advice!
- Initial release
Tests are found in a simplified Django project in the /tests
folder. Install the project requirements and do ./manage.py test
to run them.
See License.