From c8dd8ef4fcf0299d6b68193e3d1728059d3c7717 Mon Sep 17 00:00:00 2001 From: Malte Kerl Date: Thu, 21 Sep 2023 19:50:09 +0200 Subject: [PATCH] First commit --- .gitignore | 137 ++++++++++++++++++++++++++++++++ abac/__init__.py | 0 abac/admin.py | 3 + abac/apps.py | 6 ++ abac/migrations/0001_initial.py | 91 +++++++++++++++++++++ abac/migrations/__init__.py | 0 abac/models.py | 74 +++++++++++++++++ abac/tests.py | 3 + abac/views.py | 18 +++++ mabac/__init__.py | 0 mabac/asgi.py | 16 ++++ mabac/settings.py | 125 +++++++++++++++++++++++++++++ mabac/urls.py | 22 +++++ mabac/wsgi.py | 16 ++++ manage.py | 22 +++++ 15 files changed, 533 insertions(+) create mode 100644 .gitignore create mode 100644 abac/__init__.py create mode 100644 abac/admin.py create mode 100644 abac/apps.py create mode 100644 abac/migrations/0001_initial.py create mode 100644 abac/migrations/__init__.py create mode 100644 abac/models.py create mode 100644 abac/tests.py create mode 100644 abac/views.py create mode 100644 mabac/__init__.py create mode 100644 mabac/asgi.py create mode 100644 mabac/settings.py create mode 100644 mabac/urls.py create mode 100644 mabac/wsgi.py create mode 100755 manage.py diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..56a04c3 --- /dev/null +++ b/.gitignore @@ -0,0 +1,137 @@ +# Django # +*.log +*.pot +*.pyc +__pycache__ +db.sqlite3 +media + +# Backup files # +*.bak + +# If you are using PyCharm # +# User-specific stuff +.idea/**/workspace.xml +.idea/**/tasks.xml +.idea/**/usage.statistics.xml +.idea/**/dictionaries +.idea/**/shelf + +# AWS User-specific +.idea/**/aws.xml + +# Generated files +.idea/**/contentModel.xml + +# Sensitive or high-churn files +.idea/**/dataSources/ +.idea/**/dataSources.ids +.idea/**/dataSources.local.xml +.idea/**/sqlDataSources.xml +.idea/**/dynamic.xml +.idea/**/uiDesigner.xml +.idea/**/dbnavigator.xml + +# Gradle +.idea/**/gradle.xml +.idea/**/libraries + +# File-based project format +*.iws + +# IntelliJ +out/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Python # +*.py[cod] +*$py.class + +# Distribution / packaging +.Python build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +*.egg-info/ +.installed.cfg +*.egg +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.coverage +.coverage.* +.cache +.pytest_cache/ +nosetests.xml +coverage.xml +*.cover +.hypothesis/ + +# Jupyter Notebook +.ipynb_checkpoints + +# pyenv +.python-version + +# celery +celerybeat-schedule.* + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ + +# Sublime Text # +*.tmlanguage.cache +*.tmPreferences.cache +*.stTheme.cache +*.sublime-workspace +*.sublime-project + +# sftp configuration file +sftp-config.json + +# Package control specific files Package +Control.last-run +Control.ca-list +Control.ca-bundle +Control.system-ca-bundle +GitHub.sublime-settings + +# Visual Studio Code # +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +.history \ No newline at end of file diff --git a/abac/__init__.py b/abac/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/abac/admin.py b/abac/admin.py new file mode 100644 index 0000000..8c38f3f --- /dev/null +++ b/abac/admin.py @@ -0,0 +1,3 @@ +from django.contrib import admin + +# Register your models here. diff --git a/abac/apps.py b/abac/apps.py new file mode 100644 index 0000000..b48a45c --- /dev/null +++ b/abac/apps.py @@ -0,0 +1,6 @@ +from django.apps import AppConfig + + +class AbacConfig(AppConfig): + default_auto_field = 'django.db.models.BigAutoField' + name = 'abac' diff --git a/abac/migrations/0001_initial.py b/abac/migrations/0001_initial.py new file mode 100644 index 0000000..3202ccb --- /dev/null +++ b/abac/migrations/0001_initial.py @@ -0,0 +1,91 @@ +# Generated by Django 4.2.5 on 2023-09-21 17:15 + +from django.conf import settings +import django.contrib.auth.models +import django.contrib.auth.validators +from django.db import migrations, models +import django.db.models.deletion +import django.utils.timezone + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ('auth', '0012_alter_user_first_name_max_length'), + ] + + operations = [ + migrations.CreateModel( + name='User', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('password', models.CharField(max_length=128, verbose_name='password')), + ('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')), + ('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')), + ('username', models.CharField(error_messages={'unique': 'A user with that username already exists.'}, help_text='Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.', max_length=150, unique=True, validators=[django.contrib.auth.validators.UnicodeUsernameValidator()], verbose_name='username')), + ('first_name', models.CharField(blank=True, max_length=150, verbose_name='first name')), + ('last_name', models.CharField(blank=True, max_length=150, verbose_name='last name')), + ('email', models.EmailField(blank=True, max_length=254, verbose_name='email address')), + ('is_staff', models.BooleanField(default=False, help_text='Designates whether the user can log into this admin site.', verbose_name='staff status')), + ('is_active', models.BooleanField(default=True, help_text='Designates whether this user should be treated as active. Unselect this instead of deleting accounts.', verbose_name='active')), + ('date_joined', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date joined')), + ('public_key', models.TextField()), + ('private_key', models.TextField()), + ('groups', models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user', to='auth.group', verbose_name='groups')), + ('user_permissions', models.ManyToManyField(blank=True, help_text='Specific permissions for this user.', related_name='user_set', related_query_name='user', to='auth.permission', verbose_name='user permissions')), + ], + options={ + 'permissions': [('can_create_users', 'Can create new users')], + }, + managers=[ + ('objects', django.contrib.auth.models.UserManager()), + ], + ), + migrations.CreateModel( + name='Attribute', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('value', models.IntegerField()), + ], + ), + migrations.CreateModel( + name='AttributeType', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('is_secret', models.BooleanField(default=False)), + ('datatype', models.CharField(max_length=15)), + ('significant_digits', models.PositiveIntegerField(blank=True, null=True)), + ('name', models.CharField(max_length=40)), + ], + ), + migrations.CreateModel( + name='Rule', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('rule_type', models.CharField(choices=[('and', 'AND'), ('or', 'OR')], max_length=3)), + ('attributes', models.ManyToManyField(to='abac.attribute')), + ], + ), + migrations.CreateModel( + name='File', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('name', models.CharField(max_length=255)), + ('file', models.FileField(upload_to='uploads/')), + ('owner', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), + ('rules', models.ManyToManyField(to='abac.rule')), + ], + ), + migrations.AddField( + model_name='attribute', + name='attribute_type', + field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='abac.attributetype'), + ), + migrations.AddField( + model_name='attribute', + name='user', + field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL), + ), + ] diff --git a/abac/migrations/__init__.py b/abac/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/abac/models.py b/abac/models.py new file mode 100644 index 0000000..cd2fee8 --- /dev/null +++ b/abac/models.py @@ -0,0 +1,74 @@ +import pickle +from base64 import b64encode, b64decode +from django.contrib.auth.models import AbstractUser +from django.db import models + + +class User(AbstractUser): + pass + public_key = models.TextField() + private_key = models.TextField() + + def save(self, *args, **kwargs): + if hasattr(self, '_phe_public_key') and hasattr(self, '_phe_private_key'): + self.phe_public_key = b64encode(pickle.dumps(self._phe_public_key)).decode('utf-8') + self.phe_private_key = b64encode(pickle.dumps(self._phe_private_key)).decode('utf-8') + + super().save(*args, **kwargs) + + @property + def deserialized_public_key(self): + return pickle.loads(b64decode(self.phe_public_key)) + + @property + def deserialized_private_key(self): + return pickle.loads(b64decode(self.phe_private_key)) + + class Meta: + permissions = [ + ("can_create_users", "Can create new users"), + ] + + +class AttributeType(models.Model): + DATATYPE_CHOICES = [ + ('string', 'String'), + ('boolean', 'Boolean'), + ('integer', 'Integer'), + ] + + is_secret = models.BooleanField(default=False) + datatype = models.CharField(max_length=15) + significant_digits = models.PositiveIntegerField(null=True, blank=True) + name = models.CharField(max_length=40) + + def save(self, *args, **kwargs): + if self.datatype.startswith('float'): + if self.significant_digits is None: + raise ValueError('significant_digits must be set for float datatype') + self.datatype = f'float_{self.significant_digits}' + elif self.significant_digits is not None: + raise ValueError('significant_digits must be None for non-float datatype') + super().save(*args, **kwargs) + + +class Attribute(models.Model): + user = models.ForeignKey(User, on_delete=models.CASCADE) + attribute_type = models.ForeignKey(AttributeType, on_delete=models.CASCADE) + value = models.IntegerField() # assuming value is always stored as an integer + + +class Rule(models.Model): + TYPE_CHOICES = [ + ('and', 'AND'), + ('or', 'OR'), + ] + rule_type = models.CharField(max_length=3, choices=TYPE_CHOICES) + attributes = models.ManyToManyField(Attribute) + + +class File(models.Model): + owner = models.ForeignKey(User, on_delete=models.CASCADE) + name = models.CharField(max_length=255) + file = models.FileField(upload_to='uploads/') # assuming you are using FileField to store the file + rules = models.ManyToManyField(Rule) diff --git a/abac/tests.py b/abac/tests.py new file mode 100644 index 0000000..7ce503c --- /dev/null +++ b/abac/tests.py @@ -0,0 +1,3 @@ +from django.test import TestCase + +# Create your tests here. diff --git a/abac/views.py b/abac/views.py new file mode 100644 index 0000000..6c37995 --- /dev/null +++ b/abac/views.py @@ -0,0 +1,18 @@ +from django.shortcuts import render +from django.http.response import HttpResponseNotAllowed +from django.contrib.auth.decorators import permission_required +from django.http import HttpResponse + +# Create your views here. +def create_user(request): + special_user = request.user + if special_user.has_perm('abac.can_create_users'): + pass #TODO: Create new User + else: + # Return a response indicating insufficient permissions + return HttpResponseNotAllowed(request) + +@permission_required('abac.can_create_users', raise_exception=True) +def create_user_view(request): + # Your view logic here + return HttpResponse('New user created') diff --git a/mabac/__init__.py b/mabac/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/mabac/asgi.py b/mabac/asgi.py new file mode 100644 index 0000000..dfcff17 --- /dev/null +++ b/mabac/asgi.py @@ -0,0 +1,16 @@ +""" +ASGI config for mabac project. + +It exposes the ASGI callable as a module-level variable named ``application``. + +For more information on this file, see +https://docs.djangoproject.com/en/4.2/howto/deployment/asgi/ +""" + +import os + +from django.core.asgi import get_asgi_application + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mabac.settings') + +application = get_asgi_application() diff --git a/mabac/settings.py b/mabac/settings.py new file mode 100644 index 0000000..1f38a3e --- /dev/null +++ b/mabac/settings.py @@ -0,0 +1,125 @@ +""" +Django settings for mabac project. + +Generated by 'django-admin startproject' using Django 4.2.5. + +For more information on this file, see +https://docs.djangoproject.com/en/4.2/topics/settings/ + +For the full list of settings and their values, see +https://docs.djangoproject.com/en/4.2/ref/settings/ +""" + +from pathlib import Path + +# Build paths inside the project like this: BASE_DIR / 'subdir'. +BASE_DIR = Path(__file__).resolve().parent.parent + + +# Quick-start development settings - unsuitable for production +# See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/ + +# SECURITY WARNING: keep the secret key used in production secret! +SECRET_KEY = 'django-insecure-!(97p=t=qqq#btlj_ld6re=qai+(lbs5uc(eydo%#%onnzk2h2' + +# 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', + 'abac' +] + +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 = 'mabac.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 = 'mabac.wsgi.application' + + +# Database +# https://docs.djangoproject.com/en/4.2/ref/settings/#databases + +DATABASES = { + 'default': { + 'ENGINE': 'django.db.backends.sqlite3', + 'NAME': BASE_DIR / 'db.sqlite3', + } +} + + +# Password validation +# https://docs.djangoproject.com/en/4.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', + }, +] + +AUTH_USER_MODEL = 'abac.User' + +# Internationalization +# https://docs.djangoproject.com/en/4.2/topics/i18n/ + +LANGUAGE_CODE = 'en-us' + +TIME_ZONE = 'UTC' + +USE_I18N = True + +USE_TZ = True + + +# Static files (CSS, JavaScript, Images) +# https://docs.djangoproject.com/en/4.2/howto/static-files/ + +STATIC_URL = 'static/' + +# Default primary key field type +# https://docs.djangoproject.com/en/4.2/ref/settings/#default-auto-field + +DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' diff --git a/mabac/urls.py b/mabac/urls.py new file mode 100644 index 0000000..85713d1 --- /dev/null +++ b/mabac/urls.py @@ -0,0 +1,22 @@ +""" +URL configuration for mabac project. + +The `urlpatterns` list routes URLs to views. For more information please see: + https://docs.djangoproject.com/en/4.2/topics/http/urls/ +Examples: +Function views + 1. Add an import: from my_app import views + 2. Add a URL to urlpatterns: path('', views.home, name='home') +Class-based views + 1. Add an import: from other_app.views import Home + 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') +Including another URLconf + 1. Import the include() function: from django.urls import include, path + 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) +""" +from django.contrib import admin +from django.urls import path + +urlpatterns = [ + path('admin/', admin.site.urls), +] diff --git a/mabac/wsgi.py b/mabac/wsgi.py new file mode 100644 index 0000000..b43d43a --- /dev/null +++ b/mabac/wsgi.py @@ -0,0 +1,16 @@ +""" +WSGI config for mabac 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/4.2/howto/deployment/wsgi/ +""" + +import os + +from django.core.wsgi import get_wsgi_application + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mabac.settings') + +application = get_wsgi_application() diff --git a/manage.py b/manage.py new file mode 100755 index 0000000..a04f0b4 --- /dev/null +++ b/manage.py @@ -0,0 +1,22 @@ +#!/usr/bin/env python +"""Django's command-line utility for administrative tasks.""" +import os +import sys + + +def main(): + """Run administrative tasks.""" + os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mabac.settings') + try: + from django.core.management import execute_from_command_line + except ImportError as exc: + 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?" + ) from exc + execute_from_command_line(sys.argv) + + +if __name__ == '__main__': + main()