├── tests ├── __init__.py ├── urls.py ├── models.py ├── decorators.py ├── mixins.py ├── base.py ├── signals.py ├── forms.py ├── middleware.py ├── utils.py └── views.py ├── requirements.txt ├── MANIFEST.in ├── .coveragerc ├── setup.cfg ├── dev-requirements.txt ├── sudo ├── mixins.py ├── models.py ├── __init__.py ├── decorators.py ├── signals.py ├── forms.py ├── settings.py ├── utils.py ├── middleware.py └── views.py ├── tox.ini ├── CONTRIBUTING.rst ├── docs ├── security │ └── index.rst ├── getting-started │ └── index.rst ├── index.rst ├── contributing │ └── index.rst ├── how │ └── index.rst ├── changelog │ └── index.rst ├── config │ └── index.rst ├── usage │ └── index.rst ├── make.bat ├── Makefile └── conf.py ├── .gitignore ├── tasks.py ├── conftest.py ├── README.md ├── setup.py ├── LICENSE └── .travis.yml /tests/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | -e . 2 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include setup.py README.md MANIFEST.in LICENSE 2 | -------------------------------------------------------------------------------- /.coveragerc: -------------------------------------------------------------------------------- 1 | [run] 2 | branch = True 3 | 4 | [paths] 5 | source = sudo 6 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [tool:pytest] 2 | python_files = tests/*.py 3 | 4 | [flake8] 5 | max-line-length = 88 6 | 7 | [wheel] 8 | universal = 1 9 | -------------------------------------------------------------------------------- /tests/urls.py: -------------------------------------------------------------------------------- 1 | from django.conf.urls import url 2 | 3 | from sudo import views 4 | 5 | 6 | urlpatterns = [ 7 | url(r"^sudo/", views.sudo, name="sudo"), 8 | ] 9 | -------------------------------------------------------------------------------- /dev-requirements.txt: -------------------------------------------------------------------------------- 1 | -e . 2 | flake8>=3.7.0,<3.8.0 3 | invoke==1.4.0 4 | pytest==4.6.5 5 | pytest-cov==2.5.1 6 | pytest-django==3.5.1 7 | sphinx 8 | sphinx_rtd_theme 9 | tox 10 | twine 11 | wheel 12 | -------------------------------------------------------------------------------- /sudo/mixins.py: -------------------------------------------------------------------------------- 1 | from sudo.decorators import sudo_required 2 | 3 | 4 | class SudoMixin(object): 5 | @classmethod 6 | def as_view(cls, **initkwargs): 7 | view = super(SudoMixin, cls).as_view(**initkwargs) 8 | return sudo_required(view) 9 | -------------------------------------------------------------------------------- /sudo/models.py: -------------------------------------------------------------------------------- 1 | """ 2 | sudo.models 3 | ~~~~~~~~~~~ 4 | 5 | :copyright: (c) 2020 by Matt Robenolt. 6 | :license: BSD, see LICENSE for more details. 7 | """ 8 | # Register signals automatically by installing the app 9 | from sudo.signals import * # noqa 10 | -------------------------------------------------------------------------------- /sudo/__init__.py: -------------------------------------------------------------------------------- 1 | """ 2 | sudo 3 | ~~~~ 4 | 5 | :copyright: (c) 2020 by Matt Robenolt. 6 | :license: BSD, see LICENSE for more details. 7 | """ 8 | 9 | try: 10 | VERSION = __import__("pkg_resources").get_distribution("sudo").version 11 | except Exception: # pragma: no cover 12 | VERSION = "unknown" 13 | -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | [tox] 2 | envlist = py27-django{19,110,111}, py36-django{19,110,111}, py37-django{19,110,111} 3 | 4 | [testenv] 5 | deps = 6 | -r dev-requirements.txt 7 | django19: Django >=1.9,<1.10 8 | django110: Django >=1.10,<1.11 9 | django111: Django >=1.11,<1.12 10 | commands = py.test --cov sudo --cov-report term-missing 11 | -------------------------------------------------------------------------------- /tests/models.py: -------------------------------------------------------------------------------- 1 | from django.db import models 2 | from django.contrib.auth.models import AbstractBaseUser 3 | 4 | 5 | class EmailUser(AbstractBaseUser): 6 | email = models.CharField(max_length=254, unique=True) 7 | 8 | USERNAME_FIELD = "email" 9 | 10 | def get_username(self): 11 | return self.email 12 | 13 | class Meta: 14 | app_label = "sudo_tests" 15 | -------------------------------------------------------------------------------- /CONTRIBUTING.rst: -------------------------------------------------------------------------------- 1 | Contributing 2 | ============ 3 | 4 | Security 5 | ~~~~~~~~ 6 | 7 | If you are submitting a security vulnerability, please don't submit a public issue or pull request. 8 | Instead, review our `security page `_ 9 | for more information. 10 | 11 | Tests 12 | ~~~~~ 13 | 14 | All patches submitted, must include 100% test coverage and there is no exception to this rule. 15 | -------------------------------------------------------------------------------- /docs/security/index.rst: -------------------------------------------------------------------------------- 1 | Security 2 | ======== 3 | 4 | We take the security of ``django-sudo`` seriously. If you believe you've 5 | identified a security vulnerability, please report it to ``matt@ydekproductions.com``. 6 | 7 | You may encrypt the message using the PGP fingerprint: ``D9D7 15C4 32A9 8C40 F794 35AB A54A 6FD1 5E45 9C77``. 8 | 9 | Once you've submitted an issue via email, you should receive an acknowledgement 10 | within 48 hours, and depending on the action to be taken, you may receive 11 | further follow-up emails. 12 | 13 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.py[cod] 2 | 3 | # C extensions 4 | *.so 5 | 6 | # Packages 7 | *.egg 8 | *.egg-info 9 | dist 10 | build 11 | eggs 12 | parts 13 | bin 14 | var 15 | sdist 16 | develop-eggs 17 | .installed.cfg 18 | lib 19 | lib64 20 | 21 | # Installer logs 22 | pip-log.txt 23 | 24 | # Unit test / coverage reports 25 | .coverage 26 | .tox 27 | nosetests.xml 28 | 29 | # Translations 30 | *.mo 31 | 32 | # Mr Developer 33 | .mr.developer.cfg 34 | .project 35 | .pydevproject 36 | 37 | # vim 38 | *.swp 39 | 40 | *.log 41 | *.pot 42 | local_settings.py 43 | 44 | docs/_build 45 | -------------------------------------------------------------------------------- /tests/decorators.py: -------------------------------------------------------------------------------- 1 | from .base import BaseTestCase 2 | 3 | from django.http import HttpResponse 4 | from sudo.decorators import sudo_required 5 | 6 | 7 | @sudo_required 8 | def foo(request): 9 | return HttpResponse() 10 | 11 | 12 | class SudoRequiredTestCase(BaseTestCase): 13 | def test_is_sudo(self): 14 | self.request.is_sudo = lambda: True 15 | response = foo(self.request) 16 | self.assertEqual(response.status_code, 200) 17 | 18 | def test_is_not_sudo(self): 19 | self.request.is_sudo = lambda: False 20 | response = foo(self.request) 21 | self.assertEqual(response.status_code, 302) 22 | self.assertEqual(response["Location"], "/sudo/?next=/foo") 23 | -------------------------------------------------------------------------------- /sudo/decorators.py: -------------------------------------------------------------------------------- 1 | """ 2 | sudo.decorators 3 | ~~~~~~~~~~~~~~~ 4 | 5 | :copyright: (c) 2020 by Matt Robenolt. 6 | :license: BSD, see LICENSE for more details. 7 | """ 8 | from functools import wraps 9 | 10 | from sudo.views import redirect_to_sudo 11 | 12 | 13 | def sudo_required(func): 14 | """ 15 | Enforces a view to have elevated privileges. 16 | Should likely be paired with ``@login_required``. 17 | 18 | >>> @sudo_required 19 | >>> def secure_page(request): 20 | >>> ... 21 | """ 22 | 23 | @wraps(func) 24 | def inner(request, *args, **kwargs): 25 | if not request.is_sudo(): 26 | return redirect_to_sudo(request.get_full_path()) 27 | return func(request, *args, **kwargs) 28 | 29 | return inner 30 | -------------------------------------------------------------------------------- /sudo/signals.py: -------------------------------------------------------------------------------- 1 | """ 2 | sudo.signals 3 | ~~~~~~~~~~~~ 4 | 5 | :copyright: (c) 2020 by Matt Robenolt. 6 | :license: BSD, see LICENSE for more details. 7 | """ 8 | from django.contrib.auth.signals import user_logged_in, user_logged_out 9 | from django.dispatch import receiver 10 | 11 | from sudo.utils import grant_sudo_privileges, revoke_sudo_privileges 12 | 13 | 14 | @receiver(user_logged_in) 15 | def grant(sender, request, **kwargs): 16 | """ 17 | Automatically grant sudo privileges when logging in. 18 | """ 19 | grant_sudo_privileges(request) 20 | 21 | 22 | @receiver(user_logged_out) 23 | def revoke(sender, request, **kwargs): 24 | """ 25 | Automatically revoke sudo privileges when logging out. 26 | """ 27 | revoke_sudo_privileges(request) 28 | -------------------------------------------------------------------------------- /tests/mixins.py: -------------------------------------------------------------------------------- 1 | from .base import BaseTestCase 2 | from django.http import HttpResponse 3 | from django.views import generic 4 | from sudo.mixins import SudoMixin 5 | 6 | 7 | class FooView(SudoMixin, generic.View): 8 | def get(self, request): 9 | return HttpResponse() 10 | 11 | 12 | foo = FooView.as_view() 13 | 14 | 15 | class SudoMixinTestCase(BaseTestCase): 16 | def test_is_sudo(self): 17 | self.request.is_sudo = lambda: True 18 | response = foo(self.request) 19 | self.assertEqual(response.status_code, 200) 20 | 21 | def test_is_not_sudo(self): 22 | self.request.is_sudo = lambda: False 23 | response = foo(self.request) 24 | self.assertEqual(response.status_code, 302) 25 | self.assertEqual(response["Location"], "/sudo/?next=/foo") 26 | -------------------------------------------------------------------------------- /sudo/forms.py: -------------------------------------------------------------------------------- 1 | """ 2 | sudo.forms 3 | ~~~~~~~~~~ 4 | 5 | :copyright: (c) 2020 by Matt Robenolt. 6 | :license: BSD, see LICENSE for more details. 7 | """ 8 | from django import forms 9 | from django.contrib import auth 10 | from django.utils.translation import ugettext_lazy as _ 11 | 12 | 13 | class SudoForm(forms.Form): 14 | """ 15 | A simple password input form used by the default :func:`~sudo.views.sudo` view. 16 | """ 17 | 18 | password = forms.CharField(label=_("Password"), widget=forms.PasswordInput) 19 | 20 | def __init__(self, user, *args, **kwargs): 21 | self.user = user 22 | super(SudoForm, self).__init__(*args, **kwargs) 23 | 24 | def clean_password(self): 25 | username = self.user.get_username() 26 | if auth.authenticate(username=username, password=self.data["password"]): 27 | return self.data["password"] 28 | raise forms.ValidationError(_("Incorrect password")) 29 | -------------------------------------------------------------------------------- /docs/getting-started/index.rst: -------------------------------------------------------------------------------- 1 | Getting Started 2 | =============== 3 | 4 | Installation 5 | ~~~~~~~~~~~~ 6 | 7 | First, install the ``django-sudo`` library with `pip `_. 8 | 9 | .. code-block:: console 10 | 11 | $ pip install django-sudo 12 | 13 | Next, we need to add the ``sudo`` application to our ``INSTALLED_APPS``. Installing the application 14 | will automatically register the ``user_logged_in`` and ``user_logged_out`` signals that are needed. 15 | 16 | .. code-block:: python 17 | 18 | INSTALLED_APPS = ( 19 | # ... 20 | 'sudo', 21 | ) 22 | 23 | Now we need to install the required middleware into ``MIDDLEWARE_CLASSES``: 24 | 25 | .. code-block:: python 26 | 27 | MIDDLEWARE_CLASSES = ( 28 | # ... 29 | 'sudo.middleware.SudoMiddleware', 30 | ) 31 | 32 | .. note:: 33 | 34 | ``sudo.middleware.SudoMiddleware`` **must** be installed after 35 | ``django.contrib.session.middleware.SessionMiddleware``. 36 | 37 | Proceed to the :doc:`/config/index` documentation. 38 | -------------------------------------------------------------------------------- /tests/base.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | from django.test import RequestFactory 4 | from django.contrib.auth.models import User, AnonymousUser 5 | 6 | 7 | class StubPasswordBackend(object): 8 | """ Stub backend 9 | 10 | Always authenticates when the password matches self.password 11 | 12 | """ 13 | 14 | password = "stub" 15 | 16 | def authenticate(self, username, password): 17 | if password == self.password: 18 | return User() 19 | 20 | 21 | class FooPasswordBackend(StubPasswordBackend): 22 | password = "foo" 23 | 24 | 25 | class BaseTestCase(unittest.TestCase): 26 | def setUp(self): 27 | self.request = self.get("/foo") 28 | self.request.session = {} 29 | self.setUser(AnonymousUser()) 30 | 31 | def get(self, *args, **kwargs): 32 | return RequestFactory().get(*args, **kwargs) 33 | 34 | def post(self, *args, **kwargs): 35 | return RequestFactory().post(*args, **kwargs) 36 | 37 | def setUser(self, user): 38 | self.user = self.request.user = user 39 | 40 | def login(self, user_class=User): 41 | user = user_class() 42 | self.setUser(user) 43 | -------------------------------------------------------------------------------- /tests/signals.py: -------------------------------------------------------------------------------- 1 | from .base import BaseTestCase 2 | from sudo.signals import grant, revoke 3 | from sudo.utils import has_sudo_privileges, grant_sudo_privileges 4 | from django.contrib.auth.models import User 5 | from django.contrib.auth.signals import user_logged_in, user_logged_out 6 | 7 | 8 | class SignalsTestCase(BaseTestCase): 9 | def test_grant(self): 10 | self.login() 11 | grant(User, self.request) 12 | self.assertTrue(has_sudo_privileges(self.request)) 13 | 14 | def test_revoke(self): 15 | self.login() 16 | grant(User, self.request) 17 | revoke(User, self.request) 18 | self.assertFalse(has_sudo_privileges(self.request)) 19 | 20 | def test_user_logged_in(self): 21 | self.login() 22 | user_logged_in.send_robust(sender=User, request=self.request) 23 | self.assertTrue(has_sudo_privileges(self.request)) 24 | 25 | def test_user_logged_out(self): 26 | self.login() 27 | grant_sudo_privileges(self.request) 28 | self.assertTrue(has_sudo_privileges(self.request)) 29 | user_logged_out.send_robust(sender=User, request=self.request) 30 | self.assertFalse(has_sudo_privileges(self.request)) 31 | -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | Welcome to ``django-sudo`` 2 | ========================== 3 | 4 | ``django-sudo`` is an implementation of GitHub's `Sudo Mode 5 | `_ for `Django 6 | `_. 7 | 8 | What is this for? 9 | ~~~~~~~~~~~~~~~~~ 10 | ``django-sudo`` provides an extra layer of security for after a user is already logged in. Views can 11 | be decorated with :func:`@sudo_required `, and then a user 12 | must re-enter their password to view that page. After verifying their password, that user has 13 | elevated permissions for the duration of ``SUDO_COOKIE_AGE``. This duration is independent of the 14 | normal session duration allowing short elevated permission durations, but retain long user sessions. 15 | 16 | Installation 17 | ~~~~~~~~~~~~ 18 | 19 | .. code-block:: console 20 | 21 | $ pip install django-sudo 22 | 23 | Compatibility 24 | ~~~~~~~~~~~~~ 25 | * Django 1.4-1.9 26 | * Python 2.6-3.5 27 | * pypy 28 | 29 | Contents 30 | ~~~~~~~~ 31 | 32 | .. toctree:: 33 | :maxdepth: 2 34 | 35 | getting-started/index 36 | config/index 37 | usage/index 38 | contributing/index 39 | how/index 40 | security/index 41 | changelog/index 42 | -------------------------------------------------------------------------------- /tasks.py: -------------------------------------------------------------------------------- 1 | from invoke import run as _run, task 2 | from functools import partial 3 | 4 | # Always echo out the commands 5 | run = partial(_run, echo=True, pty=True) 6 | 7 | 8 | files = "sudo tests *.py" 9 | 10 | 11 | @task 12 | def lint(c, verbose=False): 13 | "Run flake8 linter" 14 | run("flake8 %s %s" % (files, "-v" if verbose else "")) 15 | run("black --check %s" % files) 16 | 17 | 18 | @task 19 | def format(c): 20 | "Run black" 21 | run("black %s" % files) 22 | 23 | 24 | @task 25 | def test(c, verbose=False): 26 | "Run tests using py.test" 27 | run("py.test --cov sudo --cov-report term-missing %s" % ("-v" if verbose else "")) 28 | 29 | 30 | @task 31 | def clean(c): 32 | "Clean working directory" 33 | run("rm -rf *.egg-info *.egg") 34 | run("rm -rf dist build") 35 | 36 | 37 | @task(clean) 38 | def release(c): 39 | "Cut a new release" 40 | version = run("python setup.py --version").stdout.strip() 41 | assert version, "No version found in setup.py?" 42 | 43 | print("### Releasing new version: %s" % version) 44 | run("git tag %s" % version) 45 | run("git push --tags") 46 | 47 | run("python setup.py sdist bdist_wheel") 48 | run("twine check dist/*") 49 | run("twine upload -s dist/*") 50 | -------------------------------------------------------------------------------- /conftest.py: -------------------------------------------------------------------------------- 1 | INSTALLED_APPS = [ 2 | "django.contrib.auth", 3 | "django.contrib.sessions", 4 | "django.contrib.contenttypes", 5 | "sudo", 6 | ] 7 | 8 | MIDDLEWARE_CLASSES = [ 9 | "django.contrib.sessions.middleware.SessionMiddleware", 10 | "django.contrib.auth.middleware.AuthenticationMiddleware", 11 | ] 12 | 13 | 14 | def pytest_report_header(config): 15 | return "made with love: <3" 16 | 17 | 18 | def pytest_configure(config): 19 | from django.conf import settings 20 | 21 | settings.configure( 22 | AUTHENTICATION_BACKENDS=[ 23 | "tests.base.FooPasswordBackend", 24 | "tests.base.StubPasswordBackend", 25 | ], 26 | DEBUG=True, 27 | DATABASE_ENGINE="sqlite3", 28 | DATABASES={ 29 | "default": { 30 | "NAME": ":memory:", 31 | "ENGINE": "django.db.backends.sqlite3", 32 | "TEST_NAME": ":memory:", 33 | }, 34 | }, 35 | DATABASE_NAME=":memory:", 36 | TEST_DATABASE_NAME=":memory:", 37 | INSTALLED_APPS=INSTALLED_APPS, 38 | MIDDLEWARE_CLASSES=MIDDLEWARE_CLASSES, 39 | PASSWORD_HASHERS=["django.contrib.auth.hashers.MD5PasswordHasher"], 40 | ROOT_URLCONF="tests.urls", 41 | ) 42 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # django-sudo 2 | 3 | [![](https://travis-ci.org/mattrobenolt/django-sudo.svg?branch=master)](https://travis-ci.org/mattrobenolt/django-sudo) [![](https://coveralls.io/repos/mattrobenolt/django-sudo/badge.png?branch=master)](https://coveralls.io/r/mattrobenolt/django-sudo?branch=master) 4 | 5 | > Sudo mode is an extra layer of security for your most sensitive pages.
6 | > This is an implementation of GitHub's [Sudo Mode](https://github.com/blog/1513-introducing-github-sudo-mode) for [Django](https://www.djangoproject.com/). 7 | 8 | ## What is this for? 9 | 10 | `django-sudo` provides an extra layer of security for after a user is already logged in. Views can 11 | be decorated with `@sudo_required`, and then a user 12 | must re-enter their password to view that page. After verifying their password, that user has 13 | elevated permissions for the duration of `SUDO_COOKIE_AGE`. This duration is independent of the 14 | normal session duration allowing short elevated permission durations, but retain long user sessions. 15 | 16 | ## Installation 17 | 18 | ```console 19 | $ pip install django-sudo 20 | ``` 21 | 22 | ## Compatibility 23 | 24 | * Django 1.9-1.11 25 | * Python 2.7, 3.6-3.7 26 | 27 | ## Resources 28 | 29 | * [Documentation](https://django-sudo.readthedocs.io/) 30 | * [Security](https://django-sudo.readthedocs.io/en/latest/security/index.html) 31 | * [Changelog](https://django-sudo.readthedocs.io/en/latest/changelog/index.html) 32 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """ 3 | django-sudo 4 | ~~~~~~~~~~~ 5 | 6 | :copyright: (c) 2016 by Matt Robenolt. 7 | :license: BSD, see LICENSE for more details. 8 | """ 9 | from setuptools import setup, find_packages 10 | 11 | install_requires = [] 12 | 13 | with open("README.md") as f: 14 | long_description = f.read() 15 | 16 | 17 | setup( 18 | name="django-sudo", 19 | version="3.1.0", 20 | author="Matt Robenolt", 21 | author_email="matt@ydekproductions.com", 22 | url="https://github.com/mattrobenolt/django-sudo", 23 | description="Extra security for your sensitive pages", 24 | license="BSD", 25 | long_description=long_description, 26 | long_description_content_type="text/markdown", 27 | packages=find_packages(exclude=["tests"]), 28 | install_requires=install_requires, 29 | zip_safe=True, 30 | classifiers=[ 31 | "Development Status :: 5 - Production/Stable", 32 | "Framework :: Django", 33 | "Intended Audience :: Developers", 34 | "License :: OSI Approved :: BSD License", 35 | "Operating System :: OS Independent", 36 | "Programming Language :: Python :: 2", 37 | "Programming Language :: Python :: 2.7", 38 | "Programming Language :: Python :: 3", 39 | "Programming Language :: Python :: 3.6", 40 | "Programming Language :: Python :: 3.7", 41 | "Programming Language :: Python", 42 | "Topic :: Software Development", 43 | ], 44 | ) 45 | -------------------------------------------------------------------------------- /docs/contributing/index.rst: -------------------------------------------------------------------------------- 1 | Contributing 2 | ============ 3 | 4 | Getting the source 5 | ~~~~~~~~~~~~~~~~~~ 6 | 7 | You will first want to clone the source repository locally with ``git``: 8 | 9 | .. code-block:: console 10 | 11 | $ git clone git@github.com:mattrobenolt/django-sudo.git 12 | 13 | 14 | Setup Environment 15 | ~~~~~~~~~~~~~~~~~ 16 | 17 | I would recommend using `virtualenv `_ to set up a dev 18 | environment. After creating an environment, install all dep dependencies with: 19 | 20 | .. code-block:: console 21 | 22 | $ pip install -r dev-requirements.txt 23 | 24 | Running Tests 25 | ~~~~~~~~~~~~~ 26 | 27 | Tests are run using `pytest `_ and can be found inside 28 | ``tests/*``. 29 | 30 | Tests can simply be run using: 31 | 32 | .. code-block:: console 33 | 34 | $ py.test 35 | 36 | This will discover and run the test suite using your default Python interpreter. To run tests 37 | for all supported platforms, we use `tox `_. 38 | 39 | .. code-block:: console 40 | 41 | $ tox 42 | 43 | Submitting Patches 44 | ~~~~~~~~~~~~~~~~~~ 45 | 46 | Patches are accepted via `Pull Requests `_ on 47 | GitHub. 48 | 49 | .. note:: 50 | 51 | If you are submitting a security patch, please see our :doc:`/security/index` page for special 52 | instructions. 53 | 54 | Tests 55 | ----- 56 | 57 | All new code and changed code must come with **100%** test coverage to be considered for acceptance. 58 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2020, Matt Robenolt 2 | All rights reserved. 3 | 4 | Redistribution and use in source and binary forms, with or without modification, 5 | are permitted provided that the following conditions are met: 6 | 7 | Redistributions of source code must retain the above copyright notice, this 8 | list of conditions and the following disclaimer. 9 | 10 | Redistributions in binary form must reproduce the above copyright notice, this 11 | list of conditions and the following disclaimer in the documentation and/or 12 | other materials provided with the distribution. 13 | 14 | Neither the name of the {organization} nor the names of its 15 | contributors may be used to endorse or promote products derived from 16 | this software without specific prior written permission. 17 | 18 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 19 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 20 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 21 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR 22 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 23 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 24 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 25 | ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 26 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 27 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 28 | -------------------------------------------------------------------------------- /tests/forms.py: -------------------------------------------------------------------------------- 1 | from .base import BaseTestCase 2 | from .models import EmailUser 3 | 4 | from django.forms import ValidationError 5 | from sudo.forms import SudoForm 6 | 7 | 8 | class SudoFormTestCase(BaseTestCase): 9 | def setUp(self): 10 | super(SudoFormTestCase, self).setUp() 11 | self.login() 12 | 13 | def test_integration_empty(self): 14 | self.assertFalse(SudoForm(self.user).is_valid()) 15 | 16 | def test_integration_invalid_password(self): 17 | self.assertFalse(SudoForm(self.user, {"password": "lol"}).is_valid()) 18 | 19 | def test_integration_valid_password(self): 20 | self.assertTrue(SudoForm(self.user, {"password": "foo"}).is_valid()) 21 | 22 | def test_integration_secondary_auth_valid_password(self): 23 | self.assertTrue(SudoForm(self.user, {"password": "stub"}).is_valid()) 24 | 25 | def test_clean_password_invalid_password(self): 26 | with self.assertRaises(ValidationError): 27 | SudoForm(self.user, {"password": "lol"}).clean_password() 28 | 29 | def test_clean_password_valid_password(self): 30 | password = "foo" 31 | self.assertEqual( 32 | SudoForm(self.user, {"password": password}).clean_password(), password 33 | ) 34 | 35 | def test_clean_password_secondary_auth_valid_password(self): 36 | password = "stub" 37 | self.assertEqual( 38 | SudoForm(self.user, {"password": password}).clean_password(), password 39 | ) 40 | 41 | def test_integration_custom_user(self): 42 | self.login(EmailUser) 43 | self.assertTrue(SudoForm(self.user, {"password": "foo"}).is_valid()) 44 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | dist: xenial 2 | language: python 3 | install: 4 | - pip install $DJANGO 5 | - pip install coveralls 6 | - pip install --upgrade -r dev-requirements.txt 7 | script: 8 | - inv test 9 | after_success: 10 | - coveralls 11 | matrix: 12 | include: 13 | - python: "2.7" 14 | name: 'Linter (Python 2.7)' 15 | install: 16 | - pip install --upgrade -r dev-requirements.txt 17 | script: flake8 sudo tests *.py 18 | - python: "3.7" 19 | name: 'Linter (Python 3.7)' 20 | install: 21 | - pip install --upgrade -r dev-requirements.txt 22 | script: flake8 sudo tests *.py 23 | - python: "3.7" 24 | name: 'black' 25 | install: 26 | - pip install black==19.10b0 27 | script: black --check sudo tests *.py 28 | - python: "2.7" 29 | name: "Python 2.7, Django 1.9" 30 | env: DJANGO="Django>=1.9,<1.10" 31 | - python: "2.7" 32 | name: "Python 2.7, Django 1.10" 33 | env: DJANGO="Django>=1.10,<1.11" 34 | - python: "2.7" 35 | name: "Python 2.7, Django 1.11" 36 | env: DJANGO="Django>=1.11,<1.12" 37 | - python: "3.6" 38 | name: "Python 3.6, Django 1.9" 39 | env: DJANGO="Django>=1.9,<1.10" 40 | - python: "3.6" 41 | name: "Python 3.6, Django 1.10" 42 | env: DJANGO="Django>=1.10,<1.11" 43 | - python: "3.6" 44 | name: "Python 3.6, Django 1.11" 45 | env: DJANGO="Django>=1.11,<1.12" 46 | - python: "3.7" 47 | name: "Python 3.7, Django 1.9" 48 | env: DJANGO="Django>=1.9,<1.10" 49 | - python: "3.7" 50 | name: "Python 3.7, Django 1.10" 51 | env: DJANGO="Django>=1.10,<1.11" 52 | - python: "3.7" 53 | name: "Python 3.7, Django 1.11" 54 | env: DJANGO="Django>=1.11,<1.12" 55 | -------------------------------------------------------------------------------- /docs/how/index.rst: -------------------------------------------------------------------------------- 1 | How does this work? 2 | =================== 3 | 4 | ``django-sudo`` works by setting an additional cookie that must match a secret value in your 5 | session. This cookie is ideally set to a shorter TTL than the normal session. When not in sudo mode, 6 | any view that is decorated with ``@sudo_required`` will require the user to re-enter their password. 7 | Once in sudo mode, they won't be prompted to enter their password for the next ``SUDO_COOKIE_AGE`` 8 | seconds. 9 | 10 | In practice, we want to serve this sudo cookie over https only to avoid a man-in-the-middle attack 11 | where someone hijacks this cookie. This can be utilized safely in situations where the sessionid 12 | cookie is being transmitted over http, but we want to make sure that secure areas of our site are 13 | not accessible with just the sessionid. 14 | 15 | * When logging in, ``django-sudo`` automatically elevates your permission to ``sudo mode``. 16 | * A second cookie is sent to your browser (by default this cookie is named ``sudo`` but can be set 17 | to anything with ``SUDO_COOKIE_NAME``). This cookie contains a randomly generated string of 18 | characters. 19 | * The same randomly generated string of characters is stored in the user's session. 20 | * On subsequent requests, the cookie value must match the value that was stored in the session. 21 | If the values do not match, or the cookie is not sent at all, the user will be redirected to a 22 | page to re-enter their password. 23 | * If they re-enter their password successfully, a new cookie is set and their permissions are again 24 | elevated. 25 | 26 | .. note:: 27 | 28 | The best way to secure your site and your users is to use https. ``django-sudo`` won't be able 29 | to help you if it's being served over http. 30 | -------------------------------------------------------------------------------- /sudo/settings.py: -------------------------------------------------------------------------------- 1 | """ 2 | sudo.settings 3 | ~~~~~~~~~~~~~ 4 | 5 | :copyright: (c) 2020 by Matt Robenolt. 6 | :license: BSD, see LICENSE for more details. 7 | """ 8 | from django.conf import settings 9 | 10 | # Default url to be redirected to after elevating permissions 11 | REDIRECT_URL = getattr(settings, "SUDO_REDIRECT_URL", "/") 12 | 13 | # The querystring argument to be used for redirection 14 | REDIRECT_FIELD_NAME = getattr(settings, "SUDO_REDIRECT_FIELD_NAME", "next") 15 | 16 | # How long should sudo mode be active for? Duration in seconds. 17 | COOKIE_AGE = getattr(settings, "SUDO_COOKIE_AGE", 10800) 18 | 19 | # The domain to bind the sudo cookie to. Default to the current domain. 20 | COOKIE_DOMAIN = getattr(settings, "SUDO_COOKIE_DOMAIN", None) 21 | 22 | # Should the cookie only be accessible via http requests? 23 | # Note: If this is set to False, any JavaScript files have the ability to access 24 | # this cookie, so this should only be changed if you have a good reason to do so. 25 | COOKIE_HTTPONLY = getattr(settings, "SUDO_COOKIE_HTTPONLY", True) 26 | 27 | # The name of the cookie to be used for sudo mode. 28 | COOKIE_NAME = getattr(settings, "SUDO_COOKIE_NAME", "sudo") 29 | 30 | # Restrict the sudo cookie to a specific path. 31 | COOKIE_PATH = getattr(settings, "SUDO_COOKIE_PATH", "/") 32 | 33 | # Only transmit the sudo cookie over https if True. 34 | # By default, this will match the current protocol. If your site is 35 | # https already, this will be True. 36 | COOKIE_SECURE = getattr(settings, "SUDO_COOKIE_SECURE", None) 37 | 38 | # An extra salt to be added into the cookie signature 39 | COOKIE_SALT = getattr(settings, "SUDO_COOKIE_SALT", "") 40 | 41 | # The name of the session attribute used to preserve the redirect destination 42 | # between the original page request and successful sudo login. 43 | REDIRECT_TO_FIELD_NAME = getattr( 44 | settings, "SUDO_REDIRECT_TO_FIELD_NAME", "sudo_redirect_to" 45 | ) 46 | 47 | # The url for the sudo page itself. May be a url or a view name 48 | URL = getattr(settings, "SUDO_URL", "sudo.views.sudo") 49 | -------------------------------------------------------------------------------- /sudo/utils.py: -------------------------------------------------------------------------------- 1 | """ 2 | sudo.utils 3 | ~~~~~~~~~~ 4 | 5 | :copyright: (c) 2020 by Matt Robenolt. 6 | :license: BSD, see LICENSE for more details. 7 | """ 8 | from django.core.signing import BadSignature 9 | from django.utils.crypto import get_random_string, constant_time_compare 10 | 11 | # alias for backwards compatibility with older django-sudo versions 12 | from django.utils.http import is_safe_url # NOQA 13 | 14 | from sudo.settings import COOKIE_NAME, COOKIE_AGE, COOKIE_SALT 15 | 16 | 17 | def grant_sudo_privileges(request, max_age=COOKIE_AGE): 18 | """ 19 | Assigns a random token to the user's session 20 | that allows them to have elevated permissions 21 | """ 22 | user = getattr(request, "user", None) 23 | 24 | # If there's not a user on the request, just noop 25 | if user is None: 26 | return 27 | 28 | if not user.is_authenticated(): 29 | raise ValueError("User needs to be logged in to be elevated to sudo") 30 | 31 | # Token doesn't need to be unique, 32 | # just needs to be unpredictable and match the cookie and the session 33 | token = get_random_string() 34 | request.session[COOKIE_NAME] = token 35 | request._sudo = True 36 | request._sudo_token = token 37 | request._sudo_max_age = max_age 38 | return token 39 | 40 | 41 | def revoke_sudo_privileges(request): 42 | """ 43 | Revoke sudo privileges from a request explicitly 44 | """ 45 | request._sudo = False 46 | if COOKIE_NAME in request.session: 47 | del request.session[COOKIE_NAME] 48 | 49 | 50 | def has_sudo_privileges(request): 51 | """ 52 | Check if a request is allowed to perform sudo actions 53 | """ 54 | if getattr(request, "_sudo", None) is None: 55 | try: 56 | request._sudo = request.user.is_authenticated() and constant_time_compare( 57 | request.get_signed_cookie( 58 | COOKIE_NAME, salt=COOKIE_SALT, max_age=COOKIE_AGE 59 | ), 60 | request.session[COOKIE_NAME], 61 | ) 62 | except (KeyError, BadSignature): 63 | request._sudo = False 64 | return request._sudo 65 | -------------------------------------------------------------------------------- /sudo/middleware.py: -------------------------------------------------------------------------------- 1 | """ 2 | sudo.middleware 3 | ~~~~~~~~~~~~~~~ 4 | 5 | :copyright: (c) 2020 by Matt Robenolt. 6 | :license: BSD, see LICENSE for more details. 7 | """ 8 | from sudo.settings import ( 9 | COOKIE_DOMAIN, 10 | COOKIE_HTTPONLY, 11 | COOKIE_NAME, 12 | COOKIE_PATH, 13 | COOKIE_SECURE, 14 | COOKIE_SALT, 15 | ) 16 | from sudo.utils import has_sudo_privileges 17 | 18 | 19 | class SudoMiddleware(object): 20 | """ 21 | Middleware that contributes ``request.is_sudo()`` and sets the required 22 | cookie for sudo mode to work correctly. 23 | """ 24 | 25 | def has_sudo_privileges(self, request): 26 | # Override me to alter behavior 27 | return has_sudo_privileges(request) 28 | 29 | def process_request(self, request): 30 | assert hasattr(request, "session"), ( 31 | "The Sudo middleware requires session middleware to be installed." 32 | "Edit your MIDDLEWARE_CLASSES setting to insert " 33 | "'django.contrib.sessions.middleware.SessionMiddleware' before " 34 | "'sudo.middleware.SudoMiddleware'." 35 | ) 36 | request.is_sudo = lambda: self.has_sudo_privileges(request) 37 | 38 | def process_response(self, request, response): 39 | is_sudo = getattr(request, "_sudo", None) 40 | 41 | if is_sudo is None: 42 | return response 43 | 44 | # We have explicitly had sudo revoked, so clean up cookie 45 | if is_sudo is False and COOKIE_NAME in request.COOKIES: 46 | response.delete_cookie(COOKIE_NAME) 47 | return response 48 | 49 | # Sudo mode has been granted, 50 | # and we have a token to send back to the user agent 51 | if is_sudo is True and hasattr(request, "_sudo_token"): 52 | token = request._sudo_token 53 | max_age = request._sudo_max_age 54 | response.set_signed_cookie( 55 | COOKIE_NAME, 56 | token, 57 | salt=COOKIE_SALT, 58 | max_age=max_age, # If max_age is None, it's a session cookie 59 | secure=request.is_secure() if COOKIE_SECURE is None else COOKIE_SECURE, 60 | httponly=COOKIE_HTTPONLY, # Not accessible by JavaScript 61 | path=COOKIE_PATH, 62 | domain=COOKIE_DOMAIN, 63 | ) 64 | 65 | return response 66 | -------------------------------------------------------------------------------- /docs/changelog/index.rst: -------------------------------------------------------------------------------- 1 | Changelog 2 | ========= 3 | 4 | 3.1.0 5 | ~~~~~ 6 | * Added support for Django 1.11 7 | * Removed vendored ``is_safe_url`` function because modern Django has a sufficient version. Import alias is left around. 8 | 9 | 3.0.0 10 | ~~~~~ 11 | * Added support for Django 1.10 12 | * Dropped support for Django < 1.9 13 | * Dropped support for Python 2.6, 3.3, 3.4, and 3.5 14 | 15 | 2.1.0 16 | ~~~~~ 17 | * Vendored a more secure ``is_safe_url`` implementation from latest Django, instead of relying on a potentially insecure bundled version. 18 | See `#17 `_. 19 | 20 | 2.0.1 21 | ~~~~~ 22 | * Added ``sudo.views.SudoView`` class based view. This is now more extensible and 23 | should be preferred over the older ``sudo.views.sudo`` view function. 24 | * Removed ``SUDO_FORM`` setting. It's now suggested to subclass ``sudo.views.SudoView`` 25 | and override ``form_class``. 26 | * Added ``SUDO_URL`` setting to set the url for the sudo page. 27 | 28 | 29 | 2.0.0 30 | ~~~~~ 31 | * Bad release. :( Don't install. 32 | 33 | 1.3.0 34 | ~~~~~ 35 | * Store ``redirect_to`` value in session. 36 | See `#10 `_. 37 | 38 | 1.2.1 39 | ~~~~~ 40 | * Pass along ``request`` to template context 41 | See `#8 `_. 42 | * Verified compatibility with Django 1.9 43 | 44 | 1.2.0 45 | ~~~~~ 46 | * Verified compatibility with python 3.5 and pypy3 47 | * Verified compatibility with Django 1.8 48 | * Dropped support for python 3.2 49 | * Better support for custom User models. 50 | See `#4 `_. 51 | * Added a ``SudoMixin`` for use with class based views. 52 | See `#5 `_. 53 | 54 | 1.1.3 55 | ~~~~~ 56 | * Use ``constant_time_compare`` when verifying the correct sudo token. 57 | * Make sure to check against all ``AUTHENTICATION_BACKENDS`` for the ``SudoForm``. 58 | See `#3 `_. 59 | 60 | 1.1.2 61 | ~~~~~ 62 | * Added new setting, ``SUDO_FORM`` which allows you to override the default form that is used. 63 | See `#2 `_. 64 | 65 | 1.1.1 66 | ~~~~~ 67 | * Fixed a bug when using the new ``SUDO_COOKIE_SALT``. 68 | If specifying a non-default salt, all cookies would be marked incorrectly 69 | as invalid. 70 | * Don't use ``request.REQUEST`` anymore since that's deprecated in modern Django. 71 | Always use ``request.GET`` instead since we never POSTed the ``next`` variable anyways. 72 | 73 | 1.1.0 74 | ~~~~~ 75 | * Switch to using signed cookies for the sudo cookie, 76 | see `#1 `_. 77 | * Added new ``SUDO_COOKIE_SALT`` setting to go along with the signed cookie. 78 | 79 | 1.0.0 80 | ~~~~~ 81 | 82 | * Initial release 83 | -------------------------------------------------------------------------------- /docs/config/index.rst: -------------------------------------------------------------------------------- 1 | Configuration 2 | ============= 3 | 4 | Settings 5 | ~~~~~~~~ 6 | 7 | By default, all of the settings are optional and define sane and secure defaults. 8 | 9 | ``SUDO_URL`` 10 | The url or view name for the sudo view. *Default: sudo.views.sudo* 11 | 12 | ``SUDO_REDIRECT_URL`` 13 | Default url to be redirected to after elevating permissions. *Default: /* 14 | 15 | ``SUDO_REDIRECT_FIELD_NAME`` 16 | The querystring argument to be used for redirection. *Default: next* 17 | 18 | ``SUDO_COOKIE_AGE`` 19 | How long should sudo mode be active for? Duration in seconds. *Default: 10800* 20 | 21 | ``SUDO_COOKIE_DOMAIN`` 22 | The domain to bind the sudo cookie to. *Default: current exact domain*. 23 | 24 | ``SUDO_COOKIE_HTTPONLY`` 25 | Should the cookie only be accessible via http requests? *Default: True* 26 | 27 | .. note:: 28 | If this is set to ``False``, any JavaScript files have the ability to access this cookie, 29 | so this should only be changed if you have a good reason to do so. 30 | 31 | ``SUDO_COOKIE_NAME`` 32 | The name of the cookie to be used for sudo mode. *Default: sudo* 33 | 34 | ``SUDO_COOKIE_PATH`` 35 | Restrict the sudo cookie to a specific path. *Default: /* 36 | 37 | ``SUDO_COOKIE_SECURE`` 38 | Only transmit the sudo cookie over https if True. *Default: matches current protocol* 39 | 40 | .. note:: 41 | By default, we will match the protocol that made the request. So if your sudo page is over 42 | https, we will set the ``secure`` flag on the cookie so it won't be transmitted over plain 43 | http. It is highly recommended that you only use ``django-sudo`` over https. 44 | 45 | ``SUDO_COOKIE_SALT`` 46 | An extra salt to be added into the cookie signature. *Default: ''* 47 | 48 | ``SUDO_REDIRECT_TO_FIELD_NAME`` 49 | The name of the session attribute used to preserve the redirect destination 50 | between the original page request and successful sudo login. *Default: sudo_redirect_to* 51 | 52 | Set up URLs 53 | ~~~~~~~~~~~ 54 | 55 | We need to hook up one url to use ``django-sudo`` properly. At minimum, you need something like 56 | the following: 57 | 58 | .. code-block:: python 59 | 60 | (r'^sudo/$', # Whatever path you want 61 | 'sudo.views.sudo', # Required 62 | {'template_name': 'sudo/sudo.html'} # Optionally change the template to be used 63 | ) 64 | 65 | Required Template 66 | ~~~~~~~~~~~~~~~~~ 67 | 68 | To get up and running, we last need to create a template for the sudo page to render. By default, 69 | the package will look for ``sudo/sudo.html`` but can easily be overwritten by setting the 70 | ``template_name`` when defining the url definition as seen above. 71 | 72 | sudo/sudo.html 73 | -------------- 74 | 75 | This template gets rendered with the the following context: 76 | 77 | ``form`` 78 | An instance of :class:`~sudo.forms.SudoForm`. 79 | 80 | ``SUDO_REDIRECT_FIELD_NAME`` 81 | The value of ``?next=/foo/``. If ``SUDO_REDIRECT_FIELD_NAME`` is ``name``, then expect to find 82 | ``{{ next }}`` in the context, with the value of ``/foo/``. 83 | 84 | 85 | After configuring things, we can now :doc:`start securing pages `. 86 | -------------------------------------------------------------------------------- /docs/usage/index.rst: -------------------------------------------------------------------------------- 1 | Usage 2 | ===== 3 | 4 | Once we have ``django-sudo`` :doc:`installed ` and 5 | :doc:`configured `, we need to decide which views should be secured. 6 | 7 | .. function:: sudo.decorators.sudo_required() 8 | 9 | The meat of ``django-sudo`` comes from decorating your views with ``@sudo_required`` much in the 10 | same way that ``@login_required`` works. 11 | 12 | Let's pretend that we have a page on our site that has sensitive information that we want to make 13 | extra sure that a user is allowed to see it: 14 | 15 | .. code-block:: python 16 | 17 | from sudo.decorators import sudo_required 18 | 19 | @login_required # Make sure they're at least logged in 20 | @sudo_required # On top of being logged in, are you in sudo mode? 21 | def super_secret_stuff(request): 22 | return HttpResponse('your social security number') 23 | 24 | That's it! When a user visits this page and they don't have the correct permission, they'll be 25 | redirected to a page and prompted for their password. After entering their password, they'll be 26 | redirected back to this page to continue on what they were trying to do. 27 | 28 | .. class:: sudo.mixins.SudoMixin 29 | 30 | ``SudoMixin`` provides an easy way to sudo a class-based view. Any view 31 | that inherits from this mixin is automatically wrapped by the 32 | ``@sudo_required`` decorator. 33 | 34 | This works well with the ``LoginRequiredMixin`` from 35 | `django-braces `_: 36 | 37 | .. code-block:: python 38 | 39 | from django.views import generic 40 | from braces.views import LoginRequiredMixin 41 | from sudo.mixins import SudoMixin 42 | 43 | class SuperSecretView(LoginRequiredMixin, SudoMixin, generic.TemplateView): 44 | template_name = 'secret/super-secret.html' 45 | 46 | .. method:: request.is_sudo() 47 | 48 | Returns a boolean to indicate if the current request is in sudo mode or not. This gets added on by 49 | the :class:`~sudo.middleware.SudoMiddleware`. This is an shortcut for calling 50 | :func:`~sudo.utils.has_sudo_privileges` directly. 51 | 52 | .. class:: sudo.middleware.SudoMiddleware 53 | 54 | By default, you just need to add this into your ``MIDDLEWARE_CLASSES`` list. 55 | 56 | .. method:: has_sudo_privileges(self, request) 57 | 58 | Subclass and override :func:`~sudo.middleware.SudoMiddleware.has_sudo_privileges` if you'd like 59 | to override the default behavior of :func:`request.is_sudo() `. 60 | 61 | .. method:: process_request(self, request) 62 | 63 | Adds :func:`~request.is_sudo()` to the request. 64 | 65 | .. method:: process_response(self, request, response) 66 | 67 | Controls the behavior of setting and deleting the sudo cookie for the browser. 68 | 69 | 70 | .. module:: sudo.utils 71 | 72 | .. function:: grant_sudo_privileges(request, max_age=SUDO_COOKIE_AGE) 73 | 74 | Assigns a random token to the user's session that allows them to have elevated permissions. 75 | 76 | .. code-block:: python 77 | 78 | from sudo.utils import grant_sudo_privileges 79 | token = grant_sudo_privileges(request) 80 | 81 | .. function:: revoke_sudo_privileges(request) 82 | 83 | Revoke sudo privileges from a request explicitly 84 | 85 | .. code-block:: python 86 | 87 | from sudo.utils import revoke_sudo_privileges 88 | revoke_sudo_privileges(request) 89 | 90 | .. function:: has_sudo_privileges(request) 91 | 92 | Check if a request is allowed to perform sudo actions. 93 | 94 | .. code-block:: python 95 | 96 | from sudo.utils import has_sudo_privileges 97 | has_sudo = has_sudo_privileges(request) 98 | -------------------------------------------------------------------------------- /tests/middleware.py: -------------------------------------------------------------------------------- 1 | from .base import BaseTestCase 2 | 3 | from django.http import HttpResponse 4 | 5 | from sudo.settings import COOKIE_NAME 6 | from sudo.middleware import SudoMiddleware 7 | from sudo.utils import ( 8 | grant_sudo_privileges, 9 | revoke_sudo_privileges, 10 | ) 11 | 12 | 13 | class SudoMiddlewareTestCase(BaseTestCase): 14 | middleware = SudoMiddleware() 15 | 16 | def assertSignedCookieEqual(self, v1, v2, reason=None): 17 | value, _, _ = v1.split(":") 18 | return self.assertEqual(value, v2, reason) 19 | 20 | def test_process_request_raises_without_session(self): 21 | del self.request.session 22 | with self.assertRaises(AssertionError): 23 | self.middleware.process_request(self.request) 24 | 25 | def test_process_request_adds_is_sudo(self): 26 | self.middleware.process_request(self.request) 27 | self.assertFalse(self.request.is_sudo()) 28 | 29 | def test_process_response_noop(self): 30 | response = self.middleware.process_response(self.request, HttpResponse()) 31 | self.assertEqual(len(response.cookies.items()), 0) 32 | 33 | def test_process_response_with_sudo_sets_cookie(self): 34 | self.login() 35 | self.middleware.process_request(self.request) 36 | grant_sudo_privileges(self.request) 37 | response = self.middleware.process_response(self.request, HttpResponse()) 38 | morsels = list(response.cookies.items()) 39 | self.assertEqual(len(morsels), 1) 40 | self.assertEqual(morsels[0][0], COOKIE_NAME) 41 | _, sudo = morsels[0] 42 | self.assertEqual(sudo.key, COOKIE_NAME) 43 | self.assertSignedCookieEqual(sudo.value, self.request._sudo_token) 44 | self.assertEqual(sudo["max-age"], self.request._sudo_max_age) 45 | self.assertTrue(sudo["httponly"]) 46 | 47 | # Asserting that these are insecure together explicitly 48 | # since it's a big deal to not fuck up 49 | self.assertFalse(self.request.is_secure()) 50 | self.assertFalse(sudo["secure"]) # insecure request 51 | 52 | def test_process_response_sets_secure_cookie(self): 53 | self.login() 54 | self.request.is_secure = lambda: True 55 | self.middleware.process_request(self.request) 56 | grant_sudo_privileges(self.request) 57 | response = self.middleware.process_response(self.request, HttpResponse()) 58 | morsels = list(response.cookies.items()) 59 | self.assertEqual(len(morsels), 1) 60 | self.assertEqual(morsels[0][0], COOKIE_NAME) 61 | _, sudo = morsels[0] 62 | self.assertTrue(self.request.is_secure()) 63 | self.assertTrue(sudo["secure"]) 64 | 65 | def test_process_response_sudo_revoked_removes_cookie(self): 66 | self.login() 67 | self.middleware.process_request(self.request) 68 | grant_sudo_privileges(self.request) 69 | self.request.COOKIES[COOKIE_NAME] = self.request._sudo_token 70 | revoke_sudo_privileges(self.request) 71 | response = self.middleware.process_response(self.request, HttpResponse()) 72 | morsels = list(response.cookies.items()) 73 | self.assertEqual(len(morsels), 1) 74 | self.assertEqual(morsels[0][0], COOKIE_NAME) 75 | _, sudo = morsels[0] 76 | 77 | # Deleting a cookie is just setting it's value to empty 78 | # and telling it to expire 79 | self.assertEqual(sudo.key, COOKIE_NAME) 80 | self.assertFalse(sudo.value) 81 | self.assertEqual(sudo["max-age"], 0) 82 | 83 | def test_process_response_sudo_revoked_without_cookie(self): 84 | self.login() 85 | self.middleware.process_request(self.request) 86 | grant_sudo_privileges(self.request) 87 | revoke_sudo_privileges(self.request) 88 | response = self.middleware.process_response(self.request, HttpResponse()) 89 | morsels = list(response.cookies.items()) 90 | self.assertEqual(len(morsels), 0) 91 | -------------------------------------------------------------------------------- /sudo/views.py: -------------------------------------------------------------------------------- 1 | """ 2 | sudo.views 3 | ~~~~~~~~~~ 4 | 5 | :copyright: (c) 2020 by Matt Robenolt. 6 | :license: BSD, see LICENSE for more details. 7 | """ 8 | try: 9 | from urllib.parse import urlparse, urlunparse 10 | except ImportError: # pragma: no cover 11 | # Python 2 fallback 12 | from urlparse import urlparse, urlunparse # noqa 13 | 14 | from django.contrib.auth.decorators import login_required 15 | from django.core.exceptions import ImproperlyConfigured 16 | from django.http import HttpResponseRedirect, QueryDict 17 | from django.shortcuts import resolve_url 18 | from django.template.response import TemplateResponse 19 | from django.views.decorators.debug import sensitive_post_parameters 20 | from django.views.decorators.cache import never_cache 21 | from django.views.decorators.csrf import csrf_protect 22 | from django.views.generic import View 23 | from django.utils.decorators import method_decorator 24 | from django.utils.http import is_safe_url 25 | from django.utils.module_loading import import_string 26 | 27 | from sudo.settings import REDIRECT_FIELD_NAME, REDIRECT_URL, REDIRECT_TO_FIELD_NAME, URL 28 | from sudo.utils import grant_sudo_privileges 29 | from sudo.forms import SudoForm 30 | 31 | 32 | class SudoView(View): 33 | """ 34 | The default view for the sudo mode page. The role of this page is to 35 | prompt the user for their password again, and if successful, redirect 36 | them back to ``next``. 37 | """ 38 | 39 | form_class = SudoForm 40 | template_name = "sudo/sudo.html" 41 | extra_context = None 42 | 43 | def handle_sudo(self, request, redirect_to, context): 44 | return request.method == "POST" and context["form"].is_valid() 45 | 46 | def grant_sudo_privileges(self, request, redirect_to): 47 | grant_sudo_privileges(request) 48 | # Restore the redirect destination from the GET request 49 | redirect_to = request.session.pop(REDIRECT_TO_FIELD_NAME, redirect_to) 50 | # Double check we're not redirecting to other sites 51 | if not is_safe_url(url=redirect_to, host=request.get_host()): 52 | redirect_to = resolve_url(REDIRECT_URL) 53 | return HttpResponseRedirect(redirect_to) 54 | 55 | @method_decorator(sensitive_post_parameters()) 56 | @method_decorator(never_cache) 57 | @method_decorator(csrf_protect) 58 | @method_decorator(login_required) 59 | def dispatch(self, request): 60 | redirect_to = request.GET.get(REDIRECT_FIELD_NAME, REDIRECT_URL) 61 | 62 | # Make sure we're not redirecting to other sites 63 | if not is_safe_url(url=redirect_to, host=request.get_host()): 64 | redirect_to = resolve_url(REDIRECT_URL) 65 | 66 | if request.is_sudo(): 67 | return HttpResponseRedirect(redirect_to) 68 | 69 | if request.method == "GET": 70 | request.session[REDIRECT_TO_FIELD_NAME] = redirect_to 71 | 72 | context = { 73 | "form": self.form_class(request.user, request.POST or None), 74 | "request": request, 75 | REDIRECT_FIELD_NAME: redirect_to, 76 | } 77 | if self.handle_sudo(request, redirect_to, context): 78 | return self.grant_sudo_privileges(request, redirect_to) 79 | if self.extra_context is not None: 80 | context.update(self.extra_context) 81 | return TemplateResponse(request, self.template_name, context) 82 | 83 | 84 | def sudo(request, **kwargs): 85 | return SudoView(**kwargs).dispatch(request) 86 | 87 | 88 | def redirect_to_sudo(next_url, sudo_url=None): 89 | """ 90 | Redirects the user to the login page, passing the given 'next' page 91 | """ 92 | if sudo_url is None: 93 | sudo_url = URL 94 | 95 | try: 96 | # django 1.10 and greater can't resolve the string 'sudo.views.sudo' to a URL 97 | # https://docs.djangoproject.com/en/1.10/releases/1.10/#removed-features-1-10 98 | sudo_url = import_string(sudo_url) 99 | except (ImportError, ImproperlyConfigured): 100 | pass # wasn't a dotted path 101 | 102 | sudo_url_parts = list(urlparse(resolve_url(sudo_url))) 103 | 104 | querystring = QueryDict(sudo_url_parts[4], mutable=True) 105 | querystring[REDIRECT_FIELD_NAME] = next_url 106 | sudo_url_parts[4] = querystring.urlencode(safe="/") 107 | 108 | return HttpResponseRedirect(urlunparse(sudo_url_parts)) 109 | -------------------------------------------------------------------------------- /tests/utils.py: -------------------------------------------------------------------------------- 1 | from sudo.settings import COOKIE_NAME, COOKIE_AGE 2 | from sudo.utils import ( 3 | grant_sudo_privileges, 4 | revoke_sudo_privileges, 5 | has_sudo_privileges, 6 | ) 7 | 8 | from django.core.signing import BadSignature 9 | from django.utils.http import is_safe_url 10 | 11 | from .base import BaseTestCase 12 | 13 | 14 | class GrantSudoPrivilegesTestCase(BaseTestCase): 15 | def assertRequestHasToken(self, request, max_age): 16 | token = request.session[COOKIE_NAME] 17 | 18 | self.assertRegexpMatches(token, r"^\w{12}$") 19 | self.assertTrue(request._sudo) 20 | self.assertEqual(request._sudo_token, token) 21 | self.assertEqual(request._sudo_max_age, max_age) 22 | 23 | def test_grant_token_not_logged_in(self): 24 | with self.assertRaises(ValueError): 25 | grant_sudo_privileges(self.request) 26 | 27 | def test_grant_token_default_max_age(self): 28 | self.login() 29 | token = grant_sudo_privileges(self.request) 30 | self.assertIsNotNone(token) 31 | self.assertRequestHasToken(self.request, COOKIE_AGE) 32 | 33 | def test_grant_token_explicit_max_age(self): 34 | self.login() 35 | token = grant_sudo_privileges(self.request, 60) 36 | self.assertIsNotNone(token) 37 | self.assertRequestHasToken(self.request, 60) 38 | 39 | def test_without_user(self): 40 | delattr(self.request, "user") 41 | token = grant_sudo_privileges(self.request) 42 | self.assertIsNone(token) 43 | 44 | 45 | class RevokeSudoPrivilegesTestCase(BaseTestCase): 46 | def assertRequestNotSudo(self, request): 47 | self.assertFalse(self.request._sudo) 48 | self.assertNotIn(COOKIE_NAME, self.request.session) 49 | 50 | def test_revoke_sudo_privileges_noop(self): 51 | revoke_sudo_privileges(self.request) 52 | self.assertRequestNotSudo(self.request) 53 | 54 | def test_revoke_sudo_privileges(self): 55 | self.login() 56 | grant_sudo_privileges(self.request) 57 | revoke_sudo_privileges(self.request) 58 | self.assertRequestNotSudo(self.request) 59 | 60 | 61 | class HasSudoPrivilegesTestCase(BaseTestCase): 62 | def test_untouched(self): 63 | self.assertFalse(has_sudo_privileges(self.request)) 64 | 65 | def test_granted(self): 66 | self.login() 67 | grant_sudo_privileges(self.request) 68 | self.assertTrue(has_sudo_privileges(self.request)) 69 | 70 | def test_revoked(self): 71 | self.login() 72 | grant_sudo_privileges(self.request) 73 | revoke_sudo_privileges(self.request) 74 | self.assertFalse(has_sudo_privileges(self.request)) 75 | 76 | def test_cookie_and_token_match(self): 77 | self.login() 78 | 79 | def get_signed_cookie(key, salt="", max_age=None): 80 | return "abc123" 81 | 82 | self.request.session[COOKIE_NAME] = "abc123" 83 | self.request.get_signed_cookie = get_signed_cookie 84 | self.assertTrue(has_sudo_privileges(self.request)) 85 | 86 | def test_cookie_and_token_mismatch(self): 87 | self.login() 88 | 89 | def get_signed_cookie(key, salt="", max_age=None): 90 | return "nope" 91 | 92 | self.request.session[COOKIE_NAME] = "abc123" 93 | self.assertFalse(has_sudo_privileges(self.request)) 94 | 95 | def test_cookie_bad_signature(self): 96 | self.login() 97 | 98 | def get_signed_cookie(key, salt="", max_age=None): 99 | raise BadSignature 100 | 101 | self.request.session[COOKIE_NAME] = "abc123" 102 | self.assertFalse(has_sudo_privileges(self.request)) 103 | 104 | def test_missing_keys(self): 105 | self.login() 106 | self.assertFalse(has_sudo_privileges(self.request)) 107 | 108 | 109 | class IsSafeUrlTestCase(BaseTestCase): 110 | def test_success(self): 111 | urls = ( 112 | ("/", None), 113 | ("/foo/", None), 114 | ("/", "example.com"), 115 | ("http://example.com/foo", "example.com"), 116 | ) 117 | for url in urls: 118 | self.assertTrue(is_safe_url(*url)) 119 | 120 | def test_failure(self): 121 | urls = ( 122 | (None, None), 123 | ("", ""), 124 | ("http://mattrobenolt.com/", "example.com"), 125 | ("///example.com/", None), 126 | ("ftp://example.com", "example.com"), 127 | ("http://example.com\@mattrobenolt.com", "example.com"), # noqa: W605 128 | ("http:///example.com", "example.com"), 129 | ("\x08//example.com", "example.com"), 130 | ) 131 | for url in urls: 132 | self.assertFalse(is_safe_url(*url)) 133 | -------------------------------------------------------------------------------- /docs/make.bat: -------------------------------------------------------------------------------- 1 | @ECHO OFF 2 | 3 | REM Command file for Sphinx documentation 4 | 5 | if "%SPHINXBUILD%" == "" ( 6 | set SPHINXBUILD=sphinx-build 7 | ) 8 | set BUILDDIR=_build 9 | set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . 10 | set I18NSPHINXOPTS=%SPHINXOPTS% . 11 | if NOT "%PAPER%" == "" ( 12 | set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% 13 | set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% 14 | ) 15 | 16 | if "%1" == "" goto help 17 | 18 | if "%1" == "help" ( 19 | :help 20 | echo.Please use `make ^` where ^ is one of 21 | echo. html to make standalone HTML files 22 | echo. dirhtml to make HTML files named index.html in directories 23 | echo. singlehtml to make a single large HTML file 24 | echo. pickle to make pickle files 25 | echo. json to make JSON files 26 | echo. htmlhelp to make HTML files and a HTML help project 27 | echo. qthelp to make HTML files and a qthelp project 28 | echo. devhelp to make HTML files and a Devhelp project 29 | echo. epub to make an epub 30 | echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter 31 | echo. text to make text files 32 | echo. man to make manual pages 33 | echo. texinfo to make Texinfo files 34 | echo. gettext to make PO message catalogs 35 | echo. changes to make an overview over all changed/added/deprecated items 36 | echo. linkcheck to check all external links for integrity 37 | echo. doctest to run all doctests embedded in the documentation if enabled 38 | goto end 39 | ) 40 | 41 | if "%1" == "clean" ( 42 | for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i 43 | del /q /s %BUILDDIR%\* 44 | goto end 45 | ) 46 | 47 | if "%1" == "html" ( 48 | %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html 49 | if errorlevel 1 exit /b 1 50 | echo. 51 | echo.Build finished. The HTML pages are in %BUILDDIR%/html. 52 | goto end 53 | ) 54 | 55 | if "%1" == "dirhtml" ( 56 | %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml 57 | if errorlevel 1 exit /b 1 58 | echo. 59 | echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. 60 | goto end 61 | ) 62 | 63 | if "%1" == "singlehtml" ( 64 | %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml 65 | if errorlevel 1 exit /b 1 66 | echo. 67 | echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. 68 | goto end 69 | ) 70 | 71 | if "%1" == "pickle" ( 72 | %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle 73 | if errorlevel 1 exit /b 1 74 | echo. 75 | echo.Build finished; now you can process the pickle files. 76 | goto end 77 | ) 78 | 79 | if "%1" == "json" ( 80 | %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json 81 | if errorlevel 1 exit /b 1 82 | echo. 83 | echo.Build finished; now you can process the JSON files. 84 | goto end 85 | ) 86 | 87 | if "%1" == "htmlhelp" ( 88 | %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp 89 | if errorlevel 1 exit /b 1 90 | echo. 91 | echo.Build finished; now you can run HTML Help Workshop with the ^ 92 | .hhp project file in %BUILDDIR%/htmlhelp. 93 | goto end 94 | ) 95 | 96 | if "%1" == "qthelp" ( 97 | %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp 98 | if errorlevel 1 exit /b 1 99 | echo. 100 | echo.Build finished; now you can run "qcollectiongenerator" with the ^ 101 | .qhcp project file in %BUILDDIR%/qthelp, like this: 102 | echo.^> qcollectiongenerator %BUILDDIR%\qthelp\django-sudo.qhcp 103 | echo.To view the help file: 104 | echo.^> assistant -collectionFile %BUILDDIR%\qthelp\django-sudo.ghc 105 | goto end 106 | ) 107 | 108 | if "%1" == "devhelp" ( 109 | %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp 110 | if errorlevel 1 exit /b 1 111 | echo. 112 | echo.Build finished. 113 | goto end 114 | ) 115 | 116 | if "%1" == "epub" ( 117 | %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub 118 | if errorlevel 1 exit /b 1 119 | echo. 120 | echo.Build finished. The epub file is in %BUILDDIR%/epub. 121 | goto end 122 | ) 123 | 124 | if "%1" == "latex" ( 125 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 126 | if errorlevel 1 exit /b 1 127 | echo. 128 | echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. 129 | goto end 130 | ) 131 | 132 | if "%1" == "text" ( 133 | %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text 134 | if errorlevel 1 exit /b 1 135 | echo. 136 | echo.Build finished. The text files are in %BUILDDIR%/text. 137 | goto end 138 | ) 139 | 140 | if "%1" == "man" ( 141 | %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man 142 | if errorlevel 1 exit /b 1 143 | echo. 144 | echo.Build finished. The manual pages are in %BUILDDIR%/man. 145 | goto end 146 | ) 147 | 148 | if "%1" == "texinfo" ( 149 | %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo 150 | if errorlevel 1 exit /b 1 151 | echo. 152 | echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. 153 | goto end 154 | ) 155 | 156 | if "%1" == "gettext" ( 157 | %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale 158 | if errorlevel 1 exit /b 1 159 | echo. 160 | echo.Build finished. The message catalogs are in %BUILDDIR%/locale. 161 | goto end 162 | ) 163 | 164 | if "%1" == "changes" ( 165 | %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes 166 | if errorlevel 1 exit /b 1 167 | echo. 168 | echo.The overview file is in %BUILDDIR%/changes. 169 | goto end 170 | ) 171 | 172 | if "%1" == "linkcheck" ( 173 | %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck 174 | if errorlevel 1 exit /b 1 175 | echo. 176 | echo.Link check complete; look for any errors in the above output ^ 177 | or in %BUILDDIR%/linkcheck/output.txt. 178 | goto end 179 | ) 180 | 181 | if "%1" == "doctest" ( 182 | %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest 183 | if errorlevel 1 exit /b 1 184 | echo. 185 | echo.Testing of doctests in the sources finished, look at the ^ 186 | results in %BUILDDIR%/doctest/output.txt. 187 | goto end 188 | ) 189 | 190 | :end 191 | -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = sphinx-build 7 | PAPER = 8 | BUILDDIR = _build 9 | 10 | # Internal variables. 11 | PAPEROPT_a4 = -D latex_paper_size=a4 12 | PAPEROPT_letter = -D latex_paper_size=letter 13 | ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 14 | # the i18n builder cannot share the environment and doctrees with the others 15 | I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 16 | 17 | .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext 18 | 19 | help: 20 | @echo "Please use \`make ' where is one of" 21 | @echo " html to make standalone HTML files" 22 | @echo " dirhtml to make HTML files named index.html in directories" 23 | @echo " singlehtml to make a single large HTML file" 24 | @echo " pickle to make pickle files" 25 | @echo " json to make JSON files" 26 | @echo " htmlhelp to make HTML files and a HTML help project" 27 | @echo " qthelp to make HTML files and a qthelp project" 28 | @echo " devhelp to make HTML files and a Devhelp project" 29 | @echo " epub to make an epub" 30 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" 31 | @echo " latexpdf to make LaTeX files and run them through pdflatex" 32 | @echo " text to make text files" 33 | @echo " man to make manual pages" 34 | @echo " texinfo to make Texinfo files" 35 | @echo " info to make Texinfo files and run them through makeinfo" 36 | @echo " gettext to make PO message catalogs" 37 | @echo " changes to make an overview of all changed/added/deprecated items" 38 | @echo " linkcheck to check all external links for integrity" 39 | @echo " doctest to run all doctests embedded in the documentation (if enabled)" 40 | 41 | clean: 42 | -rm -rf $(BUILDDIR)/* 43 | 44 | html: 45 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html 46 | @echo 47 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." 48 | 49 | dirhtml: 50 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml 51 | @echo 52 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." 53 | 54 | singlehtml: 55 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml 56 | @echo 57 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." 58 | 59 | pickle: 60 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle 61 | @echo 62 | @echo "Build finished; now you can process the pickle files." 63 | 64 | json: 65 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json 66 | @echo 67 | @echo "Build finished; now you can process the JSON files." 68 | 69 | htmlhelp: 70 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp 71 | @echo 72 | @echo "Build finished; now you can run HTML Help Workshop with the" \ 73 | ".hhp project file in $(BUILDDIR)/htmlhelp." 74 | 75 | qthelp: 76 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp 77 | @echo 78 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \ 79 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:" 80 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/django-sudo.qhcp" 81 | @echo "To view the help file:" 82 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/django-sudo.qhc" 83 | 84 | devhelp: 85 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp 86 | @echo 87 | @echo "Build finished." 88 | @echo "To view the help file:" 89 | @echo "# mkdir -p $$HOME/.local/share/devhelp/django-sudo" 90 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/django-sudo" 91 | @echo "# devhelp" 92 | 93 | epub: 94 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub 95 | @echo 96 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub." 97 | 98 | latex: 99 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 100 | @echo 101 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." 102 | @echo "Run \`make' in that directory to run these through (pdf)latex" \ 103 | "(use \`make latexpdf' here to do that automatically)." 104 | 105 | latexpdf: 106 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 107 | @echo "Running LaTeX files through pdflatex..." 108 | $(MAKE) -C $(BUILDDIR)/latex all-pdf 109 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 110 | 111 | text: 112 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text 113 | @echo 114 | @echo "Build finished. The text files are in $(BUILDDIR)/text." 115 | 116 | man: 117 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man 118 | @echo 119 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man." 120 | 121 | texinfo: 122 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 123 | @echo 124 | @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." 125 | @echo "Run \`make' in that directory to run these through makeinfo" \ 126 | "(use \`make info' here to do that automatically)." 127 | 128 | info: 129 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 130 | @echo "Running Texinfo files through makeinfo..." 131 | make -C $(BUILDDIR)/texinfo info 132 | @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." 133 | 134 | gettext: 135 | $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale 136 | @echo 137 | @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." 138 | 139 | changes: 140 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes 141 | @echo 142 | @echo "The overview file is in $(BUILDDIR)/changes." 143 | 144 | linkcheck: 145 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck 146 | @echo 147 | @echo "Link check complete; look for any errors in the above output " \ 148 | "or in $(BUILDDIR)/linkcheck/output.txt." 149 | 150 | doctest: 151 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest 152 | @echo "Testing of doctests in the sources finished, look at the " \ 153 | "results in $(BUILDDIR)/doctest/output.txt." 154 | -------------------------------------------------------------------------------- /tests/views.py: -------------------------------------------------------------------------------- 1 | from .base import BaseTestCase 2 | 3 | from django.template.response import TemplateResponse 4 | 5 | from sudo.settings import REDIRECT_FIELD_NAME, REDIRECT_URL, REDIRECT_TO_FIELD_NAME 6 | from sudo.views import ( 7 | sudo, 8 | redirect_to_sudo, 9 | ) 10 | from sudo.forms import SudoForm 11 | 12 | 13 | class SudoViewTestCase(BaseTestCase): 14 | def test_enforces_logged_in(self): 15 | response = sudo(self.request) 16 | self.assertEqual(response.status_code, 302) 17 | self.assertEqual(response["Location"], "/accounts/login/?next=/foo") 18 | 19 | def test_returns_template_response(self): 20 | self.login() 21 | self.request.is_sudo = lambda: False 22 | response = sudo(self.request) 23 | self.assertIsInstance(response, TemplateResponse) 24 | self.assertEqual(response.template_name, "sudo/sudo.html") # default 25 | self.assertEqual( 26 | response.context_data[REDIRECT_FIELD_NAME], REDIRECT_URL 27 | ) # default 28 | form = response.context_data["form"] 29 | self.assertIsInstance(form, SudoForm) 30 | self.assertEqual(form.user, self.user) 31 | 32 | def test_returns_template_response_with_next(self): 33 | self.login() 34 | self.request.GET = {REDIRECT_FIELD_NAME: "/lol"} 35 | self.request.is_sudo = lambda: False 36 | response = sudo(self.request) 37 | self.assertEqual(response.context_data[REDIRECT_FIELD_NAME], "/lol") # default 38 | 39 | def test_returns_template_response_override_template(self): 40 | self.login() 41 | self.request.is_sudo = lambda: False 42 | response = sudo(self.request, template_name="foo.html") 43 | self.assertEqual(response.template_name, "foo.html") 44 | 45 | def test_returns_template_response_override_extra_context(self): 46 | self.login() 47 | self.request.is_sudo = lambda: False 48 | response = sudo(self.request, extra_context={"foo": "bar"}) 49 | self.assertEqual(response.context_data["foo"], "bar") 50 | 51 | def test_redirect_if_already_sudo(self): 52 | self.login() 53 | self.request.is_sudo = lambda: True 54 | response = sudo(self.request) 55 | self.assertEqual(response.status_code, 302) 56 | self.assertEqual(response["Location"], REDIRECT_URL) 57 | 58 | def test_redirect_fix_bad_url(self): 59 | self.login() 60 | self.request.is_sudo = lambda: True 61 | self.request.GET = {REDIRECT_FIELD_NAME: "http://mattrobenolt.com/lol"} 62 | response = sudo(self.request) 63 | self.assertEqual(response["Location"], REDIRECT_URL) 64 | self.request.GET = { 65 | REDIRECT_FIELD_NAME: "http://%s\@mattrobenolt.com" 66 | % self.request.get_host(), # noqa: W605 67 | } 68 | response = sudo(self.request) 69 | self.assertEqual(response["Location"], REDIRECT_URL) 70 | 71 | def test_redirect_if_already_sudo_with_next(self): 72 | self.login() 73 | self.request.GET = {REDIRECT_FIELD_NAME: "/lol"} 74 | self.request.is_sudo = lambda: True 75 | response = sudo(self.request) 76 | self.assertEqual(response.status_code, 302) 77 | self.assertEqual(response["Location"], "/lol") 78 | 79 | def test_redirect_after_successful_post(self): 80 | self.login() 81 | self.request.is_sudo = lambda: False 82 | self.request.method = "POST" 83 | self.request.csrf_processing_done = True 84 | self.request.POST = {"password": "foo"} 85 | response = sudo(self.request) 86 | self.assertEqual(response.status_code, 302) 87 | self.assertEqual(response["Location"], REDIRECT_URL) 88 | 89 | def test_session_based_redirect(self): 90 | self.login() 91 | self.request.is_sudo = lambda: False 92 | self.request.method = "GET" 93 | self.request.GET = {REDIRECT_FIELD_NAME: "/foobar"} 94 | sudo(self.request) 95 | 96 | self.request, self.request.session = self.post("/foo"), self.request.session 97 | self.login() 98 | self.request.is_sudo = lambda: False 99 | self.request.method = "POST" 100 | self.request.POST = {"password": "foo"} 101 | self.request.csrf_processing_done = True 102 | response = sudo(self.request) 103 | self.assertEqual(response.status_code, 302) 104 | self.assertEqual(response["Location"], "/foobar") 105 | self.assertNotEqual(response["Location"], REDIRECT_URL) 106 | self.assertFalse("redirect_to" in self.request.session) 107 | 108 | def test_session_based_redirect_bad_url(self): 109 | self.login() 110 | self.request.is_sudo = lambda: False 111 | self.request.method = "POST" 112 | self.request.POST = {"password": "foo"} 113 | self.request.session[REDIRECT_TO_FIELD_NAME] = "http://mattrobenolt.com/lol" 114 | self.request.csrf_processing_done = True 115 | response = sudo(self.request) 116 | self.assertEqual(response.status_code, 302) 117 | self.assertEqual(response["Location"], REDIRECT_URL) 118 | self.assertFalse("redirect_to" in self.request.session) 119 | self.request.session[REDIRECT_TO_FIELD_NAME] = ( 120 | "http://%s\@mattrobenolt.com" % self.request.get_host() # noqa: W605 121 | ) 122 | response = sudo(self.request) 123 | self.assertEqual(response["Location"], REDIRECT_URL) 124 | 125 | def test_render_form_with_bad_password(self): 126 | self.login() 127 | self.request.is_sudo = lambda: False 128 | self.request.method = "POST" 129 | self.request.csrf_processing_done = True 130 | self.request.POST = {"password": "lol"} 131 | response = sudo(self.request) 132 | self.assertEqual(response.status_code, 200) 133 | form = response.context_data["form"] 134 | self.assertFalse(form.is_valid()) 135 | 136 | 137 | class RedirectToSudoTestCase(BaseTestCase): 138 | def test_redirect_to_sudo_simple(self): 139 | response = redirect_to_sudo("/foo") 140 | self.assertEqual(response.status_code, 302) 141 | self.assertEqual(response["Location"], "/sudo/?next=/foo") 142 | 143 | def test_redirect_to_sudo_with_querystring(self): 144 | response = redirect_to_sudo("/foo?foo=bar") 145 | self.assertEqual(response.status_code, 302) 146 | self.assertEqual(response["Location"], "/sudo/?next=/foo%3Ffoo%3Dbar") 147 | 148 | def test_redirect_to_sudo_custom_url(self): 149 | response = redirect_to_sudo("/foo", "/lolsudo/") 150 | self.assertEqual(response.status_code, 302) 151 | self.assertEqual(response["Location"], "/lolsudo/?next=/foo") 152 | -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # django-sudo documentation build configuration file, created by 4 | # sphinx-quickstart on Sun Apr 13 18:05:56 2014. 5 | # 6 | # This file is execfile()d with the current directory set to its containing dir. 7 | # 8 | # Note that not all possible configuration values are present in this 9 | # autogenerated file. 10 | # 11 | # All configuration values have a default; values that are commented out 12 | # serve to show the default. 13 | 14 | import sys, os, datetime 15 | 16 | # If extensions (or modules to document with autodoc) are in another directory, 17 | # add these directories to sys.path here. If the directory is relative to the 18 | # documentation root, use os.path.abspath to make it absolute, like shown here. 19 | #sys.path.insert(0, os.path.abspath('.')) 20 | 21 | # -- General configuration ----------------------------------------------------- 22 | 23 | # If your documentation needs a minimal Sphinx version, state it here. 24 | #needs_sphinx = '1.0' 25 | 26 | # Add any Sphinx extension module names here, as strings. They can be extensions 27 | # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. 28 | extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode'] 29 | 30 | # Add any paths that contain templates here, relative to this directory. 31 | templates_path = ['_templates'] 32 | 33 | # The suffix of source filenames. 34 | source_suffix = '.rst' 35 | 36 | # The encoding of source files. 37 | #source_encoding = 'utf-8-sig' 38 | 39 | # The master toctree document. 40 | master_doc = 'index' 41 | 42 | # General information about the project. 43 | project = u'django-sudo' 44 | copyright = u'%s, Matt Robenolt' % datetime.date.today().year 45 | 46 | # The version info for the project you're documenting, acts as replacement for 47 | # |version| and |release|, also used in various other places throughout the 48 | # built documents. 49 | # 50 | # The short X.Y version. 51 | version = __import__('pkg_resources').get_distribution('django_sudo').version 52 | # The full version, including alpha/beta/rc tags. 53 | release = version 54 | 55 | # The language for content autogenerated by Sphinx. Refer to documentation 56 | # for a list of supported languages. 57 | #language = None 58 | 59 | # There are two options for replacing |today|: either, you set today to some 60 | # non-false value, then it is used: 61 | #today = '' 62 | # Else, today_fmt is used as the format for a strftime call. 63 | #today_fmt = '%B %d, %Y' 64 | 65 | # List of patterns, relative to source directory, that match files and 66 | # directories to ignore when looking for source files. 67 | exclude_patterns = ['_build'] 68 | 69 | # The reST default role (used for this markup: `text`) to use for all documents. 70 | #default_role = None 71 | 72 | # If true, '()' will be appended to :func: etc. cross-reference text. 73 | #add_function_parentheses = True 74 | 75 | # If true, the current module name will be prepended to all description 76 | # unit titles (such as .. function::). 77 | #add_module_names = True 78 | 79 | # If true, sectionauthor and moduleauthor directives will be shown in the 80 | # output. They are ignored by default. 81 | #show_authors = False 82 | 83 | # The name of the Pygments (syntax highlighting) style to use. 84 | pygments_style = 'sphinx' 85 | 86 | # A list of ignored prefixes for module index sorting. 87 | #modindex_common_prefix = [] 88 | 89 | 90 | # -- Options for HTML output --------------------------------------------------- 91 | 92 | # The theme to use for HTML and HTML Help pages. See the documentation for 93 | # a list of builtin themes. 94 | html_theme = 'default' 95 | 96 | # Theme options are theme-specific and customize the look and feel of a theme 97 | # further. For a list of options available for each theme, see the 98 | # documentation. 99 | #html_theme_options = {} 100 | 101 | # Add any paths that contain custom themes here, relative to this directory. 102 | #html_theme_path = [] 103 | 104 | # on_rtd is whether we are on readthedocs.org 105 | on_rtd = os.environ.get('READTHEDOCS', None) == 'True' 106 | 107 | if not on_rtd: # only import and set the theme if we're building docs locally 108 | import sphinx_rtd_theme 109 | html_theme = 'sphinx_rtd_theme' 110 | html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] 111 | 112 | # The name for this set of Sphinx documents. If None, it defaults to 113 | # " v documentation". 114 | #html_title = None 115 | 116 | # A shorter title for the navigation bar. Default is the same as html_title. 117 | #html_short_title = None 118 | 119 | # The name of an image file (relative to this directory) to place at the top 120 | # of the sidebar. 121 | #html_logo = None 122 | 123 | # The name of an image file (within the static path) to use as favicon of the 124 | # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 125 | # pixels large. 126 | #html_favicon = None 127 | 128 | # Add any paths that contain custom static files (such as style sheets) here, 129 | # relative to this directory. They are copied after the builtin static files, 130 | # so a file named "default.css" will overwrite the builtin "default.css". 131 | html_static_path = ['_static'] 132 | 133 | # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, 134 | # using the given strftime format. 135 | #html_last_updated_fmt = '%b %d, %Y' 136 | 137 | # If true, SmartyPants will be used to convert quotes and dashes to 138 | # typographically correct entities. 139 | #html_use_smartypants = True 140 | 141 | # Custom sidebar templates, maps document names to template names. 142 | #html_sidebars = {} 143 | 144 | # Additional templates that should be rendered to pages, maps page names to 145 | # template names. 146 | #html_additional_pages = {} 147 | 148 | # If false, no module index is generated. 149 | #html_domain_indices = True 150 | 151 | # If false, no index is generated. 152 | #html_use_index = True 153 | 154 | # If true, the index is split into individual pages for each letter. 155 | #html_split_index = False 156 | 157 | # If true, links to the reST sources are added to the pages. 158 | #html_show_sourcelink = True 159 | 160 | # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. 161 | #html_show_sphinx = True 162 | 163 | # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. 164 | #html_show_copyright = True 165 | 166 | # If true, an OpenSearch description file will be output, and all pages will 167 | # contain a tag referring to it. The value of this option must be the 168 | # base URL from which the finished HTML is served. 169 | #html_use_opensearch = '' 170 | 171 | # This is the file name suffix for HTML files (e.g. ".xhtml"). 172 | #html_file_suffix = None 173 | 174 | # Output file base name for HTML help builder. 175 | htmlhelp_basename = 'django-sudodoc' 176 | 177 | 178 | # -- Options for LaTeX output -------------------------------------------------- 179 | 180 | latex_elements = { 181 | # The paper size ('letterpaper' or 'a4paper'). 182 | #'papersize': 'letterpaper', 183 | 184 | # The font size ('10pt', '11pt' or '12pt'). 185 | #'pointsize': '10pt', 186 | 187 | # Additional stuff for the LaTeX preamble. 188 | #'preamble': '', 189 | } 190 | 191 | # Grouping the document tree into LaTeX files. List of tuples 192 | # (source start file, target name, title, author, documentclass [howto/manual]). 193 | latex_documents = [ 194 | ('index', 'django-sudo.tex', u'django-sudo Documentation', 195 | u'Matt Robenolt', 'manual'), 196 | ] 197 | 198 | # The name of an image file (relative to this directory) to place at the top of 199 | # the title page. 200 | #latex_logo = None 201 | 202 | # For "manual" documents, if this is true, then toplevel headings are parts, 203 | # not chapters. 204 | #latex_use_parts = False 205 | 206 | # If true, show page references after internal links. 207 | #latex_show_pagerefs = False 208 | 209 | # If true, show URL addresses after external links. 210 | #latex_show_urls = False 211 | 212 | # Documents to append as an appendix to all manuals. 213 | #latex_appendices = [] 214 | 215 | # If false, no module index is generated. 216 | #latex_domain_indices = True 217 | 218 | 219 | # -- Options for manual page output -------------------------------------------- 220 | 221 | # One entry per manual page. List of tuples 222 | # (source start file, name, description, authors, manual section). 223 | man_pages = [ 224 | ('index', 'django-sudo', u'django-sudo Documentation', 225 | [u'Matt Robenolt'], 1) 226 | ] 227 | 228 | # If true, show URL addresses after external links. 229 | #man_show_urls = False 230 | 231 | 232 | # -- Options for Texinfo output ------------------------------------------------ 233 | 234 | # Grouping the document tree into Texinfo files. List of tuples 235 | # (source start file, target name, title, author, 236 | # dir menu entry, description, category) 237 | texinfo_documents = [ 238 | ('index', 'django-sudo', u'django-sudo Documentation', 239 | u'Matt Robenolt', 'django-sudo', 'One line description of project.', 240 | 'Miscellaneous'), 241 | ] 242 | 243 | # Documents to append as an appendix to all manuals. 244 | #texinfo_appendices = [] 245 | 246 | # If false, no module index is generated. 247 | #texinfo_domain_indices = True 248 | 249 | # How to display URL addresses: 'footnote', 'no', or 'inline'. 250 | #texinfo_show_urls = 'footnote' 251 | --------------------------------------------------------------------------------