From e514faed88e3cb67ef69dcf906c3f0172f00e2f2 Mon Sep 17 00:00:00 2001 From: unknown Date: Mon, 17 Jul 2023 16:31:14 +0100 Subject: [PATCH] Jumpstart the app --- AUTHORS.rst | 13 + CONTRIBUTING.rst | 112 ++++++++ HISTORY.rst | 9 + LICENSE | 13 + MANIFEST.in | 6 + README.md | 76 ++++++ dj_auth_audit/__init__.py | 1 + dj_auth_audit/admin.py | 20 ++ dj_auth_audit/apps.py | 12 + dj_auth_audit/exceptions.py | 18 ++ dj_auth_audit/handlers.py | 5 + dj_auth_audit/migrations/0001_initial.py | 35 +++ dj_auth_audit/migrations/__init__.py | 0 dj_auth_audit/mixins.py | 129 +++++++++ dj_auth_audit/models.py | 73 +++++ dj_auth_audit/serializers.py | 16 ++ dj_auth_audit/signals.py | 45 ++++ .../templates/dj_auth_audit/base.html | 21 ++ dj_auth_audit/test_utils/__init__.py | 0 dj_auth_audit/test_utils/test_app/__init__.py | 0 dj_auth_audit/test_utils/test_app/admin.py | 3 + dj_auth_audit/test_utils/test_app/apps.py | 6 + .../test_app/migrations/__init__.py | 0 dj_auth_audit/test_utils/test_app/models.py | 3 + dj_auth_audit/urls.py | 35 +++ dj_auth_audit/views.py | 38 +++ docker-compose.yaml | 13 + docs/Makefile | 177 ++++++++++++ docs/authors.rst | 1 + docs/conf.py | 254 ++++++++++++++++++ docs/contributing.rst | 1 + docs/history.rst | 1 + docs/index.rst | 19 ++ docs/installation.rst | 12 + docs/make.bat | 242 +++++++++++++++++ docs/readme.rst | 1 + docs/usage.rst | 26 ++ manage.py | 12 + requirements.txt | 2 + runtests.py | 26 ++ setup.cfg | 16 ++ setup.py | 76 ++++++ tasks.py | 109 ++++++++ tests/README.md | 24 ++ tests/__init__.py | 0 tests/requirements.txt | 5 + tests/settings.py | 122 +++++++++ tests/test_models.py | 25 ++ tests/urls.py | 10 + tests/wsgi.py | 16 ++ tox.ini | 16 ++ 51 files changed, 1895 insertions(+) create mode 100644 AUTHORS.rst create mode 100644 CONTRIBUTING.rst create mode 100644 HISTORY.rst create mode 100644 LICENSE create mode 100644 MANIFEST.in create mode 100644 README.md create mode 100644 dj_auth_audit/__init__.py create mode 100644 dj_auth_audit/admin.py create mode 100644 dj_auth_audit/apps.py create mode 100644 dj_auth_audit/exceptions.py create mode 100644 dj_auth_audit/handlers.py create mode 100644 dj_auth_audit/migrations/0001_initial.py create mode 100644 dj_auth_audit/migrations/__init__.py create mode 100644 dj_auth_audit/mixins.py create mode 100644 dj_auth_audit/models.py create mode 100644 dj_auth_audit/serializers.py create mode 100644 dj_auth_audit/signals.py create mode 100644 dj_auth_audit/templates/dj_auth_audit/base.html create mode 100644 dj_auth_audit/test_utils/__init__.py create mode 100644 dj_auth_audit/test_utils/test_app/__init__.py create mode 100644 dj_auth_audit/test_utils/test_app/admin.py create mode 100644 dj_auth_audit/test_utils/test_app/apps.py create mode 100644 dj_auth_audit/test_utils/test_app/migrations/__init__.py create mode 100644 dj_auth_audit/test_utils/test_app/models.py create mode 100644 dj_auth_audit/urls.py create mode 100644 dj_auth_audit/views.py create mode 100644 docker-compose.yaml create mode 100644 docs/Makefile create mode 100644 docs/authors.rst create mode 100644 docs/conf.py create mode 100644 docs/contributing.rst create mode 100644 docs/history.rst create mode 100644 docs/index.rst create mode 100644 docs/installation.rst create mode 100644 docs/make.bat create mode 100644 docs/readme.rst create mode 100644 docs/usage.rst create mode 100644 manage.py create mode 100644 requirements.txt create mode 100644 runtests.py create mode 100644 setup.cfg create mode 100644 setup.py create mode 100644 tasks.py create mode 100644 tests/README.md create mode 100644 tests/__init__.py create mode 100644 tests/requirements.txt create mode 100644 tests/settings.py create mode 100644 tests/test_models.py create mode 100644 tests/urls.py create mode 100644 tests/wsgi.py create mode 100644 tox.ini diff --git a/AUTHORS.rst b/AUTHORS.rst new file mode 100644 index 0000000..0d36979 --- /dev/null +++ b/AUTHORS.rst @@ -0,0 +1,13 @@ +======= +Credits +======= + +Development Lead +---------------- + +* Chrigui Abdelbaki + +Contributors +------------ + +None yet. Why not be the first? diff --git a/CONTRIBUTING.rst b/CONTRIBUTING.rst new file mode 100644 index 0000000..703b13f --- /dev/null +++ b/CONTRIBUTING.rst @@ -0,0 +1,112 @@ +============ +Contributing +============ + +Contributions are welcome, and they are greatly appreciated! Every +little bit helps, and credit will always be given. + +You can contribute in many ways: + +Types of Contributions +---------------------- + +Report Bugs +~~~~~~~~~~~ + +Report bugs at https://github.com/abdelbaki1/dj-auth-audit/issues. + +If you are reporting a bug, please include: + +* Your operating system name and version. +* Any details about your local setup that might be helpful in troubleshooting. +* Detailed steps to reproduce the bug. + +Fix Bugs +~~~~~~~~ + +Look through the GitHub issues for bugs. Anything tagged with "bug" +is open to whoever wants to implement it. + +Implement Features +~~~~~~~~~~~~~~~~~~ + +Look through the GitHub issues for features. Anything tagged with "feature" +is open to whoever wants to implement it. + +Write Documentation +~~~~~~~~~~~~~~~~~~~ + +dj-auth-audit could always use more documentation, whether as part of the +official dj-auth-audit docs, in docstrings, or even on the web in blog posts, +articles, and such. + +Submit Feedback +~~~~~~~~~~~~~~~ + +The best way to send feedback is to file an issue at https://github.com/abdelbaki1/dj-auth-audit/issues. + +If you are proposing a feature: + +* Explain in detail how it would work. +* Keep the scope as narrow as possible, to make it easier to implement. +* Remember that this is a volunteer-driven project, and that contributions + are welcome :) + +Get Started! +------------ + +Ready to contribute? Here's how to set up `dj-auth-audit` for local development. + +1. Fork the `dj-auth-audit` repo on GitHub. +2. Clone your fork locally:: + + $ git clone git@github.com:your_name_here/dj-auth-audit.git + +3. Install your local copy into a virtualenv. Assuming you have virtualenvwrapper installed, this is how you set up your fork for local development:: + + $ mkvirtualenv dj-auth-audit + $ cd dj-auth-audit/ + $ python setup.py develop + +4. Create a branch for local development:: + + $ git checkout -b name-of-your-bugfix-or-feature + + Now you can make your changes locally. + +5. When you're done making changes, check that your changes pass flake8 and the + tests, including testing other Python versions with tox:: + + $ flake8 dj_auth_audit tests + $ python setup.py test + $ tox + + To get flake8 and tox, just pip install them into your virtualenv. + +6. Commit your changes and push your branch to GitHub:: + + $ git add . + $ git commit -m "Your detailed description of your changes." + $ git push origin name-of-your-bugfix-or-feature + +7. Submit a pull request through the GitHub website. + +Pull Request Guidelines +----------------------- + +Before you submit a pull request, check that it meets these guidelines: + +1. The pull request should include tests. +2. If the pull request adds functionality, the docs should be updated. Put + your new functionality into a function with a docstring, and add the + feature to the list in README.rst. +3. The pull request should work for Python 2.6, 2.7, and 3.3, and for PyPy. Check + https://travis-ci.org/abdelbaki1/dj-auth-audit/pull_requests + and make sure that the tests pass for all supported Python versions. + +Tips +---- + +To run a subset of tests:: + + $ python -m unittest tests.test_dj_auth_audit diff --git a/HISTORY.rst b/HISTORY.rst new file mode 100644 index 0000000..8c1c2cb --- /dev/null +++ b/HISTORY.rst @@ -0,0 +1,9 @@ +.. :changelog: + +History +------- + +0.1.0 (2023-07-16) +++++++++++++++++++ + +* First release on PyPI. diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..7556139 --- /dev/null +++ b/LICENSE @@ -0,0 +1,13 @@ +MIT License + +Copyright (c) 2023, Chrigui Abdelbaki + +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. + + + + diff --git a/MANIFEST.in b/MANIFEST.in new file mode 100644 index 0000000..d9150f5 --- /dev/null +++ b/MANIFEST.in @@ -0,0 +1,6 @@ +include AUTHORS.rst +include CONTRIBUTING.rst +include HISTORY.rst +include LICENSE +include README.md +recursive-include dj_auth_audit *.html *.png *.gif *js *.css *jpg *jpeg *svg *py diff --git a/README.md b/README.md new file mode 100644 index 0000000..0a30c79 --- /dev/null +++ b/README.md @@ -0,0 +1,76 @@ +**Make your authentication logs more easy with django-auth-audit** +================================================================== +# Please note +``django-auth-audit`` still an experimental project that originated as a feature in one of my professional projects. Due to the specific requirements and lack of existing GitHub repositories targeting this particular situation, I decided to create it as a separate project. As a result, the app is still in its early stages and may undergo frequent updates and improvements. Feedback and contributions are welcome. + +# Introduction +```django-auth-audit``` is a Django reusable app that provides functionality for tracking user authentication events, such as logins,logouts,password rest rate limit ... +It allows you to define custom mixins that override specific CRUD methods in your target class, send signals, and handle the flow back to your target class. Additionally, django-auth-audit includes a pre-defined mixins,that can be used to send signals and create authentication logs. + +## Installation + +To install ```django-auth-audit```, follow these steps: + +1. Ensure you have Django installed in your project. If not, you can install it using pip: + +```shell +pip install django +``` +Download the ```django-auth-audit``` package from the GitHub repository or install it using pip: +```python +pip install django-auth-audit +``` +Add ```django-auth-audit``` to the INSTALLED_APPS setting in your Django project's settings.py file: +```python +INSTALLED_APPS = [ + ... + 'django-auth-audit', + ... +] +``` +Run the database migrations to create the necessary tables for the app: +```shell +python manage.py migrate django-auth-audit +``` +# Usage +```django-auth-audit``` allows you to create custom mixins that override specific CRUD methods in your target class, send signals, and handle the flow back to your target class. +Here's an example: + +```python +from dj_auth_audit.mixins import FailedResetEmailSignalMixin + +class CustomPasswordResetView(FailedResetEmailSignalMixin, PasswordResetView): + class_name = 'PasswordResetView' + serializer_class = CustomPasswordResetSerializer + throttle_scope = 'reset_password_rate' +``` +In this example, the `CustomPasswordResetView` class inherits from `FailedResetEmailSignalMixin` and `PasswordResetView`. The `FailedResetEmailSignalMixin` sends a signal and creates an authentication log in the database, indicating the time of the sent reset email and the user who requested the password reset. If the user reaches the rate limit, another signal is triggered to indicate that the user has exceeded the password reset rate. + +The FailedResetEmailSignalMixin is hooked with the POST and throttled methods, which are typically defined in the target class. To use this mixin, you need to define the `class_name` attribute in the subclass alongside with the self.user to define the actor. +### Note +```django-auth-audit``` has a built-in mixin for all basic authentication logs you will need ,inclusing but not limited to : `Login` , `Logout`,`password change`,`password reset`,`verfication email` ... and if you define a throttle scope on the subclass , you will get rate limit signal the user have exceeded the allowed request rate. + +You can also define your own mixin by inheriting from `AbstractSignalMixin` in the `mixin.py` file. + +Note: The `FailedResetEmailSignalMixin` or any other mixin will raise an exception if: + +- ***class_name*** is not defined. +- The target class doesn't have any of the required methods for sending requests **(`POST`,`GET`...)** +- The ***self.user*** is not defined. +Please refer to `mixin.py` for more information on creating custom mixins and using the provided mixins. +# Contributing +If you'd like to contribute to this project, please follow these guidelines: + +Fork the repository on GitHub. +Create a new branch from the master branch for your feature or bug fix. +Make your changes and ensure they are properly tested. +Commit your changes with clear and descriptive commit messages. +Push your branch to your forked repository. +Submit a pull request to the master branch of the this repository. +Please refer to the Contribution Guidelines for more information. + +# License +```django-auth-audit``` is released under the MIT License. See the LICENSE file for more details. + +# Support +If you encounter any issues or have questions, please open an issue on the GitHub repository. diff --git a/dj_auth_audit/__init__.py b/dj_auth_audit/__init__.py new file mode 100644 index 0000000..34d7366 --- /dev/null +++ b/dj_auth_audit/__init__.py @@ -0,0 +1 @@ +__version__ = '0.0' diff --git a/dj_auth_audit/admin.py b/dj_auth_audit/admin.py new file mode 100644 index 0000000..63bc586 --- /dev/null +++ b/dj_auth_audit/admin.py @@ -0,0 +1,20 @@ +# -*- coding: utf-8 -*- + +from django.contrib import admin + +from .models import ( + AuthLogEntry, +) + + +class activityAdmin(admin.ModelAdmin): + + # def has_add_permission(self, request): + # return False + + def has_change_permission(self, request, obj=None): + return False + + # def has_delete_permission(self, request, obj=None): + # return False +admin.site.register(AuthLogEntry, activityAdmin) diff --git a/dj_auth_audit/apps.py b/dj_auth_audit/apps.py new file mode 100644 index 0000000..65f3ad9 --- /dev/null +++ b/dj_auth_audit/apps.py @@ -0,0 +1,12 @@ +# -*- coding: utf-8 +from django.apps import AppConfig + + +class DjAuthAuditConfig(AppConfig): + default_auto_field = 'django.db.models.BigAutoField' + name = 'dj_auth_audit' + def ready(self) -> None: + from .signals import AUTH_SIGNALS_CLASSES + from .handlers import create_auth_log + for siganl in AUTH_SIGNALS_CLASSES: + siganl.connect(create_auth_log) diff --git a/dj_auth_audit/exceptions.py b/dj_auth_audit/exceptions.py new file mode 100644 index 0000000..02cacf9 --- /dev/null +++ b/dj_auth_audit/exceptions.py @@ -0,0 +1,18 @@ +class ClassNameUnavailbleException(Exception): + pass + + +class UserUnavailableException(Exception): + pass + + +class PostUnavailableException(Exception): + pass + + +class SignalUnavailable(Exception): + pass + + +class ViewUnavailable(Exception): + pass diff --git a/dj_auth_audit/handlers.py b/dj_auth_audit/handlers.py new file mode 100644 index 0000000..2d94184 --- /dev/null +++ b/dj_auth_audit/handlers.py @@ -0,0 +1,5 @@ +from .models import AuthLogEntry + + +def create_auth_log(sender, action, changes=None, *args, **kwargs): + AuthLogEntry.objects.create(actor=sender, action=action, changes=changes) diff --git a/dj_auth_audit/migrations/0001_initial.py b/dj_auth_audit/migrations/0001_initial.py new file mode 100644 index 0000000..8b8ff82 --- /dev/null +++ b/dj_auth_audit/migrations/0001_initial.py @@ -0,0 +1,35 @@ +# Generated by Django 3.2.20 on 2023-07-16 19:26 + +from django.conf import settings +from django.db import migrations, models +import django.db.models.deletion +import django.utils.timezone + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ] + + operations = [ + migrations.CreateModel( + name='AuthLogEntry', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('action', models.PositiveSmallIntegerField(choices=[(0, 'login'), (1, 'login_failure'), (2, 'logout'), (3, 'logout_failure'), (4, 'password_change_success'), (5, 'password_change_failure'), (6, 'password_reset_success'), (7, 'password_reset_failure'), (8, 'email_validation_success'), (9, 'email_validation_failure'), (10, 'email_reset_password_success'), (11, 'email_reset_password_failure'), (12, 'upload_success'), (13, 'upload_failure')], db_index=True, verbose_name='action')), + ('cid', models.CharField(blank=True, db_index=True, max_length=255, null=True, verbose_name='Correlation ID')), + ('changes', models.JSONField(null=True, verbose_name='change message')), + ('timestamp', models.DateTimeField(db_index=True, default=django.utils.timezone.now, verbose_name='timestamp')), + ('actor', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to=settings.AUTH_USER_MODEL, verbose_name='actor')), + ], + options={ + 'verbose_name': 'authlog entry', + 'verbose_name_plural': 'authlog entries', + 'ordering': ['-timestamp'], + 'get_latest_by': 'timestamp', + }, + ), + ] diff --git a/dj_auth_audit/migrations/__init__.py b/dj_auth_audit/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/dj_auth_audit/mixins.py b/dj_auth_audit/mixins.py new file mode 100644 index 0000000..323fb30 --- /dev/null +++ b/dj_auth_audit/mixins.py @@ -0,0 +1,129 @@ +from dj_auth_audit.exceptions import ClassNameUnavailbleException, PostUnavailableException, SignalUnavailable, ViewUnavailable +from .signals import * +from abc import ABC +from django.utils.translation import ugettext_lazy as _ + + +class AbstractSignalMixin(ABC): + host_class: object + class_name: str + post_action: int + user = None + + def get_host_class(self): + if not hasattr(self, 'host_class'): + self.search_class() + return self.host_class + + def get_class_name(self): + if not hasattr(self, 'class_name'): + raise ClassNameUnavailbleException("class_name undefined") + return self.class_name.lower() + + def search_class(self): + classes = self.__class__.mro() + for cls in classes: + if cls.__name__.lower() == self.get_class_name(): + self.host_class = cls + return + + else: + raise ViewUnavailable('class name does not matches any existing view') + + def send_post_signal(self): + self.get_post_signal().send(sender=self.user, action=self.post_action) + + def get_post_signal(self): + raise SignalUnavailable('get_signal must be implemented') + + def post(self, request, *args, **kwargs): + if not hasattr(self.get_host_class(), 'post'): + raise PostUnavailableException( + 'unable to find post method in {}'.format(self.get_host_class())) + if request.user.is_authenticated: + self.user = request.user + res = self.get_host_class().post(self, request, *args, **kwargs) + self.send_post_signal() + return res + + +class LoginSignalMixin(AbstractSignalMixin): + post_action = 0 + + def get_post_signal(self): + return user_logged_in + + +class LogoutSignalMixin(AbstractSignalMixin): + post_action = 2 + + def get_post_signal(self): + return user_logged_out + + +class AbstractThrottleSignalMixin(AbstractSignalMixin): + def get_throttle_signal(self): + raise SignalUnavailable() + throttle_action: int + message: str + + def send_throttle_signal(self, request): + self.get_throttle_signal().send(sender=request.user, action=self.throttle_action, changes={ + 'detail': "user" + request.user.username + "have " + self.message + }) + + def throttled(self, request, wait): + self.send_throttle_signal(request=request) + return self.get_host_class().throttled(self, request, wait) + + +class FailedPasswordResetSignalMixin(AbstractThrottleSignalMixin): + """ + triggered when password reset limit is passed + """ + message = "exceeded his password reset limit" + throttle_action = 7 + post_action = 6 + + def get_post_signal(self): + return password_reset + + def get_throttle_signal(self): + return rate_limit_password_reset + + +class FailedResetEmailSignalMixin(AbstractThrottleSignalMixin): + message = "exceeded his email sent for reset password" + throttle_action = 12 + post_action = 10 + + def get_post_signal(self): + return password_reset_email_sent + + def get_throttle_signal(self): + return rate_limit_password_reset_email_sent + + +class FailedPasswordChangeSignalMixin(AbstractThrottleSignalMixin): + """triggered when password change limit is passed""" + message = "exceeded his password change limit" + throttle_action = 5 + post_action = 4 + + def get_signal(self): + return password_changed + + def get_throttle_signal(self): + return rate_limit_password_change + + +class FailedUploadImageRateSignal(AbstractThrottleSignalMixin): + message = "exceeded his mobile upload limit" + throttle_action = 13 + post_action = 12 + + def get_post_signal(self): + return file_uploaded + + def get_throttle_signal(self): + return mobile_upload_rate_limit diff --git a/dj_auth_audit/models.py b/dj_auth_audit/models.py new file mode 100644 index 0000000..092563c --- /dev/null +++ b/dj_auth_audit/models.py @@ -0,0 +1,73 @@ +from django.db import models +from django.conf import settings +from django.utils import timezone +from django.utils.translation import ugettext_lazy as _ + + +class AuthLogEntry(models.Model): + class Action: + LOGIN = 0 + LOGIN_FAILURE = 1 + LOGOUT = 2 + LOGOUT_FAILURE = 3 + PASSWORD_CHANGE_SUCCESS = 4 + PASSWORD_CHANGE_FAILURE = 5 + PASSWORD_RESET_SUCCESS = 6 + PASSWORD_RESET_FAILURE = 7 + EMAIL_VALIDATION_SUCCESS = 8 + EMAIL_VALIDATION_FAILURE = 9 + EMAIL_REST_PASSWORD_SUCCESS = 10 + EMAIL_REST_PASSWORD_FAILURE = 11 + UPLOAD_SUCCESS = 12 + UPLOAD_FAILURE = 13 + + choices = ( + (LOGIN, _("login")), + (LOGIN_FAILURE, _("login_failure")), + (LOGOUT, _("logout")), + (LOGOUT_FAILURE, _("logout_failure")), + (PASSWORD_CHANGE_SUCCESS, _("password_change_success")), + (PASSWORD_CHANGE_FAILURE, _("password_change_failure")), + (PASSWORD_RESET_SUCCESS, _("password_reset_success")), + (PASSWORD_RESET_FAILURE, _("password_reset_failure")), + (EMAIL_VALIDATION_SUCCESS, _("email_validation_success")), + (EMAIL_VALIDATION_FAILURE, _("email_validation_failure")), + (EMAIL_REST_PASSWORD_SUCCESS, _("email_reset_password_success")), + (EMAIL_REST_PASSWORD_FAILURE, _("email_reset_password_failure")), + (UPLOAD_SUCCESS, _('upload_success')), + (UPLOAD_FAILURE, _("upload_failure")), + ) + + action = models.PositiveSmallIntegerField( + choices=Action.choices, verbose_name=_("action"), db_index=True + ) + cid = models.CharField( + max_length=255, + db_index=True, + blank=True, + null=True, + verbose_name=_("Correlation ID"), + ) + changes = models.JSONField(null=True, verbose_name=_("change message")) + actor = models.ForeignKey( + to=settings.AUTH_USER_MODEL, + on_delete=models.SET_NULL, + blank=True, + null=True, + related_name="+", + verbose_name=_("actor"), + ) + timestamp = models.DateTimeField( + default=timezone.now, + db_index=True, + verbose_name=_("timestamp"), + ) + + class Meta: + get_latest_by = "timestamp" + ordering = ["-timestamp"] + verbose_name = _("authlog entry") + verbose_name_plural = _("authlog entries") + + def __str__(self) -> str: + return f"authlog of {self.actor} with action {self.Action.choices[self.action][1]}" diff --git a/dj_auth_audit/serializers.py b/dj_auth_audit/serializers.py new file mode 100644 index 0000000..19b8f78 --- /dev/null +++ b/dj_auth_audit/serializers.py @@ -0,0 +1,16 @@ +from rest_framework import serializers +from .models import AuthLogEntry + + +class AuthLogEntrySerializer(serializers.ModelSerializer): + timestamp = serializers.DateTimeField(format="%d %B/%Y at %H:%M:%S") + + actor = serializers.SlugRelatedField( + read_only=True, + slug_field="email", default='system' + ) + action = serializers.CharField(source='get_action_display') + + class Meta: + model = AuthLogEntry + fields = '__all__' diff --git a/dj_auth_audit/signals.py b/dj_auth_audit/signals.py new file mode 100644 index 0000000..2782192 --- /dev/null +++ b/dj_auth_audit/signals.py @@ -0,0 +1,45 @@ +from django.dispatch import Signal + +# Regular Signals +user_logged_in = Signal() +user_logged_out = Signal() + + +user_signed_up = Signal() + +password_set = Signal() +password_changed = Signal() +password_reset = Signal() + +email_confirmed = Signal() +email_confirmation_sent = Signal() + +password_reset_email_sent = Signal() +file_uploaded = Signal() + + +# ######### Signals for failing operations + +rate_limit_password_reset_email_sent = Signal() +rate_limit_password_change = Signal() + +rate_limit_password_reset = Signal() + +mobile_upload_rate_limit = Signal() + +AUTH_SIGNALS_CLASSES = [ + user_logged_in, + user_logged_out, + user_signed_up, + password_set, + password_changed, + password_reset, + email_confirmed, + email_confirmation_sent, + rate_limit_password_change, + rate_limit_password_reset, + rate_limit_password_reset_email_sent, + password_reset_email_sent, + file_uploaded, + mobile_upload_rate_limit, +] diff --git a/dj_auth_audit/templates/dj_auth_audit/base.html b/dj_auth_audit/templates/dj_auth_audit/base.html new file mode 100644 index 0000000..09d26f3 --- /dev/null +++ b/dj_auth_audit/templates/dj_auth_audit/base.html @@ -0,0 +1,21 @@ + +{% comment %} +As the developer of this package, don't place anything here if you can help it +since this allows developers to have interoperability between your template +structure and their own. + +Example: Developer melding the 2SoD pattern to fit inside with another pattern:: + + {% extends "base.html" %} + {% load static %} + + + {% block extra_js %} + + + {% block javascript %} + + {% endblock javascript %} + + {% endblock extra_js %} +{% endcomment %} diff --git a/dj_auth_audit/test_utils/__init__.py b/dj_auth_audit/test_utils/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/dj_auth_audit/test_utils/test_app/__init__.py b/dj_auth_audit/test_utils/test_app/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/dj_auth_audit/test_utils/test_app/admin.py b/dj_auth_audit/test_utils/test_app/admin.py new file mode 100644 index 0000000..051a1bd --- /dev/null +++ b/dj_auth_audit/test_utils/test_app/admin.py @@ -0,0 +1,3 @@ +from django.contrib import admin + +# Put your models admin models here diff --git a/dj_auth_audit/test_utils/test_app/apps.py b/dj_auth_audit/test_utils/test_app/apps.py new file mode 100644 index 0000000..286d683 --- /dev/null +++ b/dj_auth_audit/test_utils/test_app/apps.py @@ -0,0 +1,6 @@ +from django.apps import AppConfig + + +class TestAppConfig(AppConfig): + default_auto_field = 'django.db.models.BigAutoField' + name = 'dj_auth_audit.test_utils.test_app' diff --git a/dj_auth_audit/test_utils/test_app/migrations/__init__.py b/dj_auth_audit/test_utils/test_app/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/dj_auth_audit/test_utils/test_app/models.py b/dj_auth_audit/test_utils/test_app/models.py new file mode 100644 index 0000000..25a1b28 --- /dev/null +++ b/dj_auth_audit/test_utils/test_app/models.py @@ -0,0 +1,3 @@ +from django.db import models + +# Put your test models here diff --git a/dj_auth_audit/urls.py b/dj_auth_audit/urls.py new file mode 100644 index 0000000..4666d12 --- /dev/null +++ b/dj_auth_audit/urls.py @@ -0,0 +1,35 @@ +# -*- coding: utf-8 -*- +from django.conf.urls import url +from django.views.generic import TemplateView + +from . import views + + +app_name = 'dj_auth_audit' +urlpatterns = [ + url( + regex="^AuthLogEntry/~create/$", + view=views.AuthLogEntryCreateView.as_view(), + name='AuthLogEntry_create', + ), + url( + regex="^AuthLogEntry/(?P\d+)/~delete/$", + view=views.AuthLogEntryDeleteView.as_view(), + name='AuthLogEntry_delete', + ), + url( + regex="^AuthLogEntry/(?P\d+)/$", + view=views.AuthLogEntryDetailView.as_view(), + name='AuthLogEntry_detail', + ), + url( + regex="^AuthLogEntry/(?P\d+)/~update/$", + view=views.AuthLogEntryUpdateView.as_view(), + name='AuthLogEntry_update', + ), + url( + regex="^AuthLogEntry/$", + view=views.AuthLogEntryListView.as_view(), + name='AuthLogEntry_list', + ), + ] diff --git a/dj_auth_audit/views.py b/dj_auth_audit/views.py new file mode 100644 index 0000000..29cd9ae --- /dev/null +++ b/dj_auth_audit/views.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +from django.views.generic import ( + CreateView, + DeleteView, + DetailView, + UpdateView, + ListView +) + +from .models import ( + AuthLogEntry, +) + + +class AuthLogEntryCreateView(CreateView): + + model = AuthLogEntry + + +class AuthLogEntryDeleteView(DeleteView): + + model = AuthLogEntry + + +class AuthLogEntryDetailView(DetailView): + + model = AuthLogEntry + + +class AuthLogEntryUpdateView(UpdateView): + + model = AuthLogEntry + + +class AuthLogEntryListView(ListView): + + model = AuthLogEntry + diff --git a/docker-compose.yaml b/docker-compose.yaml new file mode 100644 index 0000000..c51bdda --- /dev/null +++ b/docker-compose.yaml @@ -0,0 +1,13 @@ +services: + db_dj_auth_audit: + container_name: db_dj_auth_audit + image: postgres + restart: always + environment: + POSTGRES_DB: ${TEST_DB_NAME} + POSTGRES_USER: ${TEST_DB_USER} + POSTGRES_PASSWORD: ${TEST_DB_PASS} + ports: + - "${TEST_DB_PORT}:5432" +# networks: +# - internal \ No newline at end of file diff --git a/docs/Makefile b/docs/Makefile new file mode 100644 index 0000000..0e35bee --- /dev/null +++ b/docs/Makefile @@ -0,0 +1,177 @@ +# Makefile for Sphinx documentation +# + +# You can set these variables from the command line. +SPHINXOPTS = +SPHINXBUILD = sphinx-build +PAPER = +BUILDDIR = _build + +# User-friendly check for sphinx-build +ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) +$(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) +endif + +# Internal variables. +PAPEROPT_a4 = -D latex_paper_size=a4 +PAPEROPT_letter = -D latex_paper_size=letter +ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . +# the i18n builder cannot share the environment and doctrees with the others +I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . + +.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext + +help: + @echo "Please use \`make ' where is one of" + @echo " html to make standalone HTML files" + @echo " dirhtml to make HTML files named index.html in directories" + @echo " singlehtml to make a single large HTML file" + @echo " pickle to make pickle files" + @echo " json to make JSON files" + @echo " htmlhelp to make HTML files and a HTML help project" + @echo " qthelp to make HTML files and a qthelp project" + @echo " devhelp to make HTML files and a Devhelp project" + @echo " epub to make an epub" + @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" + @echo " latexpdf to make LaTeX files and run them through pdflatex" + @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" + @echo " text to make text files" + @echo " man to make manual pages" + @echo " texinfo to make Texinfo files" + @echo " info to make Texinfo files and run them through makeinfo" + @echo " gettext to make PO message catalogs" + @echo " changes to make an overview of all changed/added/deprecated items" + @echo " xml to make Docutils-native XML files" + @echo " pseudoxml to make pseudoxml-XML files for display purposes" + @echo " linkcheck to check all external links for integrity" + @echo " doctest to run all doctests embedded in the documentation (if enabled)" + +clean: + rm -rf $(BUILDDIR)/* + +html: + $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html + @echo + @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." + +dirhtml: + $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml + @echo + @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." + +singlehtml: + $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml + @echo + @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." + +pickle: + $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle + @echo + @echo "Build finished; now you can process the pickle files." + +json: + $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json + @echo + @echo "Build finished; now you can process the JSON files." + +htmlhelp: + $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp + @echo + @echo "Build finished; now you can run HTML Help Workshop with the" \ + ".hhp project file in $(BUILDDIR)/htmlhelp." + +qthelp: + $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp + @echo + @echo "Build finished; now you can run "qcollectiongenerator" with the" \ + ".qhcp project file in $(BUILDDIR)/qthelp, like this:" + @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/complexity.qhcp" + @echo "To view the help file:" + @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/complexity.qhc" + +devhelp: + $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp + @echo + @echo "Build finished." + @echo "To view the help file:" + @echo "# mkdir -p $$HOME/.local/share/devhelp/complexity" + @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/complexity" + @echo "# devhelp" + +epub: + $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub + @echo + @echo "Build finished. The epub file is in $(BUILDDIR)/epub." + +latex: + $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex + @echo + @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." + @echo "Run \`make' in that directory to run these through (pdf)latex" \ + "(use \`make latexpdf' here to do that automatically)." + +latexpdf: + $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex + @echo "Running LaTeX files through pdflatex..." + $(MAKE) -C $(BUILDDIR)/latex all-pdf + @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." + +latexpdfja: + $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex + @echo "Running LaTeX files through platex and dvipdfmx..." + $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja + @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." + +text: + $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text + @echo + @echo "Build finished. The text files are in $(BUILDDIR)/text." + +man: + $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man + @echo + @echo "Build finished. The manual pages are in $(BUILDDIR)/man." + +texinfo: + $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo + @echo + @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." + @echo "Run \`make' in that directory to run these through makeinfo" \ + "(use \`make info' here to do that automatically)." + +info: + $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo + @echo "Running Texinfo files through makeinfo..." + make -C $(BUILDDIR)/texinfo info + @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." + +gettext: + $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale + @echo + @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." + +changes: + $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes + @echo + @echo "The overview file is in $(BUILDDIR)/changes." + +linkcheck: + $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck + @echo + @echo "Link check complete; look for any errors in the above output " \ + "or in $(BUILDDIR)/linkcheck/output.txt." + +doctest: + $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest + @echo "Testing of doctests in the sources finished, look at the " \ + "results in $(BUILDDIR)/doctest/output.txt." + +xml: + $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml + @echo + @echo "Build finished. The XML files are in $(BUILDDIR)/xml." + +pseudoxml: + $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml + @echo + @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." diff --git a/docs/authors.rst b/docs/authors.rst new file mode 100644 index 0000000..e122f91 --- /dev/null +++ b/docs/authors.rst @@ -0,0 +1 @@ +.. include:: ../AUTHORS.rst diff --git a/docs/conf.py b/docs/conf.py new file mode 100644 index 0000000..a87b397 --- /dev/null +++ b/docs/conf.py @@ -0,0 +1,254 @@ +# -*- coding: utf-8 -*- +# +# complexity documentation build configuration file, created by +# sphinx-quickstart on Tue Jul 9 22:26:36 2013. +# +# This file is execfile()d with the current directory set to its containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +import sys, os + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +#sys.path.insert(0, os.path.abspath('.')) + +cwd = os.getcwd() +parent = os.path.dirname(cwd) +sys.path.append(parent) + +import dj_auth_audit + +# -- General configuration ----------------------------------------------------- + +# If your documentation needs a minimal Sphinx version, state it here. +#needs_sphinx = '1.0' + +# Add any Sphinx extension module names here, as strings. They can be extensions +# coming with Sphinx (named 'sphinx.ext.*') or your custom ones. +extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode'] + +# Add any paths that contain templates here, relative to this directory. +templates_path = ['_templates'] + +# The suffix of source filenames. +source_suffix = '.rst' + +# The encoding of source files. +#source_encoding = 'utf-8-sig' + +# The master toctree document. +master_doc = 'index' + +# General information about the project. +project = u'dj-auth-audit' +copyright = u'2023, Chrigui Abdelbaki' + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The short X.Y version. +version = dj_auth_audit.__version__ +# The full version, including alpha/beta/rc tags. +release = dj_auth_audit.__version__ + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +#language = None + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +#today = '' +# Else, today_fmt is used as the format for a strftime call. +#today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = ['_build'] + +# The reST default role (used for this markup: `text`) to use for all documents. +#default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +#add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +#add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +#show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = 'sphinx' + +# A list of ignored prefixes for module index sorting. +#modindex_common_prefix = [] + +# If true, keep warnings as "system message" paragraphs in the built documents. +#keep_warnings = False + + +# -- Options for HTML output --------------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +html_theme = 'default' + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +#html_theme_options = {} + +# Add any paths that contain custom themes here, relative to this directory. +#html_theme_path = [] + +# The name for this set of Sphinx documents. If None, it defaults to +# " v documentation". +#html_title = None + +# A shorter title for the navigation bar. Default is the same as html_title. +#html_short_title = None + +# The name of an image file (relative to this directory) to place at the top +# of the sidebar. +#html_logo = None + +# The name of an image file (within the static path) to use as favicon of the +# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 +# pixels large. +#html_favicon = None + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ['_static'] + +# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, +# using the given strftime format. +#html_last_updated_fmt = '%b %d, %Y' + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +#html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +#html_sidebars = {} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +#html_additional_pages = {} + +# If false, no module index is generated. +#html_domain_indices = True + +# If false, no index is generated. +#html_use_index = True + +# If true, the index is split into individual pages for each letter. +#html_split_index = False + +# If true, links to the reST sources are added to the pages. +#html_show_sourcelink = True + +# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. +#html_show_sphinx = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. +#html_show_copyright = True + +# If true, an OpenSearch description file will be output, and all pages will +# contain a tag referring to it. The value of this option must be the +# base URL from which the finished HTML is served. +#html_use_opensearch = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +#html_file_suffix = None + +# Output file base name for HTML help builder. +htmlhelp_basename = 'dj-auth-auditdoc' + + +# -- Options for LaTeX output -------------------------------------------------- + +latex_elements = { +# The paper size ('letterpaper' or 'a4paper'). +#'papersize': 'letterpaper', + +# The font size ('10pt', '11pt' or '12pt'). +#'pointsize': '10pt', + +# Additional stuff for the LaTeX preamble. +#'preamble': '', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, author, documentclass [howto/manual]). +latex_documents = [ + ('index', 'dj-auth-audit.tex', u'dj-auth-audit Documentation', + u'Chrigui Abdelbaki', 'manual'), +] + +# The name of an image file (relative to this directory) to place at the top of +# the title page. +#latex_logo = None + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +#latex_use_parts = False + +# If true, show page references after internal links. +#latex_show_pagerefs = False + +# If true, show URL addresses after external links. +#latex_show_urls = False + +# Documents to append as an appendix to all manuals. +#latex_appendices = [] + +# If false, no module index is generated. +#latex_domain_indices = True + + +# -- Options for manual page output -------------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + ('index', 'dj-auth-audit', u'dj-auth-audit Documentation', + [u'Chrigui Abdelbaki'], 1) +] + +# If true, show URL addresses after external links. +#man_show_urls = False + + +# -- Options for Texinfo output ------------------------------------------------ + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + ('index', 'dj-auth-audit', u'dj-auth-audit Documentation', + u'Chrigui Abdelbaki', 'dj-auth-audit', 'One line description of project.', + 'Miscellaneous'), +] + +# Documents to append as an appendix to all manuals. +#texinfo_appendices = [] + +# If false, no module index is generated. +#texinfo_domain_indices = True + +# How to display URL addresses: 'footnote', 'no', or 'inline'. +#texinfo_show_urls = 'footnote' + +# If true, do not generate a @detailmenu in the "Top" node's menu. +#texinfo_no_detailmenu = False diff --git a/docs/contributing.rst b/docs/contributing.rst new file mode 100644 index 0000000..e582053 --- /dev/null +++ b/docs/contributing.rst @@ -0,0 +1 @@ +.. include:: ../CONTRIBUTING.rst diff --git a/docs/history.rst b/docs/history.rst new file mode 100644 index 0000000..2506499 --- /dev/null +++ b/docs/history.rst @@ -0,0 +1 @@ +.. include:: ../HISTORY.rst diff --git a/docs/index.rst b/docs/index.rst new file mode 100644 index 0000000..414d6aa --- /dev/null +++ b/docs/index.rst @@ -0,0 +1,19 @@ +.. complexity documentation master file, created by + sphinx-quickstart on Tue Jul 9 22:26:36 2013. + You can adapt this file completely to your liking, but it should at least + contain the root `toctree` directive. + +Welcome to dj-auth-audit's documentation! +================================================================= + +Contents: + +.. toctree:: + :maxdepth: 2 + + readme + installation + usage + contributing + authors + history diff --git a/docs/installation.rst b/docs/installation.rst new file mode 100644 index 0000000..6f35e42 --- /dev/null +++ b/docs/installation.rst @@ -0,0 +1,12 @@ +============ +Installation +============ + +At the command line:: + + $ easy_install dj-auth-audit + +Or, if you have virtualenvwrapper installed:: + + $ mkvirtualenv dj-auth-audit + $ pip install dj-auth-audit diff --git a/docs/make.bat b/docs/make.bat new file mode 100644 index 0000000..2df9a8c --- /dev/null +++ b/docs/make.bat @@ -0,0 +1,242 @@ +@ECHO OFF + +REM Command file for Sphinx documentation + +if "%SPHINXBUILD%" == "" ( + set SPHINXBUILD=sphinx-build +) +set BUILDDIR=_build +set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . +set I18NSPHINXOPTS=%SPHINXOPTS% . +if NOT "%PAPER%" == "" ( + set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% + set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% +) + +if "%1" == "" goto help + +if "%1" == "help" ( + :help + echo.Please use `make ^` where ^ is one of + echo. html to make standalone HTML files + echo. dirhtml to make HTML files named index.html in directories + echo. singlehtml to make a single large HTML file + echo. pickle to make pickle files + echo. json to make JSON files + echo. htmlhelp to make HTML files and a HTML help project + echo. qthelp to make HTML files and a qthelp project + echo. devhelp to make HTML files and a Devhelp project + echo. epub to make an epub + echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter + echo. text to make text files + echo. man to make manual pages + echo. texinfo to make Texinfo files + echo. gettext to make PO message catalogs + echo. changes to make an overview over all changed/added/deprecated items + echo. xml to make Docutils-native XML files + echo. pseudoxml to make pseudoxml-XML files for display purposes + echo. linkcheck to check all external links for integrity + echo. doctest to run all doctests embedded in the documentation if enabled + goto end +) + +if "%1" == "clean" ( + for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i + del /q /s %BUILDDIR%\* + goto end +) + + +%SPHINXBUILD% 2> nul +if errorlevel 9009 ( + echo. + echo.The 'sphinx-build' command was not found. Make sure you have Sphinx + echo.installed, then set the SPHINXBUILD environment variable to point + echo.to the full path of the 'sphinx-build' executable. Alternatively you + echo.may add the Sphinx directory to PATH. + echo. + echo.If you don't have Sphinx installed, grab it from + echo.http://sphinx-doc.org/ + exit /b 1 +) + +if "%1" == "html" ( + %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The HTML pages are in %BUILDDIR%/html. + goto end +) + +if "%1" == "dirhtml" ( + %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. + goto end +) + +if "%1" == "singlehtml" ( + %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. + goto end +) + +if "%1" == "pickle" ( + %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; now you can process the pickle files. + goto end +) + +if "%1" == "json" ( + %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; now you can process the JSON files. + goto end +) + +if "%1" == "htmlhelp" ( + %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; now you can run HTML Help Workshop with the ^ +.hhp project file in %BUILDDIR%/htmlhelp. + goto end +) + +if "%1" == "qthelp" ( + %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; now you can run "qcollectiongenerator" with the ^ +.qhcp project file in %BUILDDIR%/qthelp, like this: + echo.^> qcollectiongenerator %BUILDDIR%\qthelp\complexity.qhcp + echo.To view the help file: + echo.^> assistant -collectionFile %BUILDDIR%\qthelp\complexity.ghc + goto end +) + +if "%1" == "devhelp" ( + %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. + goto end +) + +if "%1" == "epub" ( + %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The epub file is in %BUILDDIR%/epub. + goto end +) + +if "%1" == "latex" ( + %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. + goto end +) + +if "%1" == "latexpdf" ( + %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex + cd %BUILDDIR%/latex + make all-pdf + cd %BUILDDIR%/.. + echo. + echo.Build finished; the PDF files are in %BUILDDIR%/latex. + goto end +) + +if "%1" == "latexpdfja" ( + %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex + cd %BUILDDIR%/latex + make all-pdf-ja + cd %BUILDDIR%/.. + echo. + echo.Build finished; the PDF files are in %BUILDDIR%/latex. + goto end +) + +if "%1" == "text" ( + %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The text files are in %BUILDDIR%/text. + goto end +) + +if "%1" == "man" ( + %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The manual pages are in %BUILDDIR%/man. + goto end +) + +if "%1" == "texinfo" ( + %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. + goto end +) + +if "%1" == "gettext" ( + %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The message catalogs are in %BUILDDIR%/locale. + goto end +) + +if "%1" == "changes" ( + %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes + if errorlevel 1 exit /b 1 + echo. + echo.The overview file is in %BUILDDIR%/changes. + goto end +) + +if "%1" == "linkcheck" ( + %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck + if errorlevel 1 exit /b 1 + echo. + echo.Link check complete; look for any errors in the above output ^ +or in %BUILDDIR%/linkcheck/output.txt. + goto end +) + +if "%1" == "doctest" ( + %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest + if errorlevel 1 exit /b 1 + echo. + echo.Testing of doctests in the sources finished, look at the ^ +results in %BUILDDIR%/doctest/output.txt. + goto end +) + +if "%1" == "xml" ( + %SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The XML files are in %BUILDDIR%/xml. + goto end +) + +if "%1" == "pseudoxml" ( + %SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml. + goto end +) + +:end diff --git a/docs/readme.rst b/docs/readme.rst new file mode 100644 index 0000000..bdff72a --- /dev/null +++ b/docs/readme.rst @@ -0,0 +1 @@ +.. include:: ../README.md diff --git a/docs/usage.rst b/docs/usage.rst new file mode 100644 index 0000000..e8941d7 --- /dev/null +++ b/docs/usage.rst @@ -0,0 +1,26 @@ +===== +Usage +===== + +To use dj-auth-audit in a project, add it to your `INSTALLED_APPS`: + +.. code-block:: python + + INSTALLED_APPS = ( + ... + 'dj_auth_audit.apps.DjAuthAuditConfig', + ... + ) + +Add dj-auth-audit's URL patterns: + +.. code-block:: python + + from dj_auth_audit import urls as dj_auth_audit_urls + + + urlpatterns = [ + ... + url(r'^', include(dj_auth_audit_urls)), + ... + ] diff --git a/manage.py b/manage.py new file mode 100644 index 0000000..8c5be8a --- /dev/null +++ b/manage.py @@ -0,0 +1,12 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +from __future__ import unicode_literals, absolute_import + +import os +import sys + +if __name__ == "__main__": + os.environ.setdefault("DJANGO_SETTINGS_MODULE", "tests.settings") + from django.core.management import execute_from_command_line + + execute_from_command_line(sys.argv) diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..0166d95 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,2 @@ +django-model-utils>=2.0 +# Additional requirements go here diff --git a/runtests.py b/runtests.py new file mode 100644 index 0000000..a68cf32 --- /dev/null +++ b/runtests.py @@ -0,0 +1,26 @@ +#!/usr/bin/env python +# -*- coding: utf-8 +from __future__ import unicode_literals, absolute_import + +import os +import sys + +import django +from django.conf import settings +from django.test.utils import get_runner + + +def run_tests(*test_args): + if not test_args: + test_args = ['tests'] + + os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings' + django.setup() + TestRunner = get_runner(settings) + test_runner = TestRunner() + failures = test_runner.run_tests(test_args) + sys.exit(bool(failures)) + + +if __name__ == '__main__': + run_tests(*sys.argv[1:]) diff --git a/setup.cfg b/setup.cfg new file mode 100644 index 0000000..1236acd --- /dev/null +++ b/setup.cfg @@ -0,0 +1,16 @@ +[wheel] +universal = 1 + +[flake8] +ignore = D203 +exclude = + dj_auth_audit/migrations, + .git, + .tox, + docs/conf.py, + build, + dist +max-line-length = 119 + +[zest.releaser] +python-file-with-version = dj_auth_audit/__init__.py diff --git a/setup.py b/setup.py new file mode 100644 index 0000000..310a44f --- /dev/null +++ b/setup.py @@ -0,0 +1,76 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +import os +import re +import sys + +try: + from setuptools import setup +except ImportError: + from distutils.core import setup + + +def get_version(*file_paths): + """Retrieves the version from dj_auth_audit/__init__.py""" + filename = os.path.join(os.path.dirname(__file__), *file_paths) + version_file = open(filename).read() + version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]", + version_file, re.M) + if version_match: + return version_match.group(1) + raise RuntimeError('Unable to find version string.') + + +version = get_version("dj_auth_audit", "__init__.py") + + +if sys.argv[-1] == 'publish': + try: + import wheel + print("Wheel version: ", wheel.__version__) + except ImportError: + print('Wheel library missing. Please run "pip install wheel"') + sys.exit() + os.system('python setup.py sdist upload') + os.system('python setup.py bdist_wheel upload') + sys.exit() + +if sys.argv[-1] == 'tag': + print("Tagging the version on git:") + os.system("git tag -a %s -m 'version %s'" % (version, version)) + os.system("git push --tags") + sys.exit() + +readme = open('README.md').read() +history = open('HISTORY.rst').read().replace('.. :changelog:', '') +requirements = open('requirements.txt').readlines() + +setup( + name='dj-auth-audit', + version=version, + description="""Your project description goes here""", + long_description=readme + '\n\n' + history, + long_description_content_type='text/markdown', + author='Chrigui Abdelbaki', + author_email='chriguiabdelbaki@gmail.com', + url='https://github.com/abdelbaki1/django-auth-audit', + packages=[ + 'dj_auth_audit', + ], + include_package_data=True, + install_requires=requirements, + license="MIT", + zip_safe=False, + keywords='dj-auth-audit', + classifiers=[ + 'Development Status :: 3 - Alpha', + 'Intended Audience :: Developers', + 'License :: OSI Approved :: BSD License', + 'Natural Language :: English', + 'Programming Language :: Python :: 2', + 'Programming Language :: Python :: 2.7', + 'Programming Language :: Python :: 3', + 'Programming Language :: Python :: 3.5', + 'Programming Language :: Python :: 3.6', + ], +) diff --git a/tasks.py b/tasks.py new file mode 100644 index 0000000..828a50c --- /dev/null +++ b/tasks.py @@ -0,0 +1,109 @@ +import os +import webbrowser + +from invoke import task + + +def open_browser(path): + try: + from urllib import pathname2url + except: + from urllib.request import pathname2url + webbrowser.open("file://" + pathname2url(os.path.abspath(path))) + + +@task +def clean_build(c): + """ + Remove build artifacts + """ + c.run("rm -fr build/") + c.run("rm -fr dist/") + c.run("rm -fr *.egg-info") + + +@task +def clean_pyc(c): + """ + Remove python file artifacts + """ + c.run("find . -name '*.pyc' -exec rm -f {} +") + c.run("find . -name '*.pyo' -exec rm -f {} +") + c.run("find . -name '*~' -exec rm -f {} +") + + +@task +def coverage(c): + """ + check code coverage quickly with the default Python + """ + c.run("coverage run --source dj-auth-audit runtests.py tests") + c.run("coverage report -m") + c.run("coverage html") + c.run("open htmlcov/index.html") + + +@task +def docs(c): + """ + Build the documentation and open it in the browser + """ + c.run("rm -f docs/dj-auth-audit.rst") + c.run("rm -f docs/modules.rst") + c.run("sphinx-apidoc -o docs/ dj_auth_audit") + + c.run("sphinx-build -E -b html docs docs/_build") + open_browser(path='docs/_build/html/index.html') + + +@task +def test_all(c): + """ + Run tests on every python version with tox + """ + c.run("tox") + + +@task +def clean(c): + """ + Remove python file and build artifacts + """ + clean_build(c) + clean_pyc(c) + + +@task +def unittest(c): + """ + Run unittests + """ + c.run("python manage.py test") + + +@task +def lint(c): + """ + Check style with flake8 + """ + c.run("flake8 dj-auth-audit tests") + + +@task(help={'bumpsize': 'Bump either for a "feature" or "breaking" change'}) +def release(c, bumpsize=''): + """ + Package and upload a release + """ + clean(c) + if bumpsize: + bumpsize = '--' + bumpsize + + c.run("bumpversion {bump} --no-input".format(bump=bumpsize)) + + import dj_auth_audit + c.run("python setup.py sdist bdist_wheel") + c.run("twine upload dist/*") + + c.run('git tag -a {version} -m "New version: {version}"'.format(version=dj_auth_audit.__version__)) + c.run("git push --tags") + c.run("git push origin master") diff --git a/tests/README.md b/tests/README.md new file mode 100644 index 0000000..a8ccbe9 --- /dev/null +++ b/tests/README.md @@ -0,0 +1,24 @@ +## Example Project for dj_auth_audit + +This example is provided as a convenience feature to allow potential users to try the app straight from the app repo without having to create a django project. + +It can also be used to develop the app in place. + +To run this example, follow these instructions: + +1. Navigate to the root directory of your application (same as `manage.py`) +2. Install the requirements for the package: + + pip install -r requirements.txt + +3. Make and apply migrations + + python manage.py makemigrations + + python manage.py migrate + +4. Run the server + + python manage.py runserver + +5. Access from the browser at `http://127.0.0.1:8000` diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/requirements.txt b/tests/requirements.txt new file mode 100644 index 0000000..bc331ce --- /dev/null +++ b/tests/requirements.txt @@ -0,0 +1,5 @@ +# Your app requirements. +-r ../requirements_test.txt + +# Your app in editable mode. +-e ../ diff --git a/tests/settings.py b/tests/settings.py new file mode 100644 index 0000000..997dbb8 --- /dev/null +++ b/tests/settings.py @@ -0,0 +1,122 @@ +""" +Django settings for example project. + +Generated by Cookiecutter Django Package +""" + +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__))) + +# Quick-start development settings - unsuitable for production +# See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/ + +# SECURITY WARNING: keep the secret key used in production secret! +SECRET_KEY = "b40!+x@2#1i7_u(uiqywibt*i9dkcvk7@*whb!7$^w06@jkcf5" + +# 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', + + 'dj_auth_audit', + + 'dj_auth_audit.test_utils.test_app' + + + # if your app has other dependencies that need to be added to the site + # they should be added here +] + +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 = 'tests.urls' + +TEMPLATES = [ + { + 'BACKEND': 'django.template.backends.django.DjangoTemplates', + 'DIRS': [os.path.join(BASE_DIR, 'templates'), ], + '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 = 'tests.wsgi.application' + +# Database +# https://docs.djangoproject.com/en/1.9/ref/settings/#databases + +DATABASES = { + "default": { + "ENGINE": "django.db.backends.postgresql", + "NAME": os.getenv( + "TEST_DB_NAME", 'TEST_DB_NAME' + ), + "USER": os.getenv("TEST_DB_USER", "TEST_DB_USER"), + "PASSWORD": os.getenv("TEST_DB_PASS", "TEST_DB_PASS"), + "HOST": os.getenv("TEST_DB_HOST", "127.0.0.1"), + "PORT": os.getenv("TEST_DB_PORT", "6543"), + } +} + +# Password validation +# https://docs.djangoproject.com/en/1.9/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/1.9/topics/i18n/ + +LANGUAGE_CODE = 'en-us' + +TIME_ZONE = 'UTC' + +USE_I18N = True + +USE_L10N = True + +USE_TZ = True + +# Static files (CSS, JavaScript, Images) +# https://docs.djangoproject.com/en/1.9/howto/static-files/ + +STATIC_URL = '/static/' diff --git a/tests/test_models.py b/tests/test_models.py new file mode 100644 index 0000000..b275647 --- /dev/null +++ b/tests/test_models.py @@ -0,0 +1,25 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +""" +test_dj-auth-audit +------------ + +Tests for `dj-auth-audit` models module. +""" + +from django.test import TestCase + +from dj_auth_audit import models + + +class TestDj_auth_audit(TestCase): + + def setUp(self): + pass + + def test_something(self): + pass + + def tearDown(self): + pass diff --git a/tests/urls.py b/tests/urls.py new file mode 100644 index 0000000..6ae6e1b --- /dev/null +++ b/tests/urls.py @@ -0,0 +1,10 @@ +# -*- coding: utf-8 -*- +from __future__ import unicode_literals, absolute_import + +from django.conf.urls import url, include +from django.contrib import admin + +urlpatterns = [ + url(r'^admin/', admin.site.urls), + url(r'^', include('dj_auth_audit.urls', namespace='dj_auth_audit')), +] diff --git a/tests/wsgi.py b/tests/wsgi.py new file mode 100644 index 0000000..ab9b7da --- /dev/null +++ b/tests/wsgi.py @@ -0,0 +1,16 @@ +""" +WSGI config for example 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/1.9/howto/deployment/wsgi/ +""" + +import os + +from django.core.wsgi import get_wsgi_application + +os.environ.setdefault("DJANGO_SETTINGS_MODULE", "tests.settings") + +application = get_wsgi_application() diff --git a/tox.ini b/tox.ini new file mode 100644 index 0000000..87d3c82 --- /dev/null +++ b/tox.ini @@ -0,0 +1,16 @@ +[tox] +envlist = + {py35,py36}-django-master + +[testenv] +setenv = + PYTHONPATH = {toxinidir}:{toxinidir}/dj_auth_audit +commands = coverage run --source dj_auth_audit runtests.py +deps = + django-master: https://github.com/django/django/archive/master.tar.gz + -r{toxinidir}/requirements_test.txt +basepython = + py37: python3.7 + py36: python3.6 + py35: python3.5 + py27: python2.7