{"id":16217168,"url":"https://github.com/mblayman/django-denied","last_synced_at":"2025-04-05T08:03:43.851Z","repository":{"id":50290703,"uuid":"518657963","full_name":"mblayman/django-denied","owner":"mblayman","description":"An authorization system based exclusively on allow lists","archived":false,"fork":false,"pushed_at":"2024-10-21T23:01:03.000Z","size":98,"stargazers_count":85,"open_issues_count":1,"forks_count":2,"subscribers_count":3,"default_branch":"main","last_synced_at":"2024-10-22T19:33:35.990Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/mblayman.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":".github/CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2022-07-28T01:13:41.000Z","updated_at":"2024-10-21T23:01:05.000Z","dependencies_parsed_at":"2024-02-19T18:07:13.121Z","dependency_job_id":"fc337555-516a-4cd6-bf37-977eb29f8df5","html_url":"https://github.com/mblayman/django-denied","commit_stats":{"total_commits":53,"total_committers":2,"mean_commits":26.5,"dds":0.4528301886792453,"last_synced_commit":"ef8b86dfd8ae437c03694019b10fdbe34810b49a"},"previous_names":[],"tags_count":6,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mblayman%2Fdjango-denied","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mblayman%2Fdjango-denied/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mblayman%2Fdjango-denied/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mblayman%2Fdjango-denied/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/mblayman","download_url":"https://codeload.github.com/mblayman/django-denied/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247305930,"owners_count":20917207,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-10-10T11:25:38.111Z","updated_at":"2025-04-05T08:03:43.833Z","avatar_url":"https://github.com/mblayman.png","language":"Python","funding_links":[],"categories":["Python"],"sub_categories":[],"readme":"# django-denied\n\n\u003e None shall pass.\n\u003e\n\u003e The Black Knight\n\ndjango-denied is an authorization system\nfor the Django web framework.\nWith django-denied,\nevery Django view *must be explicitly allowed*.\nThis design means\nthat developers have to make a choice\nabout authorization\nfor a view to work.\n\nIn other words,\ndjango-denied makes authorization a requirement\nfor every view in a Django project.\n\n## Who should use this?\n\nThis package is well suited for Django projects\nthat need to protect pages against unauthorized access normally.\nIf you are making a service\nthat requires user's to login\nand restricts which data a user sees,\nthen django-denied may be a good fit for you.\n\nIf your web application is meant to be open\nfor a large audience,\nespecially with lots of anonymous users,\nthen this package may be overkill for your needs.\nA blog or content management system may not be a good candidate.\n\n## Install\n\nGet the package.\n\n```\npip install django-denied\n```\n\ndjango-denied uses Django's built-in `auth` and `admin` apps.\nThese apps also depend on the `contenttypes` app.\nEnsure that these apps are in your `INSTALL_APPS`\nin your Django settings file.\n\n```python\nINSTALLED_APPS = [\n    \"django.contrib.admin\",\n    \"django.contrib.auth\",\n    \"django.contrib.contenttypes\",\n    ...,\n]\n```\n\nAdd the `DeniedMiddleware`.\nThis middleware does all the authorization checking.\nThe middleware depends on the `request.user`,\nso be sure to include it *after* the `AuthenticationMiddleware`.\n\n```python\nMIDDLEWARE = [\n    ...,\n    \"django.contrib.auth.middleware.AuthenticationMiddleware\",\n    \"denied.middleware.DeniedMiddleware\",\n    ...,\n]\n```\n\nNow you're ready to start.\n\n## Usage\n\ndjango-denied has two primary modes\nfor handling views.\n\n1. `allow`\n2. `authorize`\n\nThese decorators are the main interface\nof the package\nand are described in the sections below.\n\nBy default,\ndjango-denied assumes that all users should be authenticated,\nwith the exception of allowed views or login pages.\n\nThe login pages are\n\n* The page defined by `settings.LOGIN_URL` and\n* The Django admin login defined at the `admin:login` route.\n\nIf you set `LOGIN_URL`,\ndjango-denied expects the path form\nof the setting\n(e.g., `/accounts/login/`)\nrather than the `url` name\n(e.g., `accounts:login`).\n\n### Allowing views\n\nEvery app is likely to have views\nthat should be made accessible to unauthenticated users.\nA company's about page, terms of service, and privacy policy are all good examples.\n\nThe `allow` decorator is for marking a Django view as exempt\nfrom the authorization checking done\nby the `DeniedMiddleware`.\n\nThis is an example of how you might create a terms of service view.\n\n```python\n# application/views.py\nfrom denied.decorators import allow\nfrom django.shortcuts import render\n\n\n@allow\ndef terms_of_service(request):\n    return render(request, \"tos.html\", {})\n```\n\nThe `allow` decorator has a secondary function.\nAside from allowing a single view,\nthe decorator can allow a set of views\nthat you would use with `django.urls.path`.\n\nThis is necessary to permit third party apps\nthat have other views,\nbut are unaware of the django-denied system.\n\nThis is an example of using `allow`\nto permit the Django admin views\nas well as the popular app,\n[django-allauth](https://django-allauth.readthedocs.io/en/latest/).\n\n```python\n# project/urls.py\nfrom denied.decorators import allow\nfrom django.contrib import admin\nfrom django.urls import include, path\n\nurlpatterns = [\n    path(\"accounts/\", allow(include(\"allauth.urls\"))),\n    path(\"admin/\", allow(admin.site.urls)),\n]\n```\n\nNote:\nEven if you include `allow` on a view or a set of views,\nthat does not mean that what you've allowed will suddenly\nbypass any existing authentication or authorization checking.\n***This is a feature, not a bug!***\n\n`login_required`, `permission_required`,\nand any other authentication or authorization checking\nthat pre-exist on views will remain.\n*django-denied does not disable the security features\nof other third party libraries.*\n\n## Authorizing views\n\nWith django-denied,\na Django view is authorized with the `authorize` decorator\nand an *authorizer* function.\nAn authorizer has a function signature of\n\n```python\nfrom django.http import HttpRequest\n\n\ndef example_authorizer(request: HttpRequest, **view_kwargs: dict) -\u003e bool:\n    ...\n```\n\nThe authorizer evaluates the incoming request and view information\nand should return `True` if the request is authorized\nor `False` is the request is not authorized.\nThe `view_kwargs` include any data that was parsed out of the URL route.\n\nThe authorizer acts as a declarative way\nof showing what is authorized\nfor the view.\n\n```python\nfrom denied.decorators import authorize\n\nfrom .authorizers import example_authorizer\n\n\n@authorize(example_authorizer)\ndef example_view(request):\n    ...\n```\n\nTo use `authorize` on a class-based view,\nyou must attach the decorator to the `dispatch` method.\n\n```python\nfrom denied.decorators import authorize\nfrom django.utils.decorators import method_decorator\nfrom django.views.generic import DetailView\n\nfrom .authorizers import example_authorizer\nfrom .models import Example\n\n\n@method_decorator(authorize(example_authorizer), \"dispatch\")\nclass ExampleDetail(DetailView):\n    queryset = Example.objects.all()\n```\n### Built-in authorizers\n\nThe library includes built-in authorizers\nfor common cases.\n\n#### `denied.authorizers.any_authorized`\n\nThis authorizer always evaluates to `True` and is the logical equivalent\nto `login_required` since django-denied always enforces authentication checking.\n\n#### `denied.authorizers.staff_authorized`\n\nThis authorizer only permits access when `user.is_staff == True`.\n`staff_authorized` is equivalent to `staff_member_required`\nfrom the Django `admin` app.\n\n#### Authorizer example\n\nThis section shows a more complete example\nof an authorizer\nto give you a sense\nof how django-denied works in practice.\n\nFor our example,\nwe'll consider a project tracking application.\nThis is little more than a TODO list\nthat groups the tasks into projects.\n\nHere are the models.\n\n```python\n# application/models.py\nfrom django.contrib.auth.models import User\nfrom django.db import models\n\n\nclass Project(models.Model):\n    owner = models.ForeignKey(User, on_delete=models.CASCADE)\n\n\nclass Task(models.Model):\n    project = models.ForeignKey(Project, on_delete=models.CASCADE)\n    description = models.TextField()\n    completed = models.BooleanField(default=False)\n```\n\nFor this simple system,\nonly project owners can do anything\nwith a task.\nLet's create the authorizer for that.\n\n```python\n# application/authorizers.py\n\n\ndef task_authorized(request, **view_kwargs):\n    return Task.objects.filter(\n        project__owner=request.user,\n        pk=view_kwargs[\"pk\"],\n    ).exists()\n```\n\nThese are the URLs we want to support\nwith this authorizer.\n\n```python\n# application/urls.py\n\nfrom django.urls import path\n\nfrom .views import task_detail, task_edit\n\nurlpatterns = [\n    path(\"tasks/\u003cint:pk\u003e/\", task_detail, name=\"task_detail\"),\n    path(\"tasks/\u003cint:pk\u003e/edit/\", task_detail, name=\"task_edit\"),\n]\n```\n\nNow we can set our views\nand set their authorization.\n\n```python\n# application/views.py\nfrom denied.decorators import authorize\nfrom django.shortcuts import render\n\nfrom .authorizers import task_authorized\nfrom .models import Task\n\n\n@authorize(task_authorized)\ndef task_detail(request, pk):\n    task = Task.objects.get(pk=pk)\n    return render(request, \"task_detail.html\", {\"task\": task})\n\n\n@authorize(task_authorized)\ndef task_edit(request, pk):\n    task = Task.objects.get(pk=pk)\n    return render(request, \"task_edit.html\", {\"task\": task})\n```\n\nSince the authorizer handles the access control,\nwe can be confident that the task is safe to fetch\nby its key alone.\nAccess control is pushed to the boundary of the view\nso that the view's internal logic is about as simple\nas you can make it.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmblayman%2Fdjango-denied","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmblayman%2Fdjango-denied","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmblayman%2Fdjango-denied/lists"}