Skip to content

Commit

Permalink
added missing files
Browse files Browse the repository at this point in the history
  • Loading branch information
Alessandro De Noia committed Mar 21, 2018
1 parent e3a7214 commit 5188711
Show file tree
Hide file tree
Showing 13 changed files with 687 additions and 0 deletions.
3 changes: 3 additions & 0 deletions .coveragerc
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
[run]
source = admin_ip_restrictor
omit = .tox/*,.circleci/*
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright (c) 2016 UK Trade & Investment (UKTI)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
3 changes: 3 additions & 0 deletions MANIFEST.in
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
include LICENSE
include README.rst
prune tests
92 changes: 92 additions & 0 deletions README.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
Django Admin IP Restrictor
==========================

.. image:: https://circleci.com/gh/uktrade/django-admin-ip-restrictor/tree/master.svg?style=shield
:target: https://circleci.com/gh/uktrade/django-admin-ip-restrictor/tree/master

.. image:: https://codecov.io/gh/uktrade/django-admin-ip-restrictor/branch/master/graph/badge.svg
:target: https://codecov.io/gh/uktrade/django-admin-ip-restrictor

.. image:: https://img.shields.io/pypi/v/django-admin-ip-restrictor.svg
:target: https://pypi.python.org/pypi/django-admin-ip-restrictor

.. image:: https://img.shields.io/pypi/pyversions/django-admin-ip-restrictor.svg
:target: https://pypi.python.org/pypi/django-admin-ip-restrictor

.. image:: https://img.shields.io/pypi/l/django-admin-ip-restrictor.svg
:target: https://pypi.python.org/pypi/django-admin-ip-restrictor

A Django middleware to restrict the access to the Django admin based on incoming IPs

Requirements
------------

* Python >= 3.4
* Django >= 1.9
* django-ipware=>2,<3


Usage
-----

First install the package::

$ pip install django-admin-ip-restrictor

Then add the middleware to your settings::

# Django 1.10+
MIDDLEWARE = [
...
'admin_ip_restrictor.middleware.AdminIPRestrictorMiddleware'
]

# Django 1.9
MIDDLEWARE_CLASSES = [
...
'admin_ip_restrictor.middleware.AdminIPRestrictorMiddleware'
]

Set these variables in your `settings.py` to control who has access to the admin (IPV4 and IPV6 can be mixed)::

RESTRICT_ADMIN=True
ALLOWED_ADMIN_IPS=['127.0.0.1', '::1']
ALLOWED_ADMIN_IP_RANGES=['127.0.0.0/24', '::/1']


If using environment variables make sure that the variables receive the right type of value.
`django-admin-ip-restrictor` automatically converts the following formats::

$ export RESTRICT_ADMIN='true'
$ export ALLOWED_ADMIN_IPS='127.0.0.1,::1'
$ export ALLOWED_ADMIN_IP_RANGES='127.0.0.0/24,::/1'


For `RESTRICT_ADMIN` also these values can be used: `True`, `1`, `false`, `False`, `0`

Run tests
---------

Install `tox` and `pyenv`::

$ pip install tox pyenv


Install Python versions in `pyenv`::

$ pyenv install 3.4.4
$ pyenv install 3.5.3
$ pyenv install 3.6.2

Specify the Python versions you want to test with::

$ pyenv local 3.4.4 3.5.3 3.6.2

Run tests::

$ tox

Contribute
----------

Fork the project and submit a PR!
91 changes: 91 additions & 0 deletions admin_ip_restrictor/middleware.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
import ipaddress

from django.conf import settings
from django.http import Http404
from ipware.ip2 import get_client_ip

try:
from django.urls import resolve
except ImportError: # pragma: no cover
from django.core.urlresolvers import resolve


class AdminIPRestrictorMiddleware(object):

def __init__(self, get_response=None):
self.get_response = get_response
restrict_admin = getattr(
settings,
'RESTRICT_ADMIN',
False
)
self.restrict_admin = self.parse_bool_envars(
restrict_admin
)
allowed_admin_ips = getattr(
settings,
'ALLOWED_ADMIN_IPS',
[]
)
self.allowed_admin_ips = self.parse_list_envars(
allowed_admin_ips
)
allowed_admin_ip_ranges = getattr(
settings,
'ALLOWED_ADMIN_IP_RANGES',
[]
)
self.allowed_admin_ip_ranges = self.parse_list_envars(
allowed_admin_ip_ranges
)

def __call__(self, request):
response = self.process_request(request)

if not response and self.get_response:
response = self.get_response(request)

return response

@staticmethod
def parse_bool_envars(value):
if value in ('true', 'True', '1', 1):
return True
return False

@staticmethod
def parse_list_envars(value):
if type(value) == list:
return value
else:
return value.split(',')

def is_blocked(self, ip):
"""Determine if an IP address should be considered blocked."""
blocked = True

if ip in self.allowed_admin_ips:
blocked = False

for allowed_range in self.allowed_admin_ip_ranges:
if ipaddress.ip_address(ip) in ipaddress.ip_network(allowed_range):
blocked = False

return blocked

def get_ip(self, request):
client_ip, is_routable = get_client_ip(request)
assert client_ip, 'IP not found'
assert is_routable, 'IP is private'
return client_ip

def process_request(self, request):
if self.restrict_admin:
ip = self.get_ip(request)
is_admin_app = resolve(request.path).app_name == 'admin'
conditions = (is_admin_app, self.is_blocked(ip))

if all(conditions):
raise Http404()

return None
11 changes: 11 additions & 0 deletions requirements_flake8.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# Code static analysis
pep8==1.7.0
flake8==3.5.0
flake8-blind-except==0.1.1
flake8-debugger==1.4.0
flake8-import-order==0.13
flake8-docstrings==1.1.0
flake8-print==2.0.2
flake8-quotes==0.11.0
flake8-string-format==0.2.3
pep8-naming==0.4.1
27 changes: 27 additions & 0 deletions setup.cfg
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# D203: 1 blank line required before class docstring
# D100: Missing docstring in public module
# D101: Missing docstring in public class
# D102: Missing docstring in public method
# D103: Missing docstring in public function
# D104: Missing docstring in public package
# D105: Missing docstring in magic method
# D106: Missing docstring in public nested class
# D107: Missing docstring in __init__
# D401: First line should be imperative

[flake8]
max-line-length = 120
exclude = .tox,.git,*/migrations/*,*/static/CACHE/*,node_modules,*settings*,manage.py,wsgi.py
ignore = D203, D100, D101, D102, D103, D104, D105, D106, D107, D401
max-complexity = 7
application-import-names = money_tracker
import_order_style = smarkets

[pycodestyle]
max-line-length = 120
exclude=.tox,.git,*/migrations/*,*/static/CACHE/*,node_modules,*settings*,manage.py,wsgi.py
ignore = D203, D100, D101, D102, D103, D104, D105, D106, D107, D401

[tool:pytest]
testpaths = tests/
norecursedirs = .tox
Empty file added tests/__init__.py
Empty file.
9 changes: 9 additions & 0 deletions tests/conftest.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import os

import django


def pytest_configure(config):
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'tests.settings')
django.setup()

50 changes: 50 additions & 0 deletions tests/settings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
from django import VERSION as DJANGO_VERSION

SECRET_KEY = 'fake-key'

INSTALLED_APPS = [
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.admin',
'tests'
]

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
}

ROOT_URLCONF = 'tests.urls'

TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]


if DJANGO_VERSION < (1, 10):
MIDDLEWARE_CLASSES = [
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'admin_ip_restrictor.middleware.AdminIPRestrictorMiddleware'
]
else:
MIDDLEWARE = [
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'admin_ip_restrictor.middleware.AdminIPRestrictorMiddleware'
]
Loading

0 comments on commit 5188711

Please sign in to comment.