Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
anx-abruckner committed Jun 21, 2022
0 parents commit de25af5
Show file tree
Hide file tree
Showing 23 changed files with 549 additions and 0 deletions.
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
.idea/*
*.egg-info*
__pycache__
db.sqlite3
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2022 Anexia

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.
61 changes: 61 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
# DRF IP Restrictions

A library that allows IP restrictions for views/endpoints in Django REST framework.

## Installation

1. Install using pip:

```
pip install git+https://github.com/anexia-it/drf-ip-restrictions@main
```

2. Add the library to your INSTALLED_APPS list.

```
INSTALLED_APPS = [
...
'drf_ip_restrictions',
...
]
```

4. Override the allowed IP addresses your `settings.py` according to your needs:
```
# within settings.py
DRF_IP_RESTRICTION_SETTINGS = {
"ALLOWED_IP_LIST": ["127.0.0.1"],
}
```

## Usage

Add the AllowedIpList class to any views / endpoints that should only provide access for the
configured IP addresses, e.g. to restrict a view set:
```
# within views.py
class MyViewSet(viewsets.ModelViewSet):
permission_classes = (AllowedIpList,)
...
```

or to restrict only a single endpoint:
```
# within views.py
class MyViewSet(viewsets.ModelViewSet):
...
@action(
detail=False,
methods=["get"],
http_method_names=["get"],
authentication_classes=[],
permission_classes=[AllowedIpList], # <-- this is the important part for IP restrictions to work
url_path=r"my-method",
)
def my_method(self, request, *args, **kwargs):
# do stuff and return rest_framework.response.Response in the end
```
5 changes: 5 additions & 0 deletions drf_ip_restrictions/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
from drf_ip_restrictions.permissions import AllowedIpList

__all__ = [
"AllowedIpList",
]
27 changes: 27 additions & 0 deletions drf_ip_restrictions/permissions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
from drf_ip_restrictions.settings import ip_restriction_settings
from ipware import get_client_ip


class AllowedIpList(object):
"""
Ensure the request's IP address is on the ip white list configured in Django settings.
"""

def has_permission(self, request, view):
client_ip, is_routable = get_client_ip(request)

if client_ip:
settings = ip_restriction_settings()
allowed_ips = settings.ALLOWED_IP_LIST
for allowed_ip in allowed_ips:
if client_ip == allowed_ip or client_ip.startswith(allowed_ip):
return True

return False

def has_object_permission(self, request, view, obj):
"""
This permission class has no special implementation of per-object permissions, so the result
will be the same as the `has_permission` method.
"""
return self.has_permission(request, view)
16 changes: 16 additions & 0 deletions drf_ip_restrictions/settings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
from django.conf import settings
from rest_framework.settings import APISettings

__all__ = ["ip_restriction_settings"]


DRF_IP_RESTRICTION_SETTINGS = {
"ALLOWED_IP_LIST": [],
}


def ip_restriction_settings():
return APISettings(
user_settings=getattr(settings, "DRF_IP_RESTRICTION_SETTINGS", {}),
defaults=DRF_IP_RESTRICTION_SETTINGS,
)
11 changes: 11 additions & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# Package and package dependencies
-e .

# Development dependencies

# TestApp dependencies

django>=3.2,<4
djangorestframework>=3.13,<4
django-filter>=21.1,<22
django-ipware>=4.0.2,<4.1
42 changes: 42 additions & 0 deletions setup.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import os

from setuptools import find_packages, setup

with open(os.path.join(os.path.dirname(__file__), 'README.md')) as readme:
README = readme.read()

# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))

setup(
name='drf-ip-restrictions',
version=os.getenv('PACKAGE_VERSION', '0.0.0').replace('refs/tags/', ''),
packages=find_packages(),
include_package_data=True,
license='MIT License',
description='A library that allows IP restrictions for views/endpoints in Django REST framework.',
long_description=README,
long_description_content_type='text/markdown',
url='https://github.com/anexia-it/drf-ip-restrictions',
author='Alexandra Bruckner',
author_email='[email protected]',
install_requires=[
'django>=3.2',
'djangorestframework>=3.12',
'django-ipware>=4.0.2',
],
classifiers=[
'Development Status :: 5 - Production/Stable',
'Framework :: Django',
'Framework :: Django :: 3.2',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: 3.9',
'Programming Language :: Python :: 3.10',
],
)
Empty file added tests/core/__init__.py
Empty file.
108 changes: 108 additions & 0 deletions tests/core/settings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
"""
Django settings for "tests" project which assures the functionality of the "drf-ip-restrictions" package
(https://github.com/anexia-it/drf-ip-restrictions).
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'H0&?S3ZyJVDoLdvzU6OhQ1i?rabJ7Pwd3#2NF.ge7NgWrRQKX$utvpd!4MPL'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = ["*"]

# Application definition

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

'rest_framework',
'drf_ip_restrictions',
'testapp',
]

MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'core.urls'

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

WSGI_APPLICATION = 'core.wsgi.application'

# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}

# Password validation
# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]

# Internationalization
# https://docs.djangoproject.com/en/3.2/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# IP Restriction Configuration
DRF_IP_RESTRICTION_SETTINGS = {
"ALLOWED_IP_LIST": ["127.0.0.1"],
}
13 changes: 13 additions & 0 deletions tests/core/urls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
from django.urls import include, path
from rest_framework import routers

from testapp.views import PublicInfoViewSet, PrivateInfoViewSet, PartiallyPrivateInfoViewSet

router = routers.DefaultRouter()
router.register(r'public_info', PublicInfoViewSet)
router.register(r'private_info', PrivateInfoViewSet)
router.register(r'partially_private_info', PartiallyPrivateInfoViewSet)

urlpatterns = [
path('api/', include(router.urls))
]
14 changes: 14 additions & 0 deletions tests/core/wsgi.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
"""
WSGI config for core project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/howto/deployment/wsgi/
"""

import os

from django.core.wsgi import get_wsgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core.settings')

application = get_wsgi_application()
22 changes: 22 additions & 0 deletions tests/manage.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
#!/usr/bin/env python
import os
import sys

if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "core.settings")
try:
from django.core.management import execute_from_command_line
except ImportError:
# The above import may fail for some other reason. Ensure that the
# issue is really that Django is missing to avoid masking other
# exceptions on Python 2.
try:
import django
except ImportError:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
)
raise
execute_from_command_line(sys.argv)
Empty file added tests/testapp/__init__.py
Empty file.
5 changes: 5 additions & 0 deletions tests/testapp/apps.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
from django.apps import AppConfig


class TestappConfig(AppConfig):
name = 'testapp'
32 changes: 32 additions & 0 deletions tests/testapp/migrations/0001_initial.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# Generated by Django 3.2.13 on 2022-06-14 11:34

from django.db import migrations, models


class Migration(migrations.Migration):

initial = True

dependencies = [
]

operations = [
migrations.CreateModel(
name='PartiallyPrivateInfo',
fields=[
('name', models.CharField(max_length=50, primary_key=True, serialize=False)),
],
),
migrations.CreateModel(
name='PrivateInfo',
fields=[
('name', models.CharField(max_length=50, primary_key=True, serialize=False)),
],
),
migrations.CreateModel(
name='PublicInfo',
fields=[
('name', models.CharField(max_length=50, primary_key=True, serialize=False)),
],
),
]
Empty file.
Loading

0 comments on commit de25af5

Please sign in to comment.