pax_global_header00006660000000000000000000000064147233574350014527gustar00rootroot0000000000000052 comment=9a7673a47ee064cb8150ddeef1394d7157079741 django-axes-7.0.1/000077500000000000000000000000001472335743500137345ustar00rootroot00000000000000django-axes-7.0.1/.github/000077500000000000000000000000001472335743500152745ustar00rootroot00000000000000django-axes-7.0.1/.github/ISSUE_TEMPLATE/000077500000000000000000000000001472335743500174575ustar00rootroot00000000000000django-axes-7.0.1/.github/ISSUE_TEMPLATE/bug_report.md000066400000000000000000000012061472335743500221500ustar00rootroot00000000000000--- name: Bug report about: Create a report to help us improve django-axes title: 'BUG: Short description of the problem' labels: 'bug' assignees: '' --- **Describe the bug** A clear and concise description of what the bug is. **To Reproduce** Steps to reproduce the behavior: 1. 2. 3. 4. **Expected behavior** A clear and concise description of what you expected to happen. **Your environment** python version: django version: django-axes version: Operating system: **Additional context** Add any other context about the problem here. **Possible implementation** Not obligatory, but suggest an idea for implementing addition or change django-axes-7.0.1/.github/ISSUE_TEMPLATE/feature_request.md000066400000000000000000000012301472335743500232000ustar00rootroot00000000000000--- name: Feature request about: Suggest an idea for django-axes title: 'FEATURE REQUEST: Short description of requested feature' labels: 'feature request' assignees: '' --- **Is your feature request related to a problem? Please describe.** A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] **Describe the solution you'd like** A clear and concise description of what you want to happen. **Describe alternatives you've considered** A clear and concise description of any alternative solutions or features you've considered. **Additional context** Add any other context or screenshots about the feature request here. django-axes-7.0.1/.github/PULL_REQUEST_TEMPLATE.md000066400000000000000000000013321472335743500210740ustar00rootroot00000000000000# What does this PR do? Fixes # (issue) ## Before submitting - [ ] This PR fixes a typo or improves the docs (you can dismiss the other checks if that's the case). - [ ] Did you make sure to update the documentation with your changes? - [ ] Did you write any new necessary tests? django-axes-7.0.1/.github/dependabot.yml000066400000000000000000000004351472335743500201260ustar00rootroot00000000000000version: 2 updates: - package-ecosystem: "pip" directory: "/" schedule: interval: "daily" time: "12:00" open-pull-requests-limit: 10 - package-ecosystem: "github-actions" directory: "/" schedule: interval: "daily" time: "12:00" open-pull-requests-limit: 10 django-axes-7.0.1/.github/workflows/000077500000000000000000000000001472335743500173315ustar00rootroot00000000000000django-axes-7.0.1/.github/workflows/codeql.yml000066400000000000000000000026211472335743500213240ustar00rootroot00000000000000name: "Code Scanning - Action" on: pull_request: jobs: CodeQL-Build: # CodeQL runs on ubuntu-latest, windows-latest, and macos-latest runs-on: ubuntu-latest permissions: # required for all workflows security-events: write steps: - name: Checkout repository uses: actions/checkout@v4 # Initializes the CodeQL tools for scanning. - name: Initialize CodeQL uses: github/codeql-action/init@v3 # Override language selection by uncommenting this and choosing your languages # with: # languages: go, javascript, csharp, python, cpp, java # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). # If this step fails, then you should remove it and run the build manually (see below). - name: Autobuild uses: github/codeql-action/autobuild@v3 # ℹ️ Command-line programs to run using the OS shell. # 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun # ✏️ If the Autobuild fails above, remove it and uncomment the following # three lines and modify them (or add more) to build your code if your # project uses a compiled language #- run: | # make bootstrap # make release - name: Perform CodeQL Analysis uses: github/codeql-action/analyze@v3 django-axes-7.0.1/.github/workflows/release.yml000066400000000000000000000020051472335743500214710ustar00rootroot00000000000000name: Release on: push: tags: - '*' permissions: contents: read jobs: build: if: github.repository == 'jazzband/django-axes' runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 with: fetch-depth: 0 - name: Set up Python uses: actions/setup-python@v5 with: python-version: 3.9 - name: Install dependencies run: | python -m pip install -U pip python -m pip install -U setuptools twine wheel - name: Build package run: | python setup.py --version python setup.py sdist --format=gztar bdist_wheel twine check dist/* - name: Upload packages to Jazzband if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags') uses: pypa/gh-action-pypi-publish@release/v1 with: user: jazzband password: ${{ secrets.JAZZBAND_RELEASE_KEY }} repository-url: https://jazzband.co/projects/django-axes/upload django-axes-7.0.1/.github/workflows/test.yml000066400000000000000000000034251472335743500210370ustar00rootroot00000000000000name: Test on: [push, pull_request] permissions: contents: read jobs: build: name: build (Python ${{ matrix.python-version }}, Django ${{ matrix.django-version }}) runs-on: ubuntu-latest strategy: fail-fast: false matrix: python-version: ['3.9', '3.10', '3.11', '3.12', '3.13'] django-version: ['4.2', '5.0', '5.1'] include: # Tox configuration for QA environment - python-version: '3.13' django-version: 'qa' # Django main - python-version: '3.13' django-version: 'main' experimental: true exclude: - python-version: '3.9' django-version: '5.0' - python-version: '3.13' django-version: '5.0' - python-version: '3.9' django-version: '5.1' steps: - uses: actions/checkout@v4 - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v5 with: python-version: ${{ matrix.python-version }} - name: Get pip cache dir id: pip-cache run: | echo "::set-output name=dir::$(pip cache dir)" - name: Cache uses: actions/cache@v4 with: path: ${{ steps.pip-cache.outputs.dir }} key: ${{ matrix.python-version }}-v1-${{ hashFiles('**/setup.py') }} restore-keys: | ${{ matrix.python-version }}-v1- - name: Install dependencies run: | python -m pip install --upgrade pip python -m pip install --upgrade tox tox-gh-actions - name: Tox tests run: | tox -v env: DJANGO: ${{ matrix.django-version }} - name: Upload coverage uses: codecov/codecov-action@v3 with: name: Python ${{ matrix.python-version }} django-axes-7.0.1/.gitignore000066400000000000000000000003501472335743500157220ustar00rootroot00000000000000*.egg-info *.pyc *.swp .coverage coverage.xml .DS_Store .idea .mypy_cache/ .project .pydevproject .python-version .tox build/ dist/ docs/_build test.db .eggs pip-wheel-metadata .vscode/ .env .venv env/ venv/ ENV/ env.bak/ venv.bak/ django-axes-7.0.1/.pre-commit-config.yaml000066400000000000000000000000121472335743500202060ustar00rootroot00000000000000repos: [] django-axes-7.0.1/.prospector.yaml000066400000000000000000000002561472335743500171010ustar00rootroot00000000000000ignore-paths: - docs - axes/migrations pycodestyle: options: max-line-length: 142 pylint: disable: - django-not-configured pyflakes: disable: - F401 django-axes-7.0.1/.readthedocs.yaml000066400000000000000000000004761472335743500171720ustar00rootroot00000000000000# Read the Docs configuration file for Sphinx projects # See https://docs.readthedocs.io/en/stable/config-file/v2.html for details version: 2 build: os: ubuntu-22.04 tools: python: "3.11" sphinx: configuration: docs/conf.py formats: - pdf - epub python: install: - requirements: requirements.txt django-axes-7.0.1/CHANGES.rst000066400000000000000000001042621472335743500155430ustar00rootroot00000000000000 Changes ======= 7.0.1 (2024-12-02) ------------------ - Add Python 3.13 support. [aleksihakli] - Deprecate Python 3.8 support. [aleksihakli] 7.0.0 (2024-10-02) ------------------ - Add support for dynamic cooloff time calculation from request. This is a breaking change. Please see `version 7 upgrade notes in the documentation `_. [browniebroke] 6.5.2 (2024-09-21) ------------------ - Add test matrix support for Django 5.1. - Drop support for EOL Django 3.2. - Drop support for PyPy 3.10. 6.5.1 (2024-07-01) ------------------ - Make 0007_alter_accessattempt_unique_together.py migration backwards compatible. [hirotasoshu] 6.5.0 (2024-06-11) ------------------ - Add session hash to access log. [sevdog] 6.4.0 (2024-03-04) ------------------ - Add support for Python 3.12 and Django 5.0, drop support for Django 4.1. [aleksihakli] 6.3.1 (2024-03-04) ------------------ - Drop ``setuptools`` and ``pkg_resources`` dependencies. [Viicos] 6.3.0 (2023-12-27) ------------------ - Add async support to middleware. [Taikono-Himazin] 6.2.0 (2023-12-08) ------------------ - Update documentation. [funkybob] - Add new management command ``axes_reset_ip_username``. [p-l-] - Add French translations. [laulaz] - Avoid running data migration on incorrect databases. [christianbundy] 6.1.1 (2023-08-01) ------------------ - Fix ``TransactionManagementError`` when using the database handler with a custom database with for ``AccessAttempt`` or ``AccessFailureLog``. [hirotasoshu] 6.1.0 (2023-07-30) ------------------ - Set ``AXES_SENSITIVE_PARAMETERS`` default value to ``["username", "ip_address"]`` in addition to the ``AXES_PASSWORD_FORM_FIELD`` configuration flag. This masks the username and IP address fields by default in the logs when writing information about login attempts to the application logs. Reverting to old configuration default of ``[]`` can be done by setting ``AXES_SENSITIVE_PARAMETERS = []`` in the Django project settings file. [GitRon] - Improve documentation on GDPR and privacy notes and configuration flags. [GitRon] 6.0.5 (2023-07-01) ------------------ - Add Indonesion translation. [kiraware] 6.0.4 (2023-06-22) ------------------ - Remove unused methods from AxesStandaloneBackend. [314eter] 6.0.3 (2023-06-18) ------------------ - Add username to admin fieldsets. [sevdog] 6.0.2 (2023-06-13) ------------------ - Add Django system checks for validating callable import path settings. [iafisher] - Improve documentation. [hirotasoshu] - Improve repository issue and PR templates. [hirotasoshu] 6.0.1 (2023-05-17) ------------------ - Fine-tune CI pipelines and RTD build requirements. [aleksihakli] 6.0.0 (2023-05-17) ------------------ Version 6 is a breaking release. Please see the documentation for upgrade instructions. - Deprecate Python 3.7 support. [aleksihakli] - Deprecate ``is_admin_site`` API call with misleading naming. [hirotasoshu] - Add ``AXES_LOCKOUT_PARAMETERS`` configuration flag that will supersede ``AXES_ONLY_USER_FAILURES``, ``AXES_LOCK_OUT_BY_COMBINATION_USER_AND_IP``, ``AXES_LOCK_OUT_BY_USER_OR_IP``, and ``AXES_USE_USER_AGENT`` configurations. Add deprecation warnings for old flags. See project documentation on RTD for update instructions. [hirotasoshu] - Improve translations. [hirotasoshu] - Use Django ``cache.incr`` API for atomic cached failure counting [hirotasoshu, aleksihakli] - Make ``django-ipware`` an optional dependency. Install it with e.g. ``pip install django-axes[ipware]`` package and extras specifier. [aleksihakli] - Deprecate and rename old configuration flags. Old flags will be removed in or after version ``6.1``. [aleksihakli] * ``AXES_PROXY_ORDER`` is now ``AXES_IPWARE_PROXY_ORDER``, * ``AXES_PROXY_COUNT`` is now ``AXES_IPWARE_PROXY_COUNT``, * ``AXES_PROXY_TRUSTED_IPS`` is now ``AXES_IPWARE_PROXY_TRUSTED_IPS``, and * ``AXES_META_PRECEDENCE_ORDER`` is now ``AXES_IPWARE_META_PRECEDENCE_ORDER``. - Set 429 as the default lockout response code. [hirotasoshu] 5.41.1 (2023-04-16) ------------------- - Fix sensitive parameter logging for database handler. [stereodamage] 5.41.0 (2023-04-02) ------------------- - Fix tests. [hirotasoshu] - Add ``AXES_CLIENT_CALLABLE`` setting. [hirotasoshu] - Update Python, Django, and package versions. [hramezani] 5.40.1 (2022-11-24) ------------------- - Fix bug in user agent request blocking. [PetrDlouhy] 5.40.0 (2022-11-19) ------------------- - Update packages and linters for new version support. [hramezani] - Update documentation links. [Arhell] - Use importlib instead of setuptools for Python 3.8+. [jedie] - Python 3.11 support. [joshuadavidthomas] - Documentation improvements. [nsht] - Documentation improvements. [timgates42] 5.39.0 (2022-08-18) ------------------- - Utilize new backend class in tests to fix false negative system check warnings. [simonkern] 5.38.0 (2022-08-16) ------------------- - Adjust changelog so release notes are correctly visible on PyPy and released package. [aleksihakli] 5.37.0 (2022-08-16) ------------------- - Add Django 4.1 support. PyPy 3.8 has a known issue with Django 4.1 and is exempted. [hramezani] 5.36.0 (2022-07-17) ------------------- - Add ``AxesStandaloneBackend`` without ``ModelBackend`` dependencies. [jcgiuffrida] 5.35.0 (2022-06-01) ------------------- - Add Arabic translations. [YDA93] 5.34.0 (2022-05-28) ------------------- - Improve German translations. [GitRon] 5.33.0 (2022-05-16) ------------------- - Migrate MD5 cache key digests to SHA256. [aleksihakli] - Improve and streamline startup logging. [ShaheedHaque] - Improve module typing. [hramezani] - Add support for float or partial hours for ``AXES_COOLOFF_TIME``. [hramezani] 5.32.0 (2022-04-08) ------------------- - Add support for persistent failure logging where failed login attempts are persisted in the database until a specific threshold is reached. [p1-gdd] - Add support for not resetting login times when users try to login during the lockout cooloff period. [antoine-42] 5.31.0 (2022-01-08) ------------------- - Adjust version specifiers for newer Python and other package versions. Set package minimum Python version to 3.7. Relax ``django-ipware`` version requirements to allow newer versions. [aleksihakli] 5.30.0 (2022-01-08) ------------------- - Fix package build error in 5.29.0 to allow publishing. [aleksihakli] 5.29.0 (2022-01-08) ------------------- - Drop Python 3.6 support. [aleksihakli] 5.28.0 (2021-12-14) ------------------- - Drop Django < 3.2 support. [hramezani] - Add Django 4.0 to test matrix. [hramezani] 5.27.0 (2021-11-04) ------------------- - Fix ``pkg_resources`` missing for package version resolution on runtime due to ``setuptools`` not being a runtime dependency. [asherf] - Add Python 3.10 and Django 3.2 support. [hramezani] 5.26.0 (2021-10-11) ------------------- - Fix ``AXES_USERNAME_CALLABLE`` not receiving ``credentials`` attribute in Axes middleware lockout response when user is locked out. [rootart] 5.25.0 (2021-09-19) ------------------- - Fix duplicated AccessAttempts with updated database model ``unique_together`` constraints and data and schema migration. [PetrDlouhy] 5.24.0 (2021-09-09) ------------------- - Use atomic transaction for updating AccessAttempts in database handler. [okapies] 5.23.0 (2021-09-02) ------------------- - Pass ``request`` as argument to ``AXES_CLIENT_STR_CALLABLE``. [sarahboyce] 5.22.0 (2021-08-31) ------------------- - Improve ``failures_since_start`` handling by moving the counter incrementation from non-atomic Python code call to atomic database function. [okapies] - Add publicly available ``request.axes_failures_since_start`` attribute. [okapies] 5.21.0 (2021-08-19) ------------------- - Add configurable lockout HTTP status code responses with the new ``AXES_HTTP_RESPONSE_CODE`` setting. [phil-bell] 5.20.0 (2021-06-29) ------------------- - Improve race condition handling in e.g. multi-process environments by using ``get_or_create`` for access attempt fetching and updates. [uli-klank] 5.19.0 (2021-06-16) ------------------- - Add Polish locale. [Quadric] 5.18.0 (2021-06-09) ------------------- - Fix ``default_auto_field`` warning. [zkanda] 5.17.0 (2021-06-05) ------------------- - Fix ``default_app_config`` deprecation. Django 3.2 automatically detects ``AppConfig`` and therefore this setting is no longer required. [nikolaik] 5.16.0 (2021-05-19) ------------------- - Add ``AXES_CLIENT_STR_CALLABLE`` setting. [smtydn] 5.15.0 (2021-05-03) ------------------- - Add option to cleanse sensitive GET and POST params in database handler with the ``AXES_SENSITIVE_PARAMETERS`` setting. [mcoconnor] 5.14.0 (2021-04-06) ------------------- - Improve message formatting for lockout message and translations. [ashokdelphia] - Remove support for Django 3.0. [hramezani] - Add support for Django 3.2. [hramezani] 5.13.1 (2021-02-22) ------------------- - Default ``AXES_VERBOSE`` to ``AXES_ENABLED`` configuration setting, disabling verbose startup logging when Axes itself is disabled. [christianbundy] - Update documentation. [KStenK] 5.13.0 (2021-02-15) ------------------- - Add support for resetting attempts with cache backend. [nattyg93] 5.12.0 (2021-01-07) ------------------- - Clean up test structure and migrate tests outside the main package for a smaller wheel distributions. [aleksihakli] - Move configuration to pyproject.toml for cleaner layout. [aleksihakli] - Clean up test settings override configuration. [hramezani] 5.11.1 (2021-01-06) ------------------- - Fix cache entry creations for None username. [cabarnes] 5.11.0 (2021-01-05) ------------------- - Add lockout view CORS support with ``AXES_ALLOWED_CORS_ORIGINS`` configuration flag. [vladox] - Add missing ``@wraps`` decorator to ``axes.decorators.axes_dispatch``. [aleksihakli] 5.10.1 (2021-01-04) ------------------- - Add ``DEFAULT_AUTO_FIELD`` to test settings. [hramezani] - Fix documentation language. [danielquinn] - Fix Python package version specifiers and remove redundant imports. [aleksihakli] 5.10.0 (2020-12-18) ------------------- - Deprecate stock DRF support from 5.8.0, require users to set it up per project. Check the documentation for more information. [aleksihakli] 5.9.1 (2020-12-02) ------------------ - Move tests to GitHub Actions [jezdez] - Fix running Axes code in middleware when ``AXES_ENABLED`` is ``False``. [ashokdelphia] 5.9.0 (2020-11-05) ------------------ - Add Python 3.9 support. [hramezani] - Prevent ``AccessAttempt`` creation with database handler when username is not set and ``AXES_ONLY_USER_FAILURES`` setting is not set. [hramezani] 5.8.0 (2020-10-16) ------------------ - Improve Django REST Framework (DRF) integration. [Anatoly] 5.7.1 (2020-09-27) ------------------ - Adjust settings import and handling chain for cleaner module import and invocation order. [aleksihakli] - Adjust the use of ``AXES_ENABLED`` flag so that imports are always done the same way and initial log is written regardless of the setting and it only affects code that is decorated or wrapped with ``toggleable``. [alekshakli] 5.7.0 (2020-09-26) ------------------ - Deprecate ``AXES_LOGGER`` Axes setting and move to ``__name__`` based logging and fully qualified Python module name log identifiers. [aleksihakli] 5.6.2 (2020-09-20) ------------------ - Fix regression in ``axes_reset_user`` management command. [aleksihakli] 5.6.1 (2020-09-17) ------------------ - Improve test dependency management and upgrade black code formatter. [smithdc1] 5.6.0 (2020-09-12) ------------------ - Add proper development ``subTest`` support via ``pytest-subtests`` package. [smithdc1] - Deprecate ``django-appconf`` and use plain settings for Axes. [aleksihakli] 5.5.2 (2020-09-11) ------------------ - Update deprecating use of the ``request.is_ajax`` method. [smithdc1] 5.5.1 (2020-09-10) ------------------ - Update deprecated uses of Django modules and members. [smithdc1] 5.5.0 (2020-08-21) ------------------ - Add support for locking requests based on username OR IP address with inclusive or using the ``LOCK_OUT_BY_USER_OR_IP`` flag. [PetrDlouhy] - Deprecate Signal ``providing_args`` for Django 3.1 support. [coredumperror] 5.4.3 (2020-08-06) ------------------ - Add Django 3.1 support. [hramezani] 5.4.2 (2020-07-28) ------------------ - Add ABC or abstract base class implementation for handlers. [jorlugaqui] 5.4.1 (2020-07-03) ------------------ - Fix code styling for linters. [aleksihakli] 5.4.0 (2020-07-03) ------------------ - Propagate username to lockout view in URL parameters. [PetrDlouhy] - Update CAPTCHA examples. [PetrDlouhy] - Upgrade django-ipware to version 3. [hramezani,mnislam01] 5.3.5 (2020-07-02) ------------------ - Restrict ipware version for version compatibility. [aleksihakli] 5.3.4 (2020-06-09) ------------------ - Deprecate Django 1.11 LTS support. [aleksihakli] 5.3.3 (2020-05-22) ------------------ - Fix ``AXES_ONLY_ADMIN_SITE`` functionality when no default admin site is defined in the URL configuration. [igor-shevchenko] 5.3.2 (2020-05-15) ------------------ - Fix AppConf settings prefix for Fargate. [marksweb] 5.3.1 (2020-03-23) ------------------ - Fix null byte ValueError bug in ORM. [ddimmich] 5.3.0 (2020-03-10) ------------------ - Improve Django REST Framework compatibility. [I0x4dI] 5.2.2 (2020-01-08) ------------------ - Add missing proxy implementation for ``axes.handlers.proxy.AxesProxyHandler.get_failures``. [aleksihakli] 5.2.1 (2020-01-08) ------------------ - Add django-reversion compatibility notes. [mark-mishyn] - Add pluggable lockout responses and the ``AXES_LOCKOUT_CALLABLE`` configuration flag. [aleksihakli] 5.2.0 (2020-01-01) ------------------ - Add a test handler. [aidanlister] 5.1.0 (2019-12-29) ------------------ - Add pluggable user account whitelisting and the ``AXES_WHITELIST_CALLABLE`` configuration flag. [aleksihakli] 5.0.20 (2019-12-01) ------------------- - Fix django-allauth compatibility issue. [hramezani] - Improve tests for login attempt monitoring. [hramezani] - Add reverse proxy documentation. [ckcollab] - Update OAuth documentation examples. [aleksihakli] 5.0.19 (2019-11-06) ------------------- - Optimize access attempt fetching in database handler. [hramezani] - Optimize request data fetching in proxy handler. [hramezani] 5.0.18 (2019-10-17) ------------------- - Add ``cooloff_timedelta`` context variable to lockout responses. [jstockwin] 5.0.17 (2019-10-15) ------------------- - Safer string formatting for user input. [aleksihakli] 5.0.16 (2019-10-15) ------------------- - Fix string formatting bug in logging. [zerolab] 5.0.15 (2019-10-09) ------------------- - Add ``AXES_ENABLE_ADMIN`` flag. [flannelhead] 5.0.14 (2019-09-28) ------------------- - Docs, CI pipeline, and code formatting improvements [aleksihakli] 5.0.13 (2019-08-30) ------------------- - Python 3.8 and PyPy support. [aleksihakli] - Migrate to ``setuptools_scm`` and automatic versioning. [aleksihakli] 5.0.12 (2019-08-05) ------------------- - Support callables for ``AXES_COOLOFF_TIME`` setting. [DariaPlotnikova] 5.0.11 (2019-07-25) ------------------- - Fix typo in rST formatting that prevented 5.0.10 release to PyPI. [aleksihakli] 5.0.10 (2019-07-25) ------------------- - Refactor type checks for ``axes.helpers.get_client_cache_key`` for framework compatibility, fixes #471. [aleksihakli] 5.0.9 (2019-07-11) ------------------ - Add better handling for attempt and log resets by moving them into handlers which allows customization and more configurability. Unimplemented handlers raise ``NotImplementedError`` by default. [aleksihakli] - Add Python 3.8 dev version and PyPy to the Travis test matrix. [aleksihakli] 5.0.8 (2019-07-09) ------------------ - Add ``AXES_ONLY_ADMIN_SITE`` flag for only running Axes on admin site. [hramezani] - Add ``axes_reset_logs`` command for removing old AccessLog records. [tlebrize] - Allow ``AxesBackend`` subclasses to pass the ``axes.W003`` system check. [adamchainz] 5.0.7 (2019-06-14) ------------------ - Fix lockout message showing when lockout is disabled with the ``AXES_LOCK_OUT_AT_FAILURE`` setting. [mogzol] - Add support for callable ``AXES_FAILURE_LIMIT`` setting. [bbayles] 5.0.6 (2019-05-25) ------------------ - Deprecate ``AXES_DISABLE_SUCCESS_ACCESS_LOG`` flag in favour of ``AXES_DISABLE_ACCESS_LOG`` which has mostly the same functionality. Update documentation to better reflect the behaviour of the flag. [aleksihakli] 5.0.5 (2019-05-19) ------------------ - Change the lockout response calculation to request flagging instead of exception throwing in the signal handler and middleware. Move request attribute calculation from middleware to handler layer. Deprecate ``axes.request.AxesHttpRequest`` object type definition. [aleksihakli] - Deprecate the old version 4.x ``axes.backends.AxesModelBackend`` class. [aleksihakli] - Improve documentation on attempt tracking, resets, Axes customization, project and component compatibility and integrations, and other things. [aleksihakli] 5.0.4 (2019-05-09) ------------------ - Fix regression with OAuth2 authentication backends not having remote IP addresses set and throwing an exception in cache key calculation. [aleksihakli] 5.0.3 (2019-05-08) ------------------ - Fix ``django.contrib.auth`` module ``login`` and ``logout`` functionality so that they work with the handlers without the an ``AxesHttpRequest`` to improve cross compatibility with other Django applications. [aleksihakli] - Change IP address resolution to allow empty or missing addresses. [aleksihakli] - Add error logging for missing request attributes in the handler layer so that users get better indicators of misconfigured applications. [aleksihakli] 5.0.2 (2019-05-07) ------------------ - Add ``AXES_ENABLED`` setting for disabling Axes with e.g. tests that use Django test client ``login``, ``logout``, and ``force_login`` methods, which do not supply the ``request`` argument to views, preventing Axes from functioning correctly in certain test setups. [aleksihakli] 5.0.1 (2019-05-03) ------------------ - Add changelog to documentation. [aleksihakli] 5.0 (2019-05-01) ---------------- - Deprecate Python 2.7, 3.4 and 3.5 support. [aleksihakli] - Remove automatic decoration and monkey-patching of Django views and forms. Decorators are available for login function and method decoration as before. [aleksihakli] - Use backend, middleware, and signal handlers for tracking login attempts and implementing user lockouts. [aleksihakli, jorlugaqui, joshua-s] - Add ``AxesDatabaseHandler``, ``AxesCacheHandler``, and ``AxesDummyHandler`` handler backends for processing user login and logout events and failures. Handlers are configurable with the ``AXES_HANDLER`` setting. [aleksihakli, jorlugaqui, joshua-s] - Improve management commands and separate commands for resetting all access attempts, attempts by IP, and attempts by username. New command names are ``axes_reset``, ``axes_reset_ip`` and ``axes_reset_username``. [aleksihakli] - Add support for string import for ``AXES_USERNAME_CALLABLE`` that supports dotted paths in addition to the old callable type such as a function or a class method. [aleksihakli] - Deprecate one argument call signature for ``AXES_USERNAME_CALLABLE``. From now on, the callable needs to accept two arguments, the HttpRequest and credentials that are supplied to the Django ``authenticate`` method in authentication backends. [aleksihakli] - Move ``axes.attempts.is_already_locked`` function to ``axes.handlers.AxesProxyHandler.is_locked``. Various other previously undocumented methods have been deprecated and moved inside the project. The new documented public APIs can be considered as stable and can be safely utilized by other projects. [aleksihakli] - Improve documentation layouting and contents. Add public API reference section. [aleksihakli] 4.5.4 (2019-01-15) ------------------ - Improve README and documentation [aleksihakli] 4.5.3 (2019-01-14) ------------------ - Remove the unused ``AccessAttempt.trusted`` flag from models [aleksihakli] - Improve README and Travis CI setups [aleksihakli] 4.5.2 (2019-01-12) ------------------ - Added Turkish translations [obayhan] 4.5.1 (2019-01-11) ------------------ - Removed duplicated check that was causing issues when using APIs. [camilonova] - Added Russian translations [lubicz-sielski] 4.5.0 (2018-12-25) ------------------ - Improve support for custom authentication credentials using the ``AXES_USERNAME_FORM_FIELD`` and ``AXES_USERNAME_CALLABLE`` settings. [mastacheata] - Updated behaviour for fetching username from request or credentials: If no ``AXES_USERNAME_CALLABLE`` is configured, the optional ``credentials`` that are supplied to the axes utility methods are now the default source for client username and the HTTP request POST is the fallback for fetching the user information. ``AXES_USERNAME_CALLABLE`` implements an alternative signature with two arguments ``request, credentials`` in addition to the old ``request`` call argument signature in a backwards compatible fashion. [aleksihakli] - Add official support for the Django 2.1 version and Python 3.7. [aleksihakli] - Improve the requirements, documentation, tests, and CI setup. [aleksihakli] 4.4.3 (2018-12-08) ------------------ - Fix MANIFEST.in missing German translations [aleksihakli] - Add `AXES_RESET_ON_SUCCESS` configuration flag [arjenzijlstra] 4.4.2 (2018-10-30) ------------------ - fix missing migration and add check to prevent it happening again. [markddavidoff] 4.4.1 (2018-10-24) ------------------ - Add a German translation [adonig] - Documentation wording changes [markddavidoff] - Use `get_client_username` in `log_user_login_failed` instead of credentials [markddavidoff] - pin prospector to 0.12.11, and pin astroid to 1.6.5 [hsiaoyi0504] 4.4.0 (2018-05-26) ------------------ - Added AXES_USERNAME_CALLABLE [jaadus] 4.3.1 (2018-04-21) ------------------ - Change custom authentication backend failures from error to warning log level [aleksihakli] - Set up strict code linting for CI pipeline that fails builds if linting does not pass [aleksihakli] - Clean up old code base and tests based on linter errors [aleksihakli] 4.3.0 (2018-04-21) ------------------ - Refactor and clean up code layout [aleksihakli] - Add prospector linting and code checks to toolchain [aleksihakli] - Clean up log message formatting and refactor type checks [EvaSDK] - Fix faulty user locking with user agent when AXES_ONLY_USER_FAILURES is set [EvaSDK] 4.2.1 (2018-04-18) ------------------ - Fix unicode string interpolation on Python 2.7 [aleksihakli] 4.2.0 (2018-04-13) ------------------ - Add configuration flags for client IP resolving [aleksihakli] - Add AxesModelBackend authentication backend [markdaviddoff] 4.1.0 (2018-02-18) ------------------ - Add AXES_CACHE setting for configuring `axes` specific caching. [JWvDronkelaar] - Add checks and tests for faulty LocMemCache usage in application setup. [aleksihakli] 4.0.2 (2018-01-19) ------------------ - Improve Windows compatibility on Python < 3.4 by utilizing win_inet_pton [hsiaoyi0504] - Add documentation on django-allauth integration [grucha] - Add documentation on known AccessAttempt caching configuration problems when using axes with the `django.core.cache.backends.locmem.LocMemCache` [aleksihakli] - Refactor and improve existing AccessAttempt cache reset utility [aleksihakli] 4.0.1 (2017-12-19) ------------------ - Fixes issue when not using `AXES_USERNAME_FORM_FIELD` [camilonova] 4.0.0 (2017-12-18) ------------------ - *BREAKING CHANGES*. `AXES_BEHIND_REVERSE_PROXY` `AXES_REVERSE_PROXY_HEADER` `AXES_NUM_PROXIES` were removed in order to use `django-ipware` to get the user ip address [camilonova] - Added support for custom username field [kakulukia] - Customizing Axes doc updated [pckapps] - Remove filtering by username [camilonova] - Fixed logging failed attempts to authenticate using a custom authentication backend. [D3X] 3.0.3 (2017-11-23) ------------------ - Test against Python 2.7. [mbaechtold] - Test against Python 3.4. [pope1ni] 3.0.2 (2017-11-21) ------------------ - Added form_invalid decorator. Fixes #265 [camilonova] 3.0.1 (2017-11-17) ------------------ - Fix DeprecationWarning for logger warning [richardowen] - Fixes global lockout possibility [joeribekker] - Changed the way output is handled in the management commands [ataylor32] 3.0.0 (2017-11-17) ------------------ - BREAKING CHANGES. Support for Django >= 1.11 and signals, see issue #215. Drop support for Python < 3.6 [camilonova] 2.3.3 (2017-07-20) ------------------ - Many tweaks and handles successful AJAX logins. [Jack Sullivan] - Add tests for proxy number parametrization [aleksihakli] - Add AXES_NUM_PROXIES setting [aleksihakli] - Log failed access attempts regardless of settings [jimr] - Updated configuration docs to include AXES_IP_WHITELIST [Minkey27] - Add test for get_cache_key function [jorlugaqui] - Delete cache key in reset command line [jorlugaqui] - Add signals for setting/deleting cache keys [jorlugaqui] 2.3.2 (2016-11-24) ------------------ - Only look for lockable users on a POST [schinckel] - Fix and add tests for IPv4 and IPv6 parsing [aleksihakli] 2.3.1 (2016-11-12) ------------------ - Added settings for disabling success accesslogs [Minkey27] - Fixed illegal IP address string passed to inet_pton [samkuehn] 2.3.0 (2016-11-04) ------------------ - Fixed ``axes_reset`` management command to skip "ip" prefix to command arguments. [EvaMarques] - Added ``axes_reset_user`` management command to reset lockouts and failed login records for given users. [vladimirnani] - Fixed Travis-PyPI release configuration. [jezdez] - Make IP position argument optional. [aredalen] - Added possibility to disable access log [svenhertle] - Fix for IIS used as reverse proxy adding port number [Dmitri-Sintsov] - Made the signal race condition safe. [Minkey27] - Added AXES_ONLY_USER_FAILURES to support only looking at the user ID. [lip77us] 2.2.0 (2016-07-20) ------------------ - Improve the logic when using a reverse proxy to avoid possible attacks. [camilonova] 2.1.0 (2016-07-14) ------------------ - Add `default_app_config` so you can just use `axes` in `INSTALLED_APPS` [vdboor] 2.0.0 (2016-06-24) ------------------ - Removed middleware to use app_config [camilonova] - Lots of cleaning [camilonova] - Improved test suite and versions [camilonova] 1.7.0 (2016-06-10) ------------------ - Use render shortcut for rendering LOCKOUT_TEMPLATE [Radoslaw Luter] - Added app_label for RemovedInDjango19Warning [yograterol] - Add iso8601 translator. [mullakhmetov] - Edit json response. Context now contains ISO 8601 formatted cooloff time [mullakhmetov] - Add json response and iso8601 tests. [mullakhmetov] - Fixes issue 162: UnicodeDecodeError on pip install [joeribekker] - Added AXES_NEVER_LOCKOUT_WHITELIST option to prevent certain IPs from being locked out. [joeribekker] 1.6.1 (2016-05-13) ------------------ - Fixes whitelist check when BEHIND_REVERSE_PROXY [Patrick Hagemeister] - Made migrations py3 compatible [mvdwaeter] - Fixing #126, possibly breaking compatibility with Django<=1.7 [int-ua] - Add note for upgrading users about new migration files [kelseyq] - Fixes #148 [camilonova] - Decorate auth_views.login only once [teeberg] - Set IP public/private classifier to be compliant with RFC 1918. [SilasX] - Issue #155. Lockout response status code changed to 403. [Arthur Mullahmetov] - BUGFIX: Missing migration [smeinel] 1.6.0 (2016-01-07) ------------------ - Stopped using render_to_response so that other template engines work [tarkatronic] - Improved performance & DoS prevention on query2str [tarkatronic] - Immediately return from is_already_locked if the user is not lockable [jdunck] - Iterate over ip addresses only once [annp89] - added initial migration files to support django 1.7 &up. Upgrading users should run migrate --fake-initial after update [ibaguio] - Add db indexes to CommonAccess model [Schweigi] 1.5.0 (2015-09-11) ------------------ - Fix #_get_user_attempts to include username when filtering AccessAttempts if AXES_LOCK_OUT_BY_COMBINATION_USER_AND_IP is True [afioca] 1.4.0 (2015-08-09) ------------------ - Send the user_locked_out signal. Fixes #94. [toabi] 1.3.9 (2015-02-11) ------------------ - Python 3 fix (#104) 1.3.8 (2014-10-07) ------------------ - Rename GitHub organization from django-security to django-pci to emphasize focus on providing assistance with building PCI compliant websites with Django. [aclark4life] 1.3.7 (2014-10-05) ------------------ - Explain common issues where Axes fails silently [cericoda] - Allow for user-defined username field for lookup in POST data [SteveByerly] - Log out only if user was logged in [zoten] - Support for floats in cooloff time (i.e: 0.1 == 6 minutes) [marianov] - Limit amount of POST data logged (#73). Limiting the length of value is not enough, as there could be arbitrary number of them, or very long key names. [peterkuma] - Improve get_ip to try for real ip address [7wonders] - Change IPAddressField to GenericIPAddressField. When using a PostgreSQL database and the client does not pass an IP address you get an inet error. This is a known problem with PostgreSQL and the IPAddressField. https://code.djangoproject.com/ticket/5622. It can be fixed by using a GenericIPAddressField instead. [polvoblanco] - Get first X-Forwarded-For IP [tutumcloud] - White listing IP addresses behind reverse proxy. Allowing some IP addresses to have direct access to the app even if they are behind a reverse proxy. Those IP addresses must still be on a white list. [ericbulloch] - Reduce logging of reverse proxy IP lookup and use configured logger. Fixes #76. Instead of logging the notice that django.axes looks for a HTTP header set by a reverse proxy on each attempt, just log it one-time on first module import. Also use the configured logger (by default axes.watch_login) for the message to be more consistent in logging. [eht16] - Limit the length of the values logged into the database. Refs #73 [camilonova] - Refactored tests to be more stable and faster [camilonova] - Clean client references [camilonova] - Fixed admin login url [camilonova] - Added django 1.7 for testing [camilonova] - Travis file cleanup [camilonova] - Remove hardcoded url path [camilonova] - Fixing tests for django 1.7 [Andrew-Crosio] - Fix for django 1.7 exception not existing [Andrew-Crosio] - Removed python 2.6 from testing [camilonova] - Use django built-in six version [camilonova] - Added six as requirement [camilonova] - Added python 2.6 for travis testing [camilonova] - Replaced u string literal prefixes with six.u() calls [amrhassan] - Fixes object type issue, response is not an string [camilonova] - Python 3 compatibility fix for db_reset [nicois] - Added example project and helper scripts [barseghyanartur] - Admin command to list login attemps [marianov] - Replaced six imports with django.utils.six ones [amrhassan] - Replaced u string literal prefixes with six.u() calls to make it compatible with Python 3.2 [amrhassan] - Replaced `assertIn`s and `assertNotIn`s with `assertContains` and `assertNotContains` [fcurella] - Added py3k to travis [fcurella] - Update test cases to be python3 compatible [nicois] - Python 3 compatibility fix for db_reset [nicois] - Removed trash from example urls [barseghyanartur] - Added django installer [barseghyanartur] - Added example project and helper scripts [barseghyanartur] 1.3.6 (2013-11-23) ------------------ - Added AttributeError in case get_profile doesn't exist [camilonova] - Improved axes_reset command [camilonova] 1.3.5 (2013-11-01) ------------------ - Fix an issue with __version__ loading the wrong version [graingert] 1.3.4 (2013-11-01) ------------------ - Update README.rst for PyPI [marty, camilonova, graingert] - Add cooloff period [visualspace] 1.3.3 (2013-07-05) ------------------ - Added 'username' field to the Admin table [bkvirendra] - Removed fallback logging creation since logging cames by default on django 1.4 or later, if you don't have it is because you explicitly wanted. Fixes #45 [camilonova] 1.3.2 (2013-03-28) ------------------ - Fix an issue when a user logout [camilonova] - Match pypi version [camilonova] - Better User model import method [camilonova] - Use only one place to get the version number [camilonova] - Fixed an issue when a user on django 1.4 logout [camilonova] - Handle exception if there is not user profile model set [camilonova] - Made some cleanup and remove a pokemon exception handling [camilonova] - Improved tests so it really looks for the rabbit in the hole [camilonova] - Match pypi version [camilonova] 1.3.1 (2013-03-19) ------------------ - Add support for Django 1.5 [camilonova] 1.3.0 (2013-02-27) ------------------ - Bug fix: get_version() format string [csghormley] 1.2.9 (2013-02-20) ------------------ - Add to and improve test cases [camilonova] 1.2.8 (2013-01-23) ------------------ - Increased http accept header length [jslatts] 1.2.7 (2013-01-17) ------------------ - Reverse proxy support [rmagee] - Clean up README [martey] 1.2.6 (2012-12-04) ------------------ - Remove unused import [aclark4life] 1.2.5 (2012-11-28) ------------------ - Fix setup.py [aclark4life] - Added ability to flag user accounts as unlockable. [kencochrane] - Added ipaddress as a param to the user_locked_out signal. [kencochrane] - Added a signal receiver for user_logged_out. [kencochrane] - Added a signal for when a user gets locked out. [kencochrane] - Added AccessLog model to log all access attempts. [kencochrane] django-axes-7.0.1/CODE_OF_CONDUCT.md000066400000000000000000000045071472335743500165410ustar00rootroot00000000000000# Code of Conduct As contributors and maintainers of the Jazzband projects, and in the interest of fostering an open and welcoming community, we pledge to respect all people who contribute through reporting issues, posting feature requests, updating documentation, submitting pull requests or patches, and other activities. We are committed to making participation in the Jazzband a harassment-free experience for everyone, regardless of the level of experience, gender, gender identity and expression, sexual orientation, disability, personal appearance, body size, race, ethnicity, age, religion, or nationality. Examples of unacceptable behavior by participants include: - The use of sexualized language or imagery - Personal attacks - Trolling or insulting/derogatory comments - Public or private harassment - Publishing other's private information, such as physical or electronic addresses, without explicit permission - Other unethical or unprofessional conduct The Jazzband roadies have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. By adopting this Code of Conduct, the roadies commit themselves to fairly and consistently applying these principles to every aspect of managing the jazzband projects. Roadies who do not follow or enforce the Code of Conduct may be permanently removed from the Jazzband roadies. This code of conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the roadies at `roadies@jazzband.co`. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. Roadies are obligated to maintain confidentiality with regard to the reporter of an incident. This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.3.0, available at [https://contributor-covenant.org/version/1/3/0/][version] [homepage]: https://contributor-covenant.org [version]: https://contributor-covenant.org/version/1/3/0/ django-axes-7.0.1/CONTRIBUTING.rst000066400000000000000000000044301472335743500163760ustar00rootroot00000000000000.. image:: https://jazzband.co/static/img/jazzband.svg :target: https://jazzband.co/ :alt: Jazzband This is a `Jazzband `_ project. By contributing you agree to abide by the `Contributor Code of Conduct `_ and follow the `guidelines `_. Contributions ============= All contributions are welcome! It is best to separate proposed changes and PRs into small, distinct patches by type so that they can be merged faster into upstream and released quicker. One way to organize contributions would be to separate PRs for e.g. * bugfixes, * new features, * code and design improvements, * documentation improvements, or * tooling and CI improvements. Merging contributions requires passing the checks configured with the CI. This includes running tests and linters successfully on the currently officially supported Python and Django versions. Development =========== You can contribute to this project forking it from GitHub and sending pull requests. First `fork `_ the `repository `_ and then clone it:: $ git clone git@github.com:/django-axes.git Initialize a virtual environment for development purposes:: $ mkdir -p ~/.virtualenvs $ python3 -m venv ~/.virtualenvs/django-axes $ source ~/.virtualenvs/django-axes/bin/activate Then install the necessary requirements:: $ cd django-axes $ pip install -r requirements.txt Unit tests are located in the ``axes/tests`` folder and can be easily run with the pytest tool:: $ pytest Prospector runs a number of source code style, safety, and complexity checks:: $ prospector Mypy runs static typing checks to verify the source code type annotations and correctness:: $ mypy . Before committing, you can run all the above tests against all supported Python and Django versions with tox:: $ tox Tox runs the same test set that is run by GitHub Actions, and your code should be good to go if it passes. If you wish to limit the testing to specific environment(s), you can parametrize the tox run:: $ tox -e py39-django32 After you have pushed your changes, open a pull request on GitHub for getting your code upstreamed. django-axes-7.0.1/LICENSE000066400000000000000000000022401472335743500147370ustar00rootroot00000000000000The MIT License Copyright (c) 2008 Josh VanderLinden Copyright (c) 2009 Philip Neustrom Copyright (c) 2016 Jazzband 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. django-axes-7.0.1/README.rst000066400000000000000000000047021472335743500154260ustar00rootroot00000000000000 django-axes =========== .. image:: https://jazzband.co/static/img/badge.svg :target: https://jazzband.co/ :alt: Jazzband .. image:: https://img.shields.io/github/stars/jazzband/django-axes.svg?label=Stars&style=socialcA :target: https://github.com/jazzband/django-axes :alt: GitHub .. image:: https://img.shields.io/pypi/v/django-axes.svg :target: https://pypi.org/project/django-axes/ :alt: PyPI release .. image:: https://img.shields.io/pypi/pyversions/django-axes.svg :target: https://pypi.org/project/django-axes/ :alt: Supported Python versions .. image:: https://img.shields.io/pypi/djversions/django-axes.svg :target: https://pypi.org/project/django-axes/ :alt: Supported Django versions .. image:: https://img.shields.io/readthedocs/django-axes.svg :target: https://django-axes.readthedocs.io/ :alt: Documentation .. image:: https://github.com/jazzband/django-axes/workflows/Test/badge.svg :target: https://github.com/jazzband/django-axes/actions :alt: GitHub Actions .. image:: https://codecov.io/gh/jazzband/django-axes/branch/master/graph/badge.svg :target: https://codecov.io/gh/jazzband/django-axes :alt: Coverage Axes is a Django plugin for keeping track of suspicious login attempts for your Django based website and implementing simple brute-force attack blocking. The name is sort of a geeky pun, since it can be interpreted as: * ``access``, as in monitoring access attempts, or * ``axes``, as in tools you can use to hack (generally on wood). Functionality ------------- Axes records login attempts to your Django powered site and prevents attackers from attempting further logins to your site when they exceed the configured attempt limit. Axes can track the attempts and persist them in the database indefinitely, or alternatively use a fast and DDoS resistant cache implementation. Axes can be configured to monitor login attempts by IP address, username, user agent, or their combinations. Axes supports cool off periods, IP address allow listing and block listing, user account allow listing, and other features for Django access management. Documentation ------------- For more information on installation and configuration see the documentation at: https://django-axes.readthedocs.io/ Issues ------ If you have questions or have trouble using the app please file a bug report at: https://github.com/jazzband/django-axes/issues Contributing ------------ See `CONTRIBUTING `__. django-axes-7.0.1/axes/000077500000000000000000000000001472335743500146745ustar00rootroot00000000000000django-axes-7.0.1/axes/__init__.py000066400000000000000000000001151472335743500170020ustar00rootroot00000000000000from importlib.metadata import version __version__ = version("django-axes") django-axes-7.0.1/axes/admin.py000066400000000000000000000057001472335743500163400ustar00rootroot00000000000000from django.contrib import admin from django.http import HttpRequest from django.utils.translation import gettext_lazy as _ from axes.conf import settings from axes.models import AccessAttempt, AccessLog, AccessFailureLog class AccessAttemptAdmin(admin.ModelAdmin): list_display = ( "attempt_time", "ip_address", "user_agent", "username", "path_info", "failures_since_start", ) list_filter = ["attempt_time", "path_info"] search_fields = ["ip_address", "username", "user_agent", "path_info"] date_hierarchy = "attempt_time" fieldsets = ( (None, {"fields": ("username", "path_info", "failures_since_start")}), (_("Form Data"), {"fields": ("get_data", "post_data")}), (_("Meta Data"), {"fields": ("user_agent", "ip_address", "http_accept")}), ) readonly_fields = [ "user_agent", "ip_address", "username", "http_accept", "path_info", "attempt_time", "get_data", "post_data", "failures_since_start", ] def has_add_permission(self, request: HttpRequest) -> bool: return False class AccessLogAdmin(admin.ModelAdmin): list_display = ( "attempt_time", "logout_time", "ip_address", "username", "user_agent", "path_info", ) list_filter = ["attempt_time", "logout_time", "path_info"] search_fields = ["ip_address", "user_agent", "username", "path_info"] date_hierarchy = "attempt_time" fieldsets = ( (None, {"fields": ("username", "path_info")}), (_("Meta Data"), {"fields": ("user_agent", "ip_address", "http_accept")}), ) readonly_fields = [ "user_agent", "ip_address", "username", "http_accept", "path_info", "attempt_time", "logout_time", ] def has_add_permission(self, request: HttpRequest) -> bool: return False class AccessFailureLogAdmin(admin.ModelAdmin): list_display = ( "attempt_time", "ip_address", "username", "user_agent", "path_info", "locked_out", ) list_filter = ["attempt_time", "locked_out", "path_info"] search_fields = ["ip_address", "user_agent", "username", "path_info"] date_hierarchy = "attempt_time" fieldsets = ( (None, {"fields": ("username", "path_info")}), (_("Meta Data"), {"fields": ("user_agent", "ip_address", "http_accept")}), ) readonly_fields = [ "user_agent", "ip_address", "username", "http_accept", "path_info", "attempt_time", "locked_out", ] def has_add_permission(self, request: HttpRequest) -> bool: return False if settings.AXES_ENABLE_ADMIN: admin.site.register(AccessAttempt, AccessAttemptAdmin) admin.site.register(AccessLog, AccessLogAdmin) admin.site.register(AccessFailureLog, AccessFailureLogAdmin) django-axes-7.0.1/axes/apps.py000066400000000000000000000033421472335743500162130ustar00rootroot00000000000000# pylint: disable=import-outside-toplevel, unused-import from logging import getLogger from django import apps from axes import __version__ log = getLogger(__name__) class AppConfig(apps.AppConfig): default_auto_field = "django.db.models.AutoField" name = "axes" initialized = False @classmethod def initialize(cls): """ Initialize Axes logging and show version information. This method is re-entrant and can be called multiple times. It displays version information exactly once at application startup. """ if cls.initialized: return cls.initialized = True # Only import settings, checks, and signals one time after Django has been initialized from axes.conf import settings from axes import checks, signals # Skip startup log messages if Axes is not set to verbose if settings.AXES_VERBOSE: if callable(settings.AXES_LOCKOUT_PARAMETERS) or isinstance( settings.AXES_LOCKOUT_PARAMETERS, str ): mode = "blocking by parameters that are calculated in a custom callable" else: mode = "blocking by " + " or ".join( [ ( param if isinstance(param, str) else "combination of " + " and ".join(param) ) for param in settings.AXES_LOCKOUT_PARAMETERS ] ) log.info( "AXES: BEGIN version %s, %s", __version__, mode, ) def ready(self): self.initialize() django-axes-7.0.1/axes/attempts.py000066400000000000000000000062511472335743500171130ustar00rootroot00000000000000from logging import getLogger from typing import List, Optional from django.db.models import QuerySet from django.http import HttpRequest from django.utils.timezone import datetime, now from axes.conf import settings from axes.helpers import get_client_username, get_client_parameters, get_cool_off from axes.models import AccessAttempt log = getLogger(__name__) def get_cool_off_threshold(request: Optional[HttpRequest] = None) -> datetime: """ Get threshold for fetching access attempts from the database. """ cool_off = get_cool_off(request) if cool_off is None: raise TypeError( "Cool off threshold can not be calculated with settings.AXES_COOLOFF_TIME set to None" ) attempt_time = request.axes_attempt_time if attempt_time is None: return now() - cool_off return attempt_time - cool_off def filter_user_attempts( request: HttpRequest, credentials: Optional[dict] = None ) -> List[QuerySet]: """ Return a list querysets of AccessAttempts that match the given request and credentials. """ username = get_client_username(request, credentials) filter_kwargs_list = get_client_parameters( username, request.axes_ip_address, request.axes_user_agent, request, credentials ) attempts_list = [ AccessAttempt.objects.filter(**filter_kwargs) for filter_kwargs in filter_kwargs_list ] return attempts_list def get_user_attempts( request: HttpRequest, credentials: Optional[dict] = None ) -> List[QuerySet]: """ Get list of querysets with valid user attempts that match the given request and credentials. """ attempts_list = filter_user_attempts(request, credentials) if settings.AXES_COOLOFF_TIME is None: log.debug( "AXES: Getting all access attempts from database because no AXES_COOLOFF_TIME is configured" ) return attempts_list threshold = get_cool_off_threshold(request) log.debug("AXES: Getting access attempts that are newer than %s", threshold) return [attempts.filter(attempt_time__gte=threshold) for attempts in attempts_list] def clean_expired_user_attempts(request: Optional[HttpRequest] = None) -> int: """ Clean expired user attempts from the database. """ if settings.AXES_COOLOFF_TIME is None: log.debug( "AXES: Skipping clean for expired access attempts because no AXES_COOLOFF_TIME is configured" ) return 0 threshold = get_cool_off_threshold(request) count, _ = AccessAttempt.objects.filter(attempt_time__lt=threshold).delete() log.info( "AXES: Cleaned up %s expired access attempts from database that were older than %s", count, threshold, ) return count def reset_user_attempts( request: HttpRequest, credentials: Optional[dict] = None ) -> int: """ Reset all user attempts that match the given request and credentials. """ attempts_list = filter_user_attempts(request, credentials) count = 0 for attempts in attempts_list: _count, _ = attempts.delete() count += _count log.info("AXES: Reset %s access attempts from database.", count) return count django-axes-7.0.1/axes/backends.py000066400000000000000000000073651472335743500170330ustar00rootroot00000000000000from typing import Optional from django.conf import settings from django.contrib.auth.backends import ModelBackend from django.http import HttpRequest from axes.exceptions import ( AxesBackendPermissionDenied, AxesBackendRequestParameterRequired, ) from axes.handlers.proxy import AxesProxyHandler from axes.helpers import get_credentials, get_lockout_message, toggleable class AxesStandaloneBackend: """ Authentication backend class that forbids login attempts for locked out users. Use this class as the first item of ``AUTHENTICATION_BACKENDS`` to prevent locked out users from being logged in by the Django authentication flow. .. note:: This backend does not log your user in. It monitors login attempts. It also does not run any permissions checks at all. Authentication is handled by the following backends that are configured in ``AUTHENTICATION_BACKENDS``. """ @toggleable def authenticate( self, request: HttpRequest, username: Optional[str] = None, password: Optional[str] = None, **kwargs: dict, ): """ Checks user lockout status and raises an exception if user is not allowed to log in. This method interrupts the login flow and inserts error message directly to the ``response_context`` attribute that is supplied as a keyword argument. :keyword response_context: kwarg that will be have its ``error`` attribute updated with context. :raises AxesBackendRequestParameterRequired: if request parameter is not passed. :raises AxesBackendPermissionDenied: if user is already locked out. """ if request is None: raise AxesBackendRequestParameterRequired( "AxesBackend requires a request as an argument to authenticate" ) credentials = get_credentials(username=username, password=password, **kwargs) if AxesProxyHandler.is_allowed(request, credentials): return # Locked out, don't try to authenticate, just update response_context and return. # Its a bit weird to pass a context and expect a response value but its nice to get a "why" back. error_msg = get_lockout_message() response_context = kwargs.get("response_context", {}) response_context["error"] = error_msg # This flag can be used later to check if it was Axes that denied the login attempt. if not settings.AXES_RESET_COOL_OFF_ON_FAILURE_DURING_LOCKOUT: request.axes_locked_out = True # Raise an error that stops the authentication flows at django.contrib.auth.authenticate. # This error stops bubbling up at the authenticate call which catches backend PermissionDenied errors. # After this error is caught by authenticate it emits a signal indicating user login failed, # which is processed by axes.signals.log_user_login_failed which logs and flags the failed request. # The axes.middleware.AxesMiddleware further processes the flagged request into a readable response. raise AxesBackendPermissionDenied( "AxesBackend detected that the given user is locked out" ) class AxesBackend(AxesStandaloneBackend, ModelBackend): """ Axes authentication backend that also inherits from ModelBackend, and thus also performs other functions of ModelBackend such as permissions checks. Use this class as the first item of ``AUTHENTICATION_BACKENDS`` to prevent locked out users from being logged in by the Django authentication flow. .. note:: This backend does not log your user in. It monitors login attempts. Authentication is handled by the following backends that are configured in ``AUTHENTICATION_BACKENDS``. """ django-axes-7.0.1/axes/checks.py000066400000000000000000000144541472335743500165160ustar00rootroot00000000000000from django.core.checks import ( # pylint: disable=redefined-builtin Tags, Warning, register, ) from django.utils.module_loading import import_string from axes.backends import AxesStandaloneBackend from axes.conf import settings class Messages: CACHE_INVALID = ( "You are using the django-axes cache handler for login attempt tracking." " Your cache configuration is however invalid and will not work correctly with django-axes." " This can leave security holes in your login systems as attempts are not tracked correctly." " Reconfigure settings.AXES_CACHE and settings.CACHES per django-axes configuration documentation." ) MIDDLEWARE_INVALID = ( "You do not have 'axes.middleware.AxesMiddleware' in your settings.MIDDLEWARE." ) BACKEND_INVALID = "You do not have 'axes.backends.AxesStandaloneBackend' or a subclass in your settings.AUTHENTICATION_BACKENDS." SETTING_DEPRECATED = "You have a deprecated setting {deprecated_setting} configured in your project settings" CALLABLE_INVALID = "{callable_setting} is not a valid callable." class Hints: CACHE_INVALID = None MIDDLEWARE_INVALID = None BACKEND_INVALID = "AxesModelBackend was renamed to AxesStandaloneBackend in django-axes version 5.0." SETTING_DEPRECATED = None CALLABLE_INVALID = None class Codes: CACHE_INVALID = "axes.W001" MIDDLEWARE_INVALID = "axes.W002" BACKEND_INVALID = "axes.W003" SETTING_DEPRECATED = "axes.W004" CALLABLE_INVALID = "axes.W005" @register(Tags.security, Tags.caches, Tags.compatibility) def axes_cache_check(app_configs, **kwargs): # pylint: disable=unused-argument axes_handler = getattr(settings, "AXES_HANDLER", "") axes_cache_key = getattr(settings, "AXES_CACHE", "default") axes_cache_config = settings.CACHES.get(axes_cache_key, {}) axes_cache_backend = axes_cache_config.get("BACKEND", "") axes_cache_backend_incompatible = [ "django.core.cache.backends.dummy.DummyCache", "django.core.cache.backends.locmem.LocMemCache", "django.core.cache.backends.filebased.FileBasedCache", ] warnings = [] if axes_handler == "axes.handlers.cache.AxesCacheHandler": if axes_cache_backend in axes_cache_backend_incompatible: warnings.append( Warning( msg=Messages.CACHE_INVALID, hint=Hints.CACHE_INVALID, id=Codes.CACHE_INVALID, ) ) return warnings @register(Tags.security, Tags.compatibility) def axes_middleware_check(app_configs, **kwargs): # pylint: disable=unused-argument warnings = [] if "axes.middleware.AxesMiddleware" not in settings.MIDDLEWARE: warnings.append( Warning( msg=Messages.MIDDLEWARE_INVALID, hint=Hints.MIDDLEWARE_INVALID, id=Codes.MIDDLEWARE_INVALID, ) ) return warnings @register(Tags.security, Tags.compatibility) def axes_backend_check(app_configs, **kwargs): # pylint: disable=unused-argument warnings = [] found = False for name in settings.AUTHENTICATION_BACKENDS: try: backend = import_string(name) except ModuleNotFoundError as e: raise ModuleNotFoundError( "Can not find module path defined in settings.AUTHENTICATION_BACKENDS" ) from e except ImportError as e: raise ImportError( "Can not import backend class defined in settings.AUTHENTICATION_BACKENDS" ) from e if issubclass(backend, AxesStandaloneBackend): found = True break if not found: warnings.append( Warning( msg=Messages.BACKEND_INVALID, hint=Hints.BACKEND_INVALID, id=Codes.BACKEND_INVALID, ) ) return warnings @register(Tags.compatibility) def axes_deprecation_check(app_configs, **kwargs): # pylint: disable=unused-argument warnings = [] deprecated_settings = [ "AXES_DISABLE_SUCCESS_ACCESS_LOG", "AXES_LOGGER", # AXES_PROXY_ and AXES_META_ parameters were updated to more explicit # AXES_IPWARE_PROXY_ and AXES_IPWARE_META_ prefixes in version 6.x "AXES_PROXY_ORDER", "AXES_PROXY_COUNT", "AXES_PROXY_TRUSTED_IPS", "AXES_META_PRECEDENCE_ORDER", # AXES_ONLY_USER_FAILURES, AXES_USE_USER_AGENT and # AXES_LOCK_OUT parameters were replaced with AXES_LOCKOUT_PARAMETERS # in version 6.x "AXES_ONLY_USER_FAILURES", "AXES_LOCK_OUT_BY_USER_OR_IP", "AXES_LOCK_OUT_BY_COMBINATION_USER_AND_IP", "AXES_USE_USER_AGENT", ] for deprecated_setting in deprecated_settings: try: getattr(settings, deprecated_setting) warnings.append( Warning( msg=Messages.SETTING_DEPRECATED.format( deprecated_setting=deprecated_setting ), hint=None, id=Codes.SETTING_DEPRECATED, ) ) except AttributeError: pass return warnings @register def axes_conf_check(app_configs, **kwargs): # pylint: disable=unused-argument warnings = [] callable_settings = [ "AXES_CLIENT_IP_CALLABLE", "AXES_CLIENT_STR_CALLABLE", "AXES_LOCKOUT_CALLABLE", "AXES_USERNAME_CALLABLE", "AXES_WHITELIST_CALLABLE", "AXES_COOLOFF_TIME", "AXES_LOCKOUT_PARAMETERS", ] for callable_setting in callable_settings: value = getattr(settings, callable_setting) if not is_valid_callable(value): warnings.append( Warning( msg=Messages.CALLABLE_INVALID.format( callable_setting=callable_setting ), hint=Hints.CALLABLE_INVALID, id=Codes.CALLABLE_INVALID, ) ) return warnings def is_valid_callable(value) -> bool: if value is None: return True if callable(value): return True if isinstance(value, str): try: import_string(value) except ImportError: return False return True django-axes-7.0.1/axes/conf.py000066400000000000000000000157021472335743500162000ustar00rootroot00000000000000from django.conf import settings from django.utils.translation import gettext_lazy as _ # disable plugin when set to False settings.AXES_ENABLED = getattr(settings, "AXES_ENABLED", True) # see if the user has overridden the failure limit settings.AXES_FAILURE_LIMIT = getattr(settings, "AXES_FAILURE_LIMIT", 3) # see if the user has set axes to lock out logins after failure limit settings.AXES_LOCK_OUT_AT_FAILURE = getattr(settings, "AXES_LOCK_OUT_AT_FAILURE", True) # lockout parameters # default value will be ["ip_address"] after removing AXES_LOCK_OUT params support settings.AXES_LOCKOUT_PARAMETERS = getattr(settings, "AXES_LOCKOUT_PARAMETERS", None) # TODO: remove it in future versions if settings.AXES_LOCKOUT_PARAMETERS is None: if getattr(settings, "AXES_ONLY_USER_FAILURES", False): settings.AXES_LOCKOUT_PARAMETERS = ["username"] else: if getattr(settings, "AXES_LOCK_OUT_BY_USER_OR_IP", False): settings.AXES_LOCKOUT_PARAMETERS = ["username", "ip_address"] elif getattr(settings, "AXES_LOCK_OUT_BY_COMBINATION_USER_AND_IP", False): settings.AXES_LOCKOUT_PARAMETERS = [["username", "ip_address"]] else: settings.AXES_LOCKOUT_PARAMETERS = ["ip_address"] if getattr(settings, "AXES_USE_USER_AGENT", False): if isinstance(settings.AXES_LOCKOUT_PARAMETERS[0], str): settings.AXES_LOCKOUT_PARAMETERS[0] = [ settings.AXES_LOCKOUT_PARAMETERS[0], "user_agent", ] else: settings.AXES_LOCKOUT_PARAMETERS[0].append("user_agent") # lock out just for admin site settings.AXES_ONLY_ADMIN_SITE = getattr(settings, "AXES_ONLY_ADMIN_SITE", False) # show Axes logs in admin settings.AXES_ENABLE_ADMIN = getattr(settings, "AXES_ENABLE_ADMIN", True) # use a specific username field to retrieve from login POST data settings.AXES_USERNAME_FORM_FIELD = getattr( settings, "AXES_USERNAME_FORM_FIELD", "username" ) # use a specific password field to retrieve from login POST data settings.AXES_PASSWORD_FORM_FIELD = getattr( settings, "AXES_PASSWORD_FORM_FIELD", "password" ) # noqa # use a provided callable to transform the POSTed username into the one used in credentials settings.AXES_USERNAME_CALLABLE = getattr(settings, "AXES_USERNAME_CALLABLE", None) # determine if given user should be always allowed to attempt authentication settings.AXES_WHITELIST_CALLABLE = getattr(settings, "AXES_WHITELIST_CALLABLE", None) # return custom lockout response if configured settings.AXES_LOCKOUT_CALLABLE = getattr(settings, "AXES_LOCKOUT_CALLABLE", None) # use a provided callable to get client ip address settings.AXES_CLIENT_IP_CALLABLE = getattr(settings, "AXES_CLIENT_IP_CALLABLE", None) # reset the number of failed attempts after one successful attempt settings.AXES_RESET_ON_SUCCESS = getattr(settings, "AXES_RESET_ON_SUCCESS", False) settings.AXES_DISABLE_ACCESS_LOG = getattr(settings, "AXES_DISABLE_ACCESS_LOG", False) settings.AXES_ENABLE_ACCESS_FAILURE_LOG = getattr( settings, "AXES_ENABLE_ACCESS_FAILURE_LOG", False ) settings.AXES_ACCESS_FAILURE_LOG_PER_USER_LIMIT = getattr( settings, "AXES_ACCESS_FAILURE_LOG_PER_USER_LIMIT", 1000 ) settings.AXES_HANDLER = getattr( settings, "AXES_HANDLER", "axes.handlers.database.AxesDatabaseHandler" ) settings.AXES_LOCKOUT_TEMPLATE = getattr(settings, "AXES_LOCKOUT_TEMPLATE", None) settings.AXES_LOCKOUT_URL = getattr(settings, "AXES_LOCKOUT_URL", None) settings.AXES_COOLOFF_TIME = getattr(settings, "AXES_COOLOFF_TIME", None) settings.AXES_VERBOSE = getattr(settings, "AXES_VERBOSE", settings.AXES_ENABLED) # whitelist and blacklist settings.AXES_NEVER_LOCKOUT_WHITELIST = getattr( settings, "AXES_NEVER_LOCKOUT_WHITELIST", False ) settings.AXES_NEVER_LOCKOUT_GET = getattr(settings, "AXES_NEVER_LOCKOUT_GET", False) settings.AXES_ONLY_WHITELIST = getattr(settings, "AXES_ONLY_WHITELIST", False) settings.AXES_IP_WHITELIST = getattr(settings, "AXES_IP_WHITELIST", None) settings.AXES_IP_BLACKLIST = getattr(settings, "AXES_IP_BLACKLIST", None) # message to show when locked out and have cooloff enabled settings.AXES_COOLOFF_MESSAGE = getattr( settings, "AXES_COOLOFF_MESSAGE", _("Account locked: too many login attempts. Please try again later."), ) # message to show when locked out and have cooloff disabled settings.AXES_PERMALOCK_MESSAGE = getattr( settings, "AXES_PERMALOCK_MESSAGE", _( "Account locked: too many login attempts. Contact an admin to unlock your account." ), ) # set CORS allowed origins when calling authentication over ajax settings.AXES_ALLOWED_CORS_ORIGINS = getattr(settings, "AXES_ALLOWED_CORS_ORIGINS", "*") # set the list of sensitive parameters to cleanse from get/post data before logging settings.AXES_SENSITIVE_PARAMETERS = getattr( settings, "AXES_SENSITIVE_PARAMETERS", ["username", "ip_address"], ) # set the callable for the readable string that can be used in # e.g. logging to distinguish client requests settings.AXES_CLIENT_STR_CALLABLE = getattr(settings, "AXES_CLIENT_STR_CALLABLE", None) # set the HTTP response code given by too many requests settings.AXES_HTTP_RESPONSE_CODE = getattr(settings, "AXES_HTTP_RESPONSE_CODE", 429) # If True, a failed login attempt during lockout will reset the cool off period settings.AXES_RESET_COOL_OFF_ON_FAILURE_DURING_LOCKOUT = getattr( settings, "AXES_RESET_COOL_OFF_ON_FAILURE_DURING_LOCKOUT", True ) ### # django-ipware settings for client IP address calculation and proxy detection # there are old AXES_PROXY_ and AXES_META_ legacy keys present for backwards compatibility # see https://github.com/un33k/django-ipware for further details ### # if your deployment is using reverse proxies, set this value to 'left-most' or 'right-most' per your configuration settings.AXES_IPWARE_PROXY_ORDER = getattr( settings, "AXES_IPWARE_PROXY_ORDER", getattr(settings, "AXES_PROXY_ORDER", "left-most"), ) # if your deployment is using reverse proxies, set this value to the number of proxies in front of Django settings.AXES_IPWARE_PROXY_COUNT = getattr( settings, "AXES_IPWARE_PROXY_COUNT", getattr(settings, "AXES_PROXY_COUNT", None), ) # if your deployment is using reverse proxies, set to your trusted proxy IP addresses prefixes if needed settings.AXES_IPWARE_PROXY_TRUSTED_IPS = getattr( settings, "AXES_IPWARE_PROXY_TRUSTED_IPS", getattr(settings, "AXES_PROXY_TRUSTED_IPS", None), ) # set to the names of request.META attributes that should be checked for the IP address of the client # if your deployment is using reverse proxies, ensure that the header attributes are securely set by the proxy # ensure that the client can not spoof the headers by setting them and sending them through the proxy settings.AXES_IPWARE_META_PRECEDENCE_ORDER = getattr( settings, "AXES_IPWARE_META_PRECEDENCE_ORDER", getattr( settings, "AXES_META_PRECEDENCE_ORDER", getattr(settings, "IPWARE_META_PRECEDENCE_ORDER", ("REMOTE_ADDR",)), ), ) django-axes-7.0.1/axes/decorators.py000066400000000000000000000011641472335743500174150ustar00rootroot00000000000000from functools import wraps from axes.handlers.proxy import AxesProxyHandler from axes.helpers import get_lockout_response def axes_dispatch(func): @wraps(func) def inner(request, *args, **kwargs): if AxesProxyHandler.is_allowed(request): return func(request, *args, **kwargs) return get_lockout_response(request) return inner def axes_form_invalid(func): @wraps(func) def inner(self, *args, **kwargs): if AxesProxyHandler.is_allowed(self.request): return func(self, *args, **kwargs) return get_lockout_response(self.request) return inner django-axes-7.0.1/axes/exceptions.py000066400000000000000000000005741472335743500174350ustar00rootroot00000000000000from django.core.exceptions import PermissionDenied class AxesBackendPermissionDenied(PermissionDenied): """ Raised by authentication backend on locked out requests to stop the Django authentication flow. """ class AxesBackendRequestParameterRequired(ValueError): """ Raised by authentication backend on invalid or missing request parameter value. """ django-axes-7.0.1/axes/handlers/000077500000000000000000000000001472335743500164745ustar00rootroot00000000000000django-axes-7.0.1/axes/handlers/__init__.py000066400000000000000000000000001472335743500205730ustar00rootroot00000000000000django-axes-7.0.1/axes/handlers/base.py000066400000000000000000000213201472335743500177560ustar00rootroot00000000000000import re from abc import ABC, abstractmethod from typing import Optional from warnings import warn from django.urls import reverse from django.urls.exceptions import NoReverseMatch from axes.conf import settings from axes.helpers import ( get_failure_limit, is_client_ip_address_blacklisted, is_client_ip_address_whitelisted, is_client_method_whitelisted, is_user_attempt_whitelisted, ) class AbstractAxesHandler(ABC): """ Contract that all handlers need to follow """ @abstractmethod def user_login_failed(self, sender, credentials: dict, request=None, **kwargs): """ Handles the Django ``django.contrib.auth.signals.user_login_failed`` authentication signal. """ raise NotImplementedError("user_login_failed should be implemented") @abstractmethod def user_logged_in(self, sender, request, user, **kwargs): """ Handles the Django ``django.contrib.auth.signals.user_logged_in`` authentication signal. """ raise NotImplementedError("user_logged_in should be implemented") @abstractmethod def user_logged_out(self, sender, request, user, **kwargs): """ Handles the Django ``django.contrib.auth.signals.user_logged_out`` authentication signal. """ raise NotImplementedError("user_logged_out should be implemented") @abstractmethod def get_failures(self, request, credentials: Optional[dict] = None) -> int: """ Checks the number of failures associated to the given request and credentials. This is a virtual method that needs an implementation in the handler subclass if the ``settings.AXES_LOCK_OUT_AT_FAILURE`` flag is set to ``True``. """ raise NotImplementedError("get_failures should be implemented") class AxesBaseHandler: # pylint: disable=unused-argument """ Handler API definition for implementations that are used by the ``AxesProxyHandler``. If you wish to specialize your own handler class, override the necessary methods and configure the class for use by setting ``settings.AXES_HANDLER = 'module.path.to.YourClass'``. Make sure that new the handler is compliant with AbstractAxesHandler and make sure it extends from this mixin. Refer to `AxesHandler` for an example. The default implementation that is actually used by Axes is ``axes.handlers.database.AxesDatabaseHandler``. .. note:: This is a virtual class and **can not be used without specialization**. """ def is_allowed(self, request, credentials: Optional[dict] = None) -> bool: """ Checks if the user is allowed to access or use given functionality such as a login view or authentication. This method is abstract and other backends can specialize it as needed, but the default implementation checks if the user has attempted to authenticate into the site too many times through the Django authentication backends and returns ``False`` if user exceeds the configured Axes thresholds. This checker can implement arbitrary checks such as IP whitelisting or blacklisting, request frequency checking, failed attempt monitoring or similar functions. Please refer to the ``axes.handlers.database.AxesDatabaseHandler`` for the default implementation and inspiration on some common checks and access restrictions before writing your own implementation. """ if settings.AXES_ONLY_ADMIN_SITE and not self.is_admin_request(request): return True if self.is_blacklisted(request, credentials): return False if self.is_whitelisted(request, credentials): return True if self.is_locked(request, credentials): return False return True def is_blacklisted(self, request, credentials: Optional[dict] = None) -> bool: """ Checks if the request or given credentials are blacklisted from access. """ if is_client_ip_address_blacklisted(request): return True return False def is_whitelisted(self, request, credentials: Optional[dict] = None) -> bool: """ Checks if the request or given credentials are whitelisted for access. """ if is_user_attempt_whitelisted(request, credentials): return True if is_client_ip_address_whitelisted(request): return True if is_client_method_whitelisted(request): return True return False def is_locked(self, request, credentials: Optional[dict] = None) -> bool: """ Checks if the request or given credentials are locked. """ if settings.AXES_LOCK_OUT_AT_FAILURE: # get_failures will have to be implemented by each specialized handler return self.get_failures( # type: ignore request, credentials ) >= get_failure_limit(request, credentials) return False def get_admin_url(self) -> Optional[str]: """ Returns admin url if exists, otherwise returns None """ try: return reverse("admin:index") except NoReverseMatch: return None def is_admin_request(self, request) -> bool: """ Checks that request located under admin site """ if hasattr(request, "path"): admin_url = self.get_admin_url() return ( admin_url is not None and re.match(f"^{admin_url}", request.path) is not None ) return False def is_admin_site(self, request) -> bool: """ Checks if the request is NOT for admin site if `settings.AXES_ONLY_ADMIN_SITE` is True. """ warn( ( "This method is deprecated and will be removed in future versions. " "If you looking for method that checks if `request.path` located under " "admin site, use `is_admin_request` instead." ), DeprecationWarning, ) if settings.AXES_ONLY_ADMIN_SITE and hasattr(request, "path"): try: admin_url = reverse("admin:index") except NoReverseMatch: return True return not re.match(f"^{admin_url}", request.path) return False def reset_attempts( self, *, ip_address: Optional[str] = None, username: Optional[str] = None, ip_or_username: bool = False, ) -> int: """ Resets access attempts that match the given IP address or username. This method makes more sense for the DB backend, but as it is used by the ProxyHandler (via inherent), it needs to be defined here, so we get compliant with all proxy methods. Please overwrite it on each specialized handler as needed. """ return 0 def reset_logs(self, *, age_days: Optional[int] = None) -> int: """ Resets access logs that are older than given number of days. This method makes more sense for the DB backend, but as it is used by the ProxyHandler (via inherent), it needs to be defined here, so we get compliant with all proxy methods. Please overwrite it on each specialized handler as needed. """ return 0 def reset_failure_logs(self, *, age_days: Optional[int] = None) -> int: """ Resets access failure logs that are older than given number of days. This method makes more sense for the DB backend, but as it is used by the ProxyHandler (via inherent), it needs to be defined here, so we get compliant with all proxy methods. Please overwrite it on each specialized handler as needed. """ return 0 def remove_out_of_limit_failure_logs( self, *, username: str, limit: Optional[int] = None ) -> int: """Remove access failure logs that are over AXES_ACCESS_FAILURE_LOG_PER_USER_LIMIT for user username. This method makes more sense for the DB backend, but as it is used by the ProxyHandler (via inherent), it needs to be defined here, so we get compliant with all proxy methods. Please overwrite it on each specialized handler as needed. """ return 0 class AxesHandler(AbstractAxesHandler, AxesBaseHandler): """ Signal bare handler implementation without any storage backend. """ def user_login_failed(self, sender, credentials: dict, request=None, **kwargs): pass def user_logged_in(self, sender, request, user, **kwargs): pass def user_logged_out(self, sender, request, user, **kwargs): pass def get_failures(self, request, credentials: Optional[dict] = None) -> int: return 0 django-axes-7.0.1/axes/handlers/cache.py000066400000000000000000000147461472335743500201250ustar00rootroot00000000000000from logging import getLogger from typing import Optional from axes.conf import settings from axes.handlers.base import AxesBaseHandler, AbstractAxesHandler from axes.helpers import ( get_cache, get_cache_timeout, get_client_cache_keys, get_client_str, get_client_username, get_credentials, get_failure_limit, get_lockout_parameters, ) from axes.models import AccessAttempt from axes.signals import user_locked_out log = getLogger(__name__) class AxesCacheHandler(AbstractAxesHandler, AxesBaseHandler): """ Signal handler implementation that records user login attempts to cache and locks users out if necessary. """ def __init__(self): self.cache = get_cache() def reset_attempts( self, *, ip_address: Optional[str] = None, username: Optional[str] = None, ip_or_username: bool = False, ) -> int: cache_keys: list = [] count = 0 if ip_address is None and username is None: raise NotImplementedError("Cannot clear all entries from cache") if ip_or_username: raise NotImplementedError( "Due to the cache key ip_or_username=True is not supported" ) cache_keys.extend( get_client_cache_keys( AccessAttempt(username=username, ip_address=ip_address) ) ) for cache_key in cache_keys: deleted = self.cache.delete(cache_key) count += int(deleted) if deleted is not None else 1 log.info("AXES: Reset %d access attempts from database.", count) return count def get_failures(self, request, credentials: Optional[dict] = None) -> int: cache_keys = get_client_cache_keys(request, credentials) failure_count = max( self.cache.get(cache_key, default=0) for cache_key in cache_keys ) return failure_count def user_login_failed(self, sender, credentials: dict, request=None, **kwargs): """ When user login fails, save attempt record in cache and lock user out if necessary. :raises AxesSignalPermissionDenied: if user should be locked out. """ if request is None: log.error( "AXES: AxesCacheHandler.user_login_failed does not function without a request." ) return username = get_client_username(request, credentials) lockout_parameters = get_lockout_parameters(request, credentials) if lockout_parameters == ["username"] and username is None: log.warning( "AXES: Username is None and username is the only one lockout parameter, new record will NOT be created." ) return # If axes denied access, don't record the failed attempt as that would reset the lockout time. if ( not settings.AXES_RESET_COOL_OFF_ON_FAILURE_DURING_LOCKOUT and request.axes_locked_out ): request.axes_credentials = credentials user_locked_out.send( "axes", request=request, username=username, ip_address=request.axes_ip_address, ) return client_str = get_client_str( username, request.axes_ip_address, request.axes_user_agent, request.axes_path_info, request, ) if self.is_whitelisted(request, credentials): log.info("AXES: Login failed from whitelisted client %s.", client_str) return cache_keys = get_client_cache_keys(request, credentials) cache_timeout = get_cache_timeout(request) failures = [] for cache_key in cache_keys: added = self.cache.add(key=cache_key, value=1, timeout=cache_timeout) if added: failures.append(1) else: failures.append(self.cache.incr(key=cache_key, delta=1)) self.cache.touch(key=cache_key, timeout=cache_timeout) failures_since_start = max(failures) request.axes_failures_since_start = failures_since_start if failures_since_start > 1: log.warning( "AXES: Repeated login failure by %s. Count = %d of %d. Updating existing record in the cache.", client_str, failures_since_start, get_failure_limit(request, credentials), ) else: log.warning( "AXES: New login failure by %s. Creating new record in the cache.", client_str, ) if ( settings.AXES_LOCK_OUT_AT_FAILURE and failures_since_start >= get_failure_limit(request, credentials) ): log.warning( "AXES: Locking out %s after repeated login failures.", client_str ) request.axes_locked_out = True request.axes_credentials = credentials user_locked_out.send( "axes", request=request, username=username, ip_address=request.axes_ip_address, ) def user_logged_in(self, sender, request, user, **kwargs): """ When user logs in, update the AccessLog related to the user. """ username = user.get_username() credentials = get_credentials(username) client_str = get_client_str( username, request.axes_ip_address, request.axes_user_agent, request.axes_path_info, request, ) log.info("AXES: Successful login by %s.", client_str) if settings.AXES_RESET_ON_SUCCESS: cache_keys = get_client_cache_keys(request, credentials) for cache_key in cache_keys: failures_since_start = self.cache.get(cache_key, default=0) self.cache.delete(cache_key) log.info( "AXES: Deleted %d failed login attempts by %s from cache.", failures_since_start, client_str, ) def user_logged_out(self, sender, request, user, **kwargs): username = user.get_username() if user else None client_str = get_client_str( username, request.axes_ip_address, request.axes_user_agent, request.axes_path_info, request, ) log.info("AXES: Successful logout by %s.", client_str) django-axes-7.0.1/axes/handlers/database.py000066400000000000000000000321331472335743500206140ustar00rootroot00000000000000from logging import getLogger from typing import Optional from django.db import router, transaction from django.db.models import F, Q, Sum, Value from django.db.models.functions import Concat from django.utils import timezone from axes.attempts import ( clean_expired_user_attempts, get_user_attempts, reset_user_attempts, ) from axes.conf import settings from axes.handlers.base import AxesBaseHandler, AbstractAxesHandler from axes.helpers import ( get_client_session_hash, get_client_str, get_client_username, get_credentials, get_failure_limit, get_lockout_parameters, get_query_str, ) from axes.models import AccessLog, AccessAttempt, AccessFailureLog from axes.signals import user_locked_out log = getLogger(__name__) class AxesDatabaseHandler(AbstractAxesHandler, AxesBaseHandler): """ Signal handler implementation that records user login attempts to database and locks users out if necessary. .. note:: The get_user_attempts function is called several time during the authentication and lockout process, caching its output can be dangerous. """ def reset_attempts( self, *, ip_address: Optional[str] = None, username: Optional[str] = None, ip_or_username: bool = False, ) -> int: attempts = AccessAttempt.objects.all() if ip_or_username: attempts = attempts.filter(Q(ip_address=ip_address) | Q(username=username)) else: if ip_address: attempts = attempts.filter(ip_address=ip_address) if username: attempts = attempts.filter(username=username) count, _ = attempts.delete() log.info("AXES: Reset %d access attempts from database.", count) return count def reset_logs(self, *, age_days: Optional[int] = None) -> int: if age_days is None: count, _ = AccessLog.objects.all().delete() log.info("AXES: Reset all %d access logs from database.", count) else: limit = timezone.now() - timezone.timedelta(days=age_days) count, _ = AccessLog.objects.filter(attempt_time__lte=limit).delete() log.info( "AXES: Reset %d access logs older than %d days from database.", count, age_days, ) return count def reset_failure_logs(self, *, age_days: Optional[int] = None) -> int: if age_days is None: count, _ = AccessFailureLog.objects.all().delete() log.info("AXES: Reset all %d access failure logs from database.", count) else: limit = timezone.now() - timezone.timedelta(days=age_days) count, _ = AccessFailureLog.objects.filter(attempt_time__lte=limit).delete() log.info( "AXES: Reset %d access failure logs older than %d days from database.", count, age_days, ) return count def remove_out_of_limit_failure_logs( self, *, username: str, limit: Optional[int] = settings.AXES_ACCESS_FAILURE_LOG_PER_USER_LIMIT, ) -> int: count = 0 failures = AccessFailureLog.objects.filter(username=username) out_of_limit_failures_logs = failures.count() - limit if out_of_limit_failures_logs > 0: for failure in failures[:out_of_limit_failures_logs]: failure.delete() count += 1 return count def get_failures(self, request, credentials: Optional[dict] = None) -> int: attempts_list = get_user_attempts(request, credentials) attempt_count = max( ( attempts.aggregate(Sum("failures_since_start"))[ "failures_since_start__sum" ] or 0 ) for attempts in attempts_list ) return attempt_count def user_login_failed(self, sender, credentials: dict, request=None, **kwargs): """When user login fails, save AccessFailureLog record in database, save AccessAttempt record in database, mark request with lockout attribute and emit lockout signal. """ log.info("AXES: User login failed, running database handler for failure.") if request is None: log.error( "AXES: AxesDatabaseHandler.user_login_failed does not function without a request." ) return # 1. database query: Clean up expired user attempts from the database before logging new attempts clean_expired_user_attempts(request) username = get_client_username(request, credentials) client_str = get_client_str( username, request.axes_ip_address, request.axes_user_agent, request.axes_path_info, request, ) # If axes denied access, don't record the failed attempt as that would reset the lockout time. if ( not settings.AXES_RESET_COOL_OFF_ON_FAILURE_DURING_LOCKOUT and request.axes_locked_out ): request.axes_credentials = credentials user_locked_out.send( "axes", request=request, username=username, ip_address=request.axes_ip_address, ) return # This replaces null byte chars that crash saving failures. get_data = get_query_str(request.GET).replace("\0", "0x00") post_data = get_query_str(request.POST).replace("\0", "0x00") if self.is_whitelisted(request, credentials): log.info("AXES: Login failed from whitelisted client %s.", client_str) return # 2. database query: Get or create access record with the new failure data lockout_parameters = get_lockout_parameters(request, credentials) if lockout_parameters == ["username"] and username is None: log.warning( "AXES: Username is None and username is the only one lockout parameter, new record will NOT be created." ) else: with transaction.atomic(using=router.db_for_write(AccessAttempt)): ( attempt, created, ) = AccessAttempt.objects.select_for_update().get_or_create( username=username, ip_address=request.axes_ip_address, user_agent=request.axes_user_agent, defaults={ "get_data": get_data, "post_data": post_data, "http_accept": request.axes_http_accept, "path_info": request.axes_path_info, "failures_since_start": 1, "attempt_time": request.axes_attempt_time, }, ) # Record failed attempt with all the relevant information. # Filtering based on username, IP address and user agent handled elsewhere, # and this handler just records the available information for further use. if created: log.warning( "AXES: New login failure by %s. Created new record in the database.", client_str, ) # 3. database query if there were previous attempts in the database # Update failed attempt information but do not touch the username, IP address, or user agent fields, # because attackers can request the site with multiple different configurations # in order to bypass the defense mechanisms that are used by the site. else: separator = "\n---------\n" attempt.get_data = Concat("get_data", Value(separator + get_data)) attempt.post_data = Concat( "post_data", Value(separator + post_data) ) attempt.http_accept = request.axes_http_accept attempt.path_info = request.axes_path_info attempt.failures_since_start = F("failures_since_start") + 1 attempt.attempt_time = request.axes_attempt_time attempt.save() log.warning( "AXES: Repeated login failure by %s. Updated existing record in the database.", client_str, ) # 3. or 4. database query: Calculate the current maximum failure number from the existing attempts failures_since_start = self.get_failures(request, credentials) request.axes_failures_since_start = failures_since_start if ( settings.AXES_LOCK_OUT_AT_FAILURE and failures_since_start >= get_failure_limit(request, credentials) ): log.warning( "AXES: Locking out %s after repeated login failures.", client_str ) request.axes_locked_out = True request.axes_credentials = credentials user_locked_out.send( "axes", request=request, username=username, ip_address=request.axes_ip_address, ) # 5. database entry: Log for ever the attempt in the AccessFailureLog if settings.AXES_ENABLE_ACCESS_FAILURE_LOG: with transaction.atomic(using=router.db_for_write(AccessFailureLog)): AccessFailureLog.objects.create( username=username, ip_address=request.axes_ip_address, user_agent=request.axes_user_agent, http_accept=request.axes_http_accept, path_info=request.axes_path_info, attempt_time=request.axes_attempt_time, locked_out=request.axes_locked_out, ) self.remove_out_of_limit_failure_logs(username=username) def user_logged_in(self, sender, request, user, **kwargs): """ When user logs in, update the AccessLog related to the user. """ # 1. database query: Clean up expired user attempts from the database clean_expired_user_attempts(request) username = user.get_username() credentials = get_credentials(username) client_str = get_client_str( username, request.axes_ip_address, request.axes_user_agent, request.axes_path_info, request, ) log.info("AXES: Successful login by %s.", client_str) if not settings.AXES_DISABLE_ACCESS_LOG: # 2. database query: Insert new access logs with login time AccessLog.objects.create( username=username, ip_address=request.axes_ip_address, user_agent=request.axes_user_agent, http_accept=request.axes_http_accept, path_info=request.axes_path_info, attempt_time=request.axes_attempt_time, # evaluate session hash here to ensure having the correct # value which is stored on the backend session_hash=get_client_session_hash(request), ) if settings.AXES_RESET_ON_SUCCESS: # 3. database query: Reset failed attempts for the logging in user count = reset_user_attempts(request, credentials) log.info( "AXES: Deleted %d failed login attempts by %s from database.", count, client_str, ) def user_logged_out(self, sender, request, user, **kwargs): """ When user logs out, update the AccessLog related to the user. """ # 1. database query: Clean up expired user attempts from the database clean_expired_user_attempts(request) username = user.get_username() if user else None client_str = get_client_str( username, request.axes_ip_address, request.axes_user_agent, request.axes_path_info, request, ) log.info("AXES: Successful logout by %s.", client_str) if username and not settings.AXES_DISABLE_ACCESS_LOG: # 2. database query: Update existing attempt logs with logout time AccessLog.objects.filter( username=username, logout_time__isnull=True, # update only access log for given session session_hash=get_client_session_hash(request), ).update(logout_time=request.axes_attempt_time) def post_save_access_attempt(self, instance, **kwargs): """ Handles the ``axes.models.AccessAttempt`` object post save signal. When needed, all post_save actions for this backend should be located here. """ def post_delete_access_attempt(self, instance, **kwargs): """ Handles the ``axes.models.AccessAttempt`` object post delete signal. When needed, all post_delete actions for this backend should be located here. """ django-axes-7.0.1/axes/handlers/dummy.py000066400000000000000000000013251472335743500202020ustar00rootroot00000000000000from axes.handlers.base import AxesBaseHandler, AbstractAxesHandler from typing import Optional class AxesDummyHandler(AbstractAxesHandler, AxesBaseHandler): """ Signal handler implementation that does nothing and can be used to disable signal processing. """ def is_allowed(self, request, credentials: Optional[dict] = None) -> bool: return True def user_login_failed(self, sender, credentials: dict, request=None, **kwargs): pass def user_logged_in(self, sender, request, user, **kwargs): pass def user_logged_out(self, sender, request, user, **kwargs): pass def get_failures(self, request, credentials: Optional[dict] = None) -> int: return 0 django-axes-7.0.1/axes/handlers/proxy.py000066400000000000000000000120361472335743500202310ustar00rootroot00000000000000# pylint: disable=arguments-differ # pylint generates false negatives from proxy class method overrides from logging import getLogger from typing import Optional from django.utils.module_loading import import_string from django.utils.timezone import now from axes.conf import settings from axes.handlers.base import AxesBaseHandler, AbstractAxesHandler, AxesHandler from axes.helpers import ( get_client_ip_address, get_client_user_agent, get_client_path_info, get_client_http_accept, toggleable, ) log = getLogger(__name__) class AxesProxyHandler(AbstractAxesHandler, AxesBaseHandler): """ Proxy interface for configurable Axes signal handler class. If you wish to implement a custom version of this handler, you can override the settings.AXES_HANDLER configuration string with a class that implements a compatible interface and methods. Defaults to using axes.handlers.proxy.AxesProxyHandler if not overridden. Refer to axes.handlers.proxy.AxesProxyHandler for default implementation. """ implementation = None # type: AxesHandler @classmethod def get_implementation(cls, force: bool = False) -> AxesHandler: """ Fetch and initialize configured handler implementation and memoize it to avoid reinitialization. This method is re-entrant and can be called multiple times from e.g. Django application loader. """ if force or not cls.implementation: cls.implementation = import_string(settings.AXES_HANDLER)() return cls.implementation @classmethod def reset_attempts( cls, *, ip_address: Optional[str] = None, username: Optional[str] = None, ip_or_username: bool = False, ) -> int: return cls.get_implementation().reset_attempts( ip_address=ip_address, username=username, ip_or_username=ip_or_username ) @classmethod def reset_logs(cls, *, age_days: Optional[int] = None) -> int: return cls.get_implementation().reset_logs(age_days=age_days) @classmethod def reset_failure_logs(cls, *, age_days: Optional[int] = None) -> int: return cls.get_implementation().reset_failure_logs(age_days=age_days) @classmethod def remove_out_of_limit_failure_logs( cls, *, username: str, limit: Optional[int] = None ) -> int: return cls.get_implementation().remove_out_of_limit_failure_logs( username=username ) @staticmethod def update_request(request): """ Update request attributes before passing them into the selected handler class. """ if request is None: log.error( "AXES: AxesProxyHandler.update_request can not set request attributes to a None request" ) return if not hasattr(request, "axes_updated"): if not hasattr(request, "axes_locked_out"): request.axes_locked_out = False request.axes_attempt_time = now() request.axes_ip_address = get_client_ip_address(request) request.axes_user_agent = get_client_user_agent(request) request.axes_path_info = get_client_path_info(request) request.axes_http_accept = get_client_http_accept(request) request.axes_failures_since_start = None request.axes_updated = True request.axes_credentials = None @classmethod def is_locked(cls, request, credentials: Optional[dict] = None) -> bool: cls.update_request(request) return cls.get_implementation().is_locked(request, credentials) @classmethod def is_allowed(cls, request, credentials: Optional[dict] = None) -> bool: cls.update_request(request) return cls.get_implementation().is_allowed(request, credentials) @classmethod def get_failures(cls, request, credentials: Optional[dict] = None) -> int: cls.update_request(request) return cls.get_implementation().get_failures(request, credentials) @classmethod @toggleable def user_login_failed(cls, sender, credentials: dict, request=None, **kwargs): cls.update_request(request) return cls.get_implementation().user_login_failed( sender, credentials, request, **kwargs ) @classmethod @toggleable def user_logged_in(cls, sender, request, user, **kwargs): cls.update_request(request) return cls.get_implementation().user_logged_in(sender, request, user, **kwargs) @classmethod @toggleable def user_logged_out(cls, sender, request, user, **kwargs): cls.update_request(request) return cls.get_implementation().user_logged_out(sender, request, user, **kwargs) @classmethod @toggleable def post_save_access_attempt(cls, instance, **kwargs): return cls.get_implementation().post_save_access_attempt(instance, **kwargs) @classmethod @toggleable def post_delete_access_attempt(cls, instance, **kwargs): return cls.get_implementation().post_delete_access_attempt(instance, **kwargs) django-axes-7.0.1/axes/handlers/test.py000066400000000000000000000012571472335743500200320ustar00rootroot00000000000000from axes.handlers.base import AxesHandler from typing import Optional class AxesTestHandler(AxesHandler): """ Signal handler implementation that does nothing, ideal for a test suite. """ def reset_attempts( self, *, ip_address: Optional[str] = None, username: Optional[str] = None, ip_or_username: bool = False, ) -> int: return 0 def reset_logs(self, *, age_days: Optional[int] = None) -> int: return 0 def is_allowed(self, request, credentials: Optional[dict] = None) -> bool: return True def get_failures(self, request, credentials: Optional[dict] = None) -> int: return 0 django-axes-7.0.1/axes/helpers.py000066400000000000000000000533501472335743500167160ustar00rootroot00000000000000from datetime import timedelta from hashlib import sha256 from logging import getLogger from string import Template from typing import Callable, Optional, Type, Union, List from urllib.parse import urlencode from django.core.cache import BaseCache, caches from django.http import HttpRequest, HttpResponse, JsonResponse, QueryDict from django.shortcuts import redirect, render from django.utils.encoding import force_bytes from django.utils.module_loading import import_string from axes.conf import settings from axes.models import AccessBase log = getLogger(__name__) try: import ipware.ip IPWARE_INSTALLED = True except ImportError: IPWARE_INSTALLED = False def get_cache() -> BaseCache: """ Get the cache instance Axes is configured to use with ``settings.AXES_CACHE`` and use ``'default'`` if not set. """ return caches[getattr(settings, "AXES_CACHE", "default")] def get_cache_timeout(request: Optional[HttpRequest] = None) -> Optional[int]: """ Return the cache timeout interpreted from settings.AXES_COOLOFF_TIME. The cache timeout can be either None if not configured or integer of seconds if configured. Notice that the settings.AXES_COOLOFF_TIME can be None, timedelta, float, integer, callable, or str path, and this function offers a unified _integer or None_ representation of that configuration for use with the Django cache backends. """ cool_off = get_cool_off(request) if cool_off is None: return None return int(cool_off.total_seconds()) def get_cool_off(request: Optional[HttpRequest] = None) -> Optional[timedelta]: """ Return the login cool off time interpreted from settings.AXES_COOLOFF_TIME. The return value is either None or timedelta. Notice that the settings.AXES_COOLOFF_TIME is either None, timedelta, integer/float of hours, a path to a callable or a callable taking 1 argument (the request). This function offers a unified _timedelta or None_ representation of that configuration for use with the Axes internal implementations. :exception TypeError: if settings.AXES_COOLOFF_TIME is of wrong type. """ cool_off = settings.AXES_COOLOFF_TIME if isinstance(cool_off, int): return timedelta(hours=cool_off) if isinstance(cool_off, float): return timedelta(minutes=cool_off * 60) if isinstance(cool_off, str): cool_off_func = import_string(cool_off) return cool_off_func(request) if callable(cool_off): return cool_off(request) # pylint: disable=not-callable return cool_off def get_cool_off_iso8601(delta: timedelta) -> str: """ Return datetime.timedelta translated to ISO 8601 formatted duration for use in e.g. cool offs. """ seconds = delta.total_seconds() minutes, seconds = divmod(seconds, 60) hours, minutes = divmod(minutes, 60) days, hours = divmod(hours, 24) days_str = f"{days:.0f}D" if days else "" time_str = "".join( f"{value:.0f}{designator}" for value, designator in [[hours, "H"], [minutes, "M"], [seconds, "S"]] if value ) if time_str: return f"P{days_str}T{time_str}" return f"P{days_str}" def get_credentials(username: Optional[str] = None, **kwargs) -> dict: """ Calculate credentials for Axes to use internally from given username and kwargs. Axes will set the username value into the key defined with ``settings.AXES_USERNAME_FORM_FIELD`` and update the credentials dictionary with the kwargs given on top of that. """ credentials = {settings.AXES_USERNAME_FORM_FIELD: username} credentials.update(kwargs) return credentials def get_client_username( request: HttpRequest, credentials: Optional[dict] = None ) -> str: """ Resolve client username from the given request or credentials if supplied. The order of preference for fetching the username is as follows: 1. If configured, use ``AXES_USERNAME_CALLABLE``, and supply ``request, credentials`` as arguments 2. If given, use ``credentials`` and fetch username from ``AXES_USERNAME_FORM_FIELD`` (defaults to ``username``) 3. Use request.POST and fetch username from ``AXES_USERNAME_FORM_FIELD`` (defaults to ``username``) :param request: incoming Django ``HttpRequest`` or similar object from authentication backend or other source :param credentials: incoming credentials ``dict`` or similar object from authentication backend or other source """ if settings.AXES_USERNAME_CALLABLE: log.debug("Using settings.AXES_USERNAME_CALLABLE to get username") if callable(settings.AXES_USERNAME_CALLABLE): return settings.AXES_USERNAME_CALLABLE( # pylint: disable=not-callable request, credentials ) if isinstance(settings.AXES_USERNAME_CALLABLE, str): return import_string(settings.AXES_USERNAME_CALLABLE)(request, credentials) raise TypeError( "settings.AXES_USERNAME_CALLABLE needs to be a string, callable, or None." ) if credentials: log.debug( "Using parameter credentials to get username with key settings.AXES_USERNAME_FORM_FIELD" ) return credentials.get(settings.AXES_USERNAME_FORM_FIELD, None) log.debug( "Using parameter request.POST to get username with key settings.AXES_USERNAME_FORM_FIELD" ) request_data = getattr(request, "data", request.POST) return request_data.get(settings.AXES_USERNAME_FORM_FIELD, None) def get_client_ip_address( request: HttpRequest, use_ipware: Optional[bool] = None, ) -> Optional[str]: """ Get client IP address as configured by the user. The order of preference for address resolution is as follows: 1. If configured, use ``AXES_CLIENT_IP_CALLABLE``, and supply ``request`` as argument 2. If available, use django-ipware package (parameters can be configured in the Axes package) 3. Use ``request.META.get('REMOTE_ADDR', None)`` as a fallback :param request: incoming Django ``HttpRequest`` or similar object from authentication backend or other source """ if settings.AXES_CLIENT_IP_CALLABLE: log.debug("Using settings.AXES_CLIENT_IP_CALLABLE to get client IP address") if callable(settings.AXES_CLIENT_IP_CALLABLE): return settings.AXES_CLIENT_IP_CALLABLE( # pylint: disable=not-callable request ) if isinstance(settings.AXES_CLIENT_IP_CALLABLE, str): return import_string(settings.AXES_CLIENT_IP_CALLABLE)(request) raise TypeError( "settings.AXES_CLIENT_IP_CALLABLE needs to be a string, callable, or None." ) # Resolve using django-ipware from a configuration flag that can be set to False to explicitly disable # this is added to both enable or disable the branch when ipware is installed in the test environment if use_ipware is None: use_ipware = IPWARE_INSTALLED if use_ipware: log.debug("Using django-ipware to get client IP address") client_ip_address, _ = ipware.ip.get_client_ip( request, proxy_order=settings.AXES_IPWARE_PROXY_ORDER, proxy_count=settings.AXES_IPWARE_PROXY_COUNT, proxy_trusted_ips=settings.AXES_IPWARE_PROXY_TRUSTED_IPS, request_header_order=settings.AXES_IPWARE_META_PRECEDENCE_ORDER, ) return client_ip_address log.debug( "Using request.META.get('REMOTE_ADDR', None) fallback method to get client IP address" ) return request.META.get("REMOTE_ADDR", None) def get_client_user_agent(request: HttpRequest) -> str: return request.META.get("HTTP_USER_AGENT", "")[:255] def get_client_path_info(request: HttpRequest) -> str: return request.META.get("PATH_INFO", "")[:255] def get_client_http_accept(request: HttpRequest) -> str: return request.META.get("HTTP_ACCEPT", "")[:1025] def get_lockout_parameters( request_or_attempt: Union[HttpRequest, AccessBase], credentials: Optional[dict] = None, ) -> List[Union[str, List[str]]]: if callable(settings.AXES_LOCKOUT_PARAMETERS): return settings.AXES_LOCKOUT_PARAMETERS(request_or_attempt, credentials) if isinstance(settings.AXES_LOCKOUT_PARAMETERS, str): return import_string(settings.AXES_LOCKOUT_PARAMETERS)( request_or_attempt, credentials ) if isinstance(settings.AXES_LOCKOUT_PARAMETERS, list): return settings.AXES_LOCKOUT_PARAMETERS raise TypeError( "settings.AXES_LOCKOUT_PARAMETERS needs to be a callable or iterable" ) def get_client_parameters( username: str, ip_address: str, user_agent: str, request_or_attempt: Union[HttpRequest, AccessBase], credentials: Optional[dict] = None, ) -> List[dict]: """ Get query parameters for filtering AccessAttempt queryset. This method returns a dict that guarantees iteration order for keys and values, and can so be used in e.g. the generation of hash keys or other deterministic functions. Returns list of dict, every item of list are separate parameters """ lockout_parameters = get_lockout_parameters(request_or_attempt, credentials) parameters_dict = { "username": username, "ip_address": ip_address, "user_agent": user_agent, } filter_kwargs = [] for parameter in lockout_parameters: try: if isinstance(parameter, str): filter_kwarg = {parameter: parameters_dict[parameter]} else: filter_kwarg = { combined_parameter: parameters_dict[combined_parameter] for combined_parameter in parameter } filter_kwargs.append(filter_kwarg) except KeyError as e: error_msg = ( f"{e} lockout parameter is not allowed. " f"Allowed parameters: {', '.join(parameters_dict.keys())}" ) log.exception(error_msg) raise ValueError(error_msg) from e return filter_kwargs def make_cache_key_list(filter_kwargs_list: List[dict]) -> List[str]: cache_keys = [] for filter_kwargs in filter_kwargs_list: cache_key_components = "".join( value for value in filter_kwargs.values() if value ) cache_key_digest = sha256(cache_key_components.encode()).hexdigest() cache_keys.append(f"axes-{cache_key_digest}") return cache_keys def get_client_cache_keys( request_or_attempt: Union[HttpRequest, AccessBase], credentials: Optional[dict] = None, ) -> List[str]: """ Build cache key name from request or AccessAttempt object. :param request_or_attempt: HttpRequest or AccessAttempt object :param credentials: credentials containing user information :return cache_key: Hash key that is usable for Django cache backends """ if isinstance(request_or_attempt, AccessBase): username = request_or_attempt.username ip_address = request_or_attempt.ip_address user_agent = request_or_attempt.user_agent else: username = get_client_username(request_or_attempt, credentials) ip_address = get_client_ip_address(request_or_attempt) user_agent = get_client_user_agent(request_or_attempt) filter_kwargs_list = get_client_parameters( username, ip_address, user_agent, request_or_attempt, credentials ) return make_cache_key_list(filter_kwargs_list) def get_client_str( username: str, ip_address: str, user_agent: str, path_info: str, request: HttpRequest, ) -> str: """ Get a readable string that can be used in e.g. logging to distinguish client requests. Example log format would be ``{username: "example", ip_address: "127.0.0.1", path_info: "/example/"}`` """ if settings.AXES_CLIENT_STR_CALLABLE: log.debug("Using settings.AXES_CLIENT_STR_CALLABLE to get client string.") if callable(settings.AXES_CLIENT_STR_CALLABLE): return settings.AXES_CLIENT_STR_CALLABLE( # pylint: disable=not-callable username, ip_address, user_agent, path_info, request ) if isinstance(settings.AXES_CLIENT_STR_CALLABLE, str): return import_string(settings.AXES_CLIENT_STR_CALLABLE)( username, ip_address, user_agent, path_info, request ) raise TypeError( "settings.AXES_CLIENT_STR_CALLABLE needs to be a string, callable or None." ) client_dict = {} if settings.AXES_VERBOSE: # Verbose mode logs every attribute that is available client_dict["username"] = username client_dict["ip_address"] = ip_address client_dict["user_agent"] = user_agent else: # Other modes initialize the attributes that are used for the actual lockouts client_list = get_client_parameters(username, ip_address, user_agent, request) client_dict = {} for client in client_list: client_dict.update(client) client_dict = cleanse_parameters(client_dict.copy()) # Path info is always included as last component in the client string for traceability purposes if path_info and isinstance(path_info, (tuple, list)): path_info = path_info[0] client_dict["path_info"] = path_info # Template the internal dictionary representation into a readable and concatenated {key: "value"} format template = Template('$key: "$value"') items = [{"key": k, "value": v} for k, v in client_dict.items()] client_str = ", ".join(template.substitute(item) for item in items) client_str = "{" + client_str + "}" return client_str def cleanse_parameters(params: dict) -> dict: """ Replace sensitive parameter values in a parameter dict with a safe placeholder value. Parameters name ``'password'`` will always be cleansed. Additionally, parameters named in ``settings.AXES_SENSITIVE_PARAMETERS`` and ``settings.AXES_PASSWORD_FORM_FIELD will be cleansed. This is used to prevent passwords and similar values from being logged in cleartext. """ sensitive_parameters = ["password"] + settings.AXES_SENSITIVE_PARAMETERS if settings.AXES_PASSWORD_FORM_FIELD: sensitive_parameters.append(settings.AXES_PASSWORD_FORM_FIELD) if sensitive_parameters: cleansed = params.copy() for param in sensitive_parameters: if param in cleansed: cleansed[param] = "********************" return cleansed return params def get_query_str(query: Type[QueryDict], max_length: int = 1024) -> str: """ Turns a query dictionary into an easy-to-read list of key-value pairs. If a field is called either ``'password'`` or ``settings.AXES_PASSWORD_FORM_FIELD`` or if the fieldname is included in ``settings.AXES_SENSITIVE_PARAMETERS`` its value will be masked. The length of the output is limited to max_length to avoid a DoS attack via excessively large payloads. """ query_dict = cleanse_parameters(query.copy()) template = Template("$key=$value") items = [{"key": k, "value": v} for k, v in query_dict.items()] query_str = "\n".join(template.substitute(item) for item in items) return query_str[:max_length] def get_failure_limit(request: HttpRequest, credentials) -> int: if callable(settings.AXES_FAILURE_LIMIT): return settings.AXES_FAILURE_LIMIT( # pylint: disable=not-callable request, credentials ) if isinstance(settings.AXES_FAILURE_LIMIT, str): return import_string(settings.AXES_FAILURE_LIMIT)(request, credentials) if isinstance(settings.AXES_FAILURE_LIMIT, int): return settings.AXES_FAILURE_LIMIT raise TypeError("settings.AXES_FAILURE_LIMIT needs to be a callable or an integer") def get_lockout_message() -> str: if settings.AXES_COOLOFF_TIME: return settings.AXES_COOLOFF_MESSAGE return settings.AXES_PERMALOCK_MESSAGE def get_lockout_response( request: HttpRequest, credentials: Optional[dict] = None ) -> HttpResponse: if settings.AXES_LOCKOUT_CALLABLE: if callable(settings.AXES_LOCKOUT_CALLABLE): return settings.AXES_LOCKOUT_CALLABLE( # pylint: disable=not-callable request, credentials ) if isinstance(settings.AXES_LOCKOUT_CALLABLE, str): return import_string(settings.AXES_LOCKOUT_CALLABLE)(request, credentials) raise TypeError( "settings.AXES_LOCKOUT_CALLABLE needs to be a string, callable, or None." ) status = settings.AXES_HTTP_RESPONSE_CODE context = { "failure_limit": get_failure_limit(request, credentials), "username": get_client_username(request, credentials) or "", } cool_off = get_cool_off(request) if cool_off: context.update( { "cooloff_time": get_cool_off_iso8601( cool_off ), # differing old name is kept for backwards compatibility "cooloff_timedelta": cool_off, } ) if request.META.get("HTTP_X_REQUESTED_WITH") == "XMLHttpRequest": json_response = JsonResponse(context, status=status) json_response["Access-Control-Allow-Origin"] = ( settings.AXES_ALLOWED_CORS_ORIGINS ) json_response["Access-Control-Allow-Methods"] = "POST, OPTIONS" json_response["Access-Control-Allow-Headers"] = ( "Origin, Content-Type, Accept, Authorization, x-requested-with" ) return json_response if settings.AXES_LOCKOUT_TEMPLATE: return render(request, settings.AXES_LOCKOUT_TEMPLATE, context, status=status) if settings.AXES_LOCKOUT_URL: lockout_url = settings.AXES_LOCKOUT_URL query_string = urlencode({"username": context["username"]}) url = f"{lockout_url}?{query_string}" return redirect(url) return HttpResponse(get_lockout_message(), status=status) def is_ip_address_in_whitelist(ip_address: str) -> bool: if not settings.AXES_IP_WHITELIST: return False return ( # pylint: disable=unsupported-membership-test ip_address in settings.AXES_IP_WHITELIST ) def is_ip_address_in_blacklist(ip_address: str) -> bool: if not settings.AXES_IP_BLACKLIST: return False return ( # pylint: disable=unsupported-membership-test ip_address in settings.AXES_IP_BLACKLIST ) def is_client_ip_address_whitelisted(request: HttpRequest): """ Check if the given request refers to a whitelisted IP. """ if settings.AXES_NEVER_LOCKOUT_WHITELIST and is_ip_address_in_whitelist( request.axes_ip_address ): return True if settings.AXES_ONLY_WHITELIST and is_ip_address_in_whitelist( request.axes_ip_address ): return True return False def is_client_ip_address_blacklisted(request: HttpRequest) -> bool: """ Check if the given request refers to a blacklisted IP. """ if is_ip_address_in_blacklist(request.axes_ip_address): return True if settings.AXES_ONLY_WHITELIST and not is_ip_address_in_whitelist( request.axes_ip_address ): return True return False def is_client_method_whitelisted(request: HttpRequest) -> bool: """ Check if the given request uses a whitelisted method. """ if settings.AXES_NEVER_LOCKOUT_GET and request.method == "GET": return True return False def is_user_attempt_whitelisted( request: HttpRequest, credentials: Optional[dict] = None ) -> bool: """ Check if the given request or credentials refer to a whitelisted username. This method invokes the ``settings.AXES_WHITELIST`` callable with ``request`` and ``credentials`` arguments. This function could use the following implementation for checking the lockout flags from a specific property in the user object: .. code-block: python username_value = get_client_username(request, credentials) username_field = getattr( get_user_model(), "USERNAME_FIELD", "username" ) kwargs = {username_field: username_value} user_model = get_user_model() user = user_model.objects.get(**kwargs) return user.nolockout """ whitelist_callable = settings.AXES_WHITELIST_CALLABLE if whitelist_callable is None: return False if callable(whitelist_callable): return whitelist_callable(request, credentials) # pylint: disable=not-callable if isinstance(whitelist_callable, str): return import_string(whitelist_callable)(request, credentials) raise TypeError( "settings.AXES_WHITELIST_CALLABLE needs to be a string, callable, or None." ) def toggleable(func) -> Callable: """ Decorator that toggles function execution based on settings. If the ``settings.AXES_ENABLED`` flag is set to ``False`` the decorated function never runs and a None is returned. This decorator is only suitable for functions that do not require return values to be passed back to callers. """ def inner(*args, **kwargs): # pylint: disable=inconsistent-return-statements if settings.AXES_ENABLED: return func(*args, **kwargs) return inner def get_client_session_hash(request: HttpRequest) -> str: """ Get client session and returns the SHA256 hash of session key, forcing session creation if required. If no session is available on request returns an empty string. """ try: session = request.session except AttributeError: # when no session is available just return an empty string return "" # ensure that a session key exists at this point # because session middleware usually creates the session key at the end # of request cycle if session.session_key is None: session.create() return sha256(force_bytes(session.session_key)).hexdigest() django-axes-7.0.1/axes/locale/000077500000000000000000000000001472335743500161335ustar00rootroot00000000000000django-axes-7.0.1/axes/locale/ar/000077500000000000000000000000001472335743500165355ustar00rootroot00000000000000django-axes-7.0.1/axes/locale/ar/LC_MESSAGES/000077500000000000000000000000001472335743500203225ustar00rootroot00000000000000django-axes-7.0.1/axes/locale/ar/LC_MESSAGES/django.mo000066400000000000000000000037421472335743500221270ustar00rootroot00000000000000|Q@S          !1@ P [gy"+:f  6Nd|    Access lock outAccount locked: too many login attempts. Contact an admin to unlock your account.Account locked: too many login attempts. Please try again later.Attempt TimeFailed LoginsForm DataGET DataHTTP AcceptIP AddressLogout TimeMeta DataPOST DataPathUser AgentUsernameaccess attemptaccess attemptsaccess failureaccess failuresaccess logaccess logsProject-Id-Version: PACKAGE VERSION Report-Msgid-Bugs-To: PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE Last-Translator: FULL NAME Language-Team: LANGUAGE Language: MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Plural-Forms: nplurals=6; plural=n==0 ? 0 : n==1 ? 1 : n==2 ? 2 : n%100>=3 && n%100<=10 ? 3 : n%100>=11 && n%100<=99 ? 4 : 5; مقيد من الدخولالحساب مغلق: محاولات تسجيل دخول كثيرة جدًا. اتصل بمسؤول لفتح حسابك.الحساب مغلق: محاولات تسجيل دخول كثيرة جدًا. الرجاء معاودة المحاولة في وقت لاحق.وقت المحاولةعمليات تسجيل دخول فاشلةبيانات النموذجGET بياناتقبول HTTPعنوان IPوقت تسجيل الخروجالبيانات الوصفيةPOST بياناتمعلومات المساروكيل المستخدماسم المستخدممحاولة دخولمحاولات دخولسجل دخول فاشلةسجلات دخول فاشلةسجل الدخولسجلات الدخولdjango-axes-7.0.1/axes/locale/ar/LC_MESSAGES/django.po000066400000000000000000000050061472335743500221250ustar00rootroot00000000000000# SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # FIRST AUTHOR , YEAR. # #, fuzzy msgid "" msgstr "" "Project-Id-Version: PACKAGE VERSION\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2022-05-30 15:16+0300\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: FULL NAME \n" "Language-Team: LANGUAGE \n" "Language: \n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=6; plural=n==0 ? 0 : n==1 ? 1 : n==2 ? 2 : n%100>=3 " "&& n%100<=10 ? 3 : n%100>=11 && n%100<=99 ? 4 : 5;\n" #: admin.py:27 msgid "Form Data" msgstr "بيانات النموذج" #: admin.py:28 admin.py:65 admin.py:100 msgid "Meta Data" msgstr "البيانات الوصفية" #: conf.py:97 msgid "Account locked: too many login attempts. Please try again later." msgstr "الحساب مغلق: محاولات تسجيل دخول كثيرة جدًا. الرجاء معاودة المحاولة في وقت لاحق." #: conf.py:105 msgid "" "Account locked: too many login attempts. Contact an admin to unlock your " "account." msgstr "الحساب مغلق: محاولات تسجيل دخول كثيرة جدًا. اتصل بمسؤول لفتح حسابك." #: models.py:6 msgid "User Agent" msgstr "وكيل المستخدم" #: models.py:8 msgid "IP Address" msgstr "عنوان IP" #: models.py:10 msgid "Username" msgstr "اسم المستخدم" #: models.py:12 msgid "HTTP Accept" msgstr "قبول HTTP" #: models.py:14 msgid "Path" msgstr "معلومات المسار" #: models.py:16 msgid "Attempt Time" msgstr "وقت المحاولة" #: models.py:26 msgid "Access lock out" msgstr "مقيد من الدخول" #: models.py:34 msgid "access failure" msgstr "سجل دخول فاشلة" #: models.py:35 msgid "access failures" msgstr "سجلات دخول فاشلة" #: models.py:39 msgid "GET Data" msgstr "GET بيانات" #: models.py:41 msgid "POST Data" msgstr "POST بيانات" #: models.py:43 msgid "Failed Logins" msgstr "عمليات تسجيل دخول فاشلة" #: models.py:49 msgid "access attempt" msgstr "محاولة دخول" #: models.py:50 msgid "access attempts" msgstr "محاولات دخول" #: models.py:55 msgid "Logout Time" msgstr "وقت تسجيل الخروج" #: models.py:61 msgid "access log" msgstr "سجل الدخول" #: models.py:62 msgid "access logs" msgstr "سجلات الدخول" django-axes-7.0.1/axes/locale/de/000077500000000000000000000000001472335743500165235ustar00rootroot00000000000000django-axes-7.0.1/axes/locale/de/LC_MESSAGES/000077500000000000000000000000001472335743500203105ustar00rootroot00000000000000django-axes-7.0.1/axes/locale/de/LC_MESSAGES/django.mo000066400000000000000000000032571472335743500221160ustar00rootroot00000000000000|Q@S          !1@ P [Bga;      "' 6CSd}      Access lock outAccount locked: too many login attempts. Contact an admin to unlock your account.Account locked: too many login attempts. Please try again later.Attempt TimeFailed LoginsForm DataGET DataHTTP AcceptIP AddressLogout TimeMeta DataPOST DataPathUser AgentUsernameaccess attemptaccess attemptsaccess failureaccess failuresaccess logaccess logsProject-Id-Version: PACKAGE VERSION Report-Msgid-Bugs-To: PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE Last-Translator: FULL NAME Language-Team: LANGUAGE Language: MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Plural-Forms: nplurals=2; plural=(n != 1); Zugriff gesperrtZugang gesperrt: zu viele fehlgeschlagene Anmeldeversuche. Kontaktieren Sie einen Administrator, um Ihren Zugang zu entsperren.Zugang gesperrt: zu viele fehlgeschlagene Anmeldeversuche. Bitte versuchen Sie es später erneut.ZugriffszeitpunktFehlgeschlagene AnmeldeversucheForm-DatenGET-DatenHTTP-AcceptIP-AdresseAbmeldezeitpunktMeta-DatenPOST-DatenPfadBrowserkennungBenutzernameZugriffsversuchZugriffsversucheFehlgeschlagener ZugriffFehlgeschlagene ZugriffeZugriffslogZugriffslogsdjango-axes-7.0.1/axes/locale/de/LC_MESSAGES/django.po000066400000000000000000000047001472335743500221130ustar00rootroot00000000000000# SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # FIRST AUTHOR , YEAR. # #, fuzzy msgid "" msgstr "" "Project-Id-Version: PACKAGE VERSION\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2022-05-27 11:46+0200\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: FULL NAME \n" "Language-Team: LANGUAGE \n" "Language: \n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=2; plural=(n != 1);\n" #: .\axes\admin.py:27 msgid "Form Data" msgstr "Form-Daten" #: .\axes\admin.py:28 .\axes\admin.py:65 .\axes\admin.py:100 msgid "Meta Data" msgstr "Meta-Daten" #: .\axes\conf.py:97 msgid "Account locked: too many login attempts. Please try again later." msgstr "" "Zugang gesperrt: zu viele fehlgeschlagene Anmeldeversuche. Bitte versuchen " "Sie es später erneut." #: .\axes\conf.py:105 msgid "" "Account locked: too many login attempts. Contact an admin to unlock your " "account." msgstr "" "Zugang gesperrt: zu viele fehlgeschlagene Anmeldeversuche. Kontaktieren Sie " "einen Administrator, um Ihren Zugang zu entsperren." #: .\axes\models.py:6 msgid "User Agent" msgstr "Browserkennung" #: .\axes\models.py:8 msgid "IP Address" msgstr "IP-Adresse" #: .\axes\models.py:10 msgid "Username" msgstr "Benutzername" #: .\axes\models.py:12 msgid "HTTP Accept" msgstr "HTTP-Accept" #: .\axes\models.py:14 msgid "Path" msgstr "Pfad" #: .\axes\models.py:16 msgid "Attempt Time" msgstr "Zugriffszeitpunkt" #: .\axes\models.py:26 #| msgid "access log" msgid "Access lock out" msgstr "Zugriff gesperrt" #: .\axes\models.py:34 #| msgid "access log" msgid "access failure" msgstr "Fehlgeschlagener Zugriff" #: .\axes\models.py:35 #| msgid "access logs" msgid "access failures" msgstr "Fehlgeschlagene Zugriffe" #: .\axes\models.py:39 msgid "GET Data" msgstr "GET-Daten" #: .\axes\models.py:41 msgid "POST Data" msgstr "POST-Daten" #: .\axes\models.py:43 msgid "Failed Logins" msgstr "Fehlgeschlagene Anmeldeversuche" #: .\axes\models.py:49 msgid "access attempt" msgstr "Zugriffsversuch" #: .\axes\models.py:50 msgid "access attempts" msgstr "Zugriffsversuche" #: .\axes\models.py:55 msgid "Logout Time" msgstr "Abmeldezeitpunkt" #: .\axes\models.py:61 msgid "access log" msgstr "Zugriffslog" #: .\axes\models.py:62 msgid "access logs" msgstr "Zugriffslogs" django-axes-7.0.1/axes/locale/fr/000077500000000000000000000000001472335743500165425ustar00rootroot00000000000000django-axes-7.0.1/axes/locale/fr/LC_MESSAGES/000077500000000000000000000000001472335743500203275ustar00rootroot00000000000000django-axes-7.0.1/axes/locale/fr/LC_MESSAGES/django.mo000066400000000000000000000033301472335743500221250ustar00rootroot00000000000000|Q@S          !1@ P [jgrS^    + 9G NYk      Access lock outAccount locked: too many login attempts. Contact an admin to unlock your account.Account locked: too many login attempts. Please try again later.Attempt TimeFailed LoginsForm DataGET DataHTTP AcceptIP AddressLogout TimeMeta DataPOST DataPathUser AgentUsernameaccess attemptaccess attemptsaccess failureaccess failuresaccess logaccess logsProject-Id-Version: PACKAGE VERSION Report-Msgid-Bugs-To: POT-Creation-Date: 2023-11-06 05:21-0600 PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE Last-Translator: FULL NAME Language-Team: LANGUAGE Language: MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Plural-Forms: nplurals=2; plural=(n > 1); Verrouillage de l'accèsCompte verrouillé: trop de tentatives de connexion. Contactez un administrateur pour déverrouiller votre compte.Compte verrouillé: trop de tentatives de connexion. Veuillez réessayer plus tard.Date de la tentativeNombre d'échecsDonnées de formulaireDonnées GETHTTP AcceptAdresse IPDate de la déconnexionMétadonnéesDonnées POSTCheminUser AgentNom d'utilisateurtentative de connexiontentatives de connexionéchec de connexionéchecs de connexionconnexionconnexionsdjango-axes-7.0.1/axes/locale/fr/LC_MESSAGES/django.po000066400000000000000000000043351472335743500221360ustar00rootroot00000000000000# SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # FIRST AUTHOR , YEAR. # #, fuzzy msgid "" msgstr "" "Project-Id-Version: PACKAGE VERSION\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2023-11-06 05:21-0600\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: FULL NAME \n" "Language-Team: LANGUAGE \n" "Language: \n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=2; plural=(n > 1);\n" #: admin.py:27 msgid "Form Data" msgstr "Données de formulaire" #: admin.py:28 admin.py:65 admin.py:100 msgid "Meta Data" msgstr "Métadonnées" #: conf.py:108 msgid "Account locked: too many login attempts. Please try again later." msgstr "" "Compte verrouillé: trop de tentatives de connexion. Veuillez réessayer plus " "tard." #: conf.py:116 msgid "" "Account locked: too many login attempts. Contact an admin to unlock your " "account." msgstr "" "Compte verrouillé: trop de tentatives de connexion. Contactez un " "administrateur pour déverrouiller votre compte." #: models.py:6 msgid "User Agent" msgstr "User Agent" #: models.py:8 msgid "IP Address" msgstr "Adresse IP" #: models.py:10 msgid "Username" msgstr "Nom d'utilisateur" #: models.py:12 msgid "HTTP Accept" msgstr "HTTP Accept" #: models.py:14 msgid "Path" msgstr "Chemin" #: models.py:16 msgid "Attempt Time" msgstr "Date de la tentative" #: models.py:26 msgid "Access lock out" msgstr "Verrouillage de l'accès" #: models.py:34 msgid "access failure" msgstr "échec de connexion" #: models.py:35 msgid "access failures" msgstr "échecs de connexion" #: models.py:39 msgid "GET Data" msgstr "Données GET" #: models.py:41 msgid "POST Data" msgstr "Données POST" #: models.py:43 msgid "Failed Logins" msgstr "Nombre d'échecs" #: models.py:49 msgid "access attempt" msgstr "tentative de connexion" #: models.py:50 msgid "access attempts" msgstr "tentatives de connexion" #: models.py:55 msgid "Logout Time" msgstr "Date de la déconnexion" #: models.py:61 msgid "access log" msgstr "connexion" #: models.py:62 msgid "access logs" msgstr "connexions" django-axes-7.0.1/axes/locale/id/000077500000000000000000000000001472335743500165275ustar00rootroot00000000000000django-axes-7.0.1/axes/locale/id/LC_MESSAGES/000077500000000000000000000000001472335743500203145ustar00rootroot00000000000000django-axes-7.0.1/axes/locale/id/LC_MESSAGES/django.mo000066400000000000000000000031221472335743500221110ustar00rootroot00000000000000|Q@S          !1@ P [igUG6~           . > H    Access lock outAccount locked: too many login attempts. Contact an admin to unlock your account.Account locked: too many login attempts. Please try again later.Attempt TimeFailed LoginsForm DataGET DataHTTP AcceptIP AddressLogout TimeMeta DataPOST DataPathUser AgentUsernameaccess attemptaccess attemptsaccess failureaccess failuresaccess logaccess logsProject-Id-Version: django-axes 6.0.4 Report-Msgid-Bugs-To: POT-Creation-Date: 2023-06-30 09:21+0800 PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE Last-Translator: Kira Language-Team: LANGUAGE Language: id MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Plural-Forms: nplurals=1; plural=0; Akses terkunciAkun terkunci: terlalu banyak percobaan login. Hubungi admin untuk membuka kunci akunAkun terkunci: terlalu banyak percobaan login. Silakan coba lagi nanti.Waktu PercobaanLogin GagalData FormulirData GETHTTP AcceptAlamat IPWaktu LogoutMeta DataData POSTPathUser AgentNama Penggunaupaya aksesupaya akseskegagalan akseskegagalan akseslog akseslog aksesdjango-axes-7.0.1/axes/locale/id/LC_MESSAGES/django.po000066400000000000000000000043411472335743500221200ustar00rootroot00000000000000# Indonesian translation for django-axes. # Copyright (C) 2023 # This file is distributed under the same license as the django-axes package. # Kira , 2023. # #, fuzzy msgid "" msgstr "" "Project-Id-Version: django-axes 6.0.4\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2023-06-30 09:21+0800\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: Kira \n" "Language-Team: LANGUAGE \n" "Language: id\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=1; plural=0;\n" #: .\axes\admin.py:27 msgid "Form Data" msgstr "Data Formulir" #: .\axes\admin.py:28 .\axes\admin.py:65 .\axes\admin.py:100 msgid "Meta Data" msgstr "Meta Data" #: .\axes\conf.py:108 msgid "Account locked: too many login attempts. Please try again later." msgstr "Akun terkunci: terlalu banyak percobaan login. Silakan coba lagi nanti." #: .\axes\conf.py:116 msgid "" "Account locked: too many login attempts. Contact an admin to unlock your " "account." msgstr "Akun terkunci: terlalu banyak percobaan login. Hubungi admin untuk" " membuka kunci akun" #: .\axes\models.py:6 msgid "User Agent" msgstr "User Agent" #: .\axes\models.py:8 msgid "IP Address" msgstr "Alamat IP" #: .\axes\models.py:10 msgid "Username" msgstr "Nama Pengguna" #: .\axes\models.py:12 msgid "HTTP Accept" msgstr "HTTP Accept" #: .\axes\models.py:14 msgid "Path" msgstr "Path" #: .\axes\models.py:16 msgid "Attempt Time" msgstr "Waktu Percobaan" #: .\axes\models.py:26 msgid "Access lock out" msgstr "Akses terkunci" #: .\axes\models.py:34 msgid "access failure" msgstr "kegagalan akses" #: .\axes\models.py:35 msgid "access failures" msgstr "kegagalan akses" #: .\axes\models.py:39 msgid "GET Data" msgstr "Data GET" #: .\axes\models.py:41 msgid "POST Data" msgstr "Data POST" #: .\axes\models.py:43 msgid "Failed Logins" msgstr "Login Gagal" #: .\axes\models.py:49 msgid "access attempt" msgstr "upaya akses" #: .\axes\models.py:50 msgid "access attempts" msgstr "upaya akses" #: .\axes\models.py:55 msgid "Logout Time" msgstr "Waktu Logout" #: .\axes\models.py:61 msgid "access log" msgstr "log akses" #: .\axes\models.py:62 msgid "access logs" msgstr "log akses" django-axes-7.0.1/axes/locale/pl/000077500000000000000000000000001472335743500165465ustar00rootroot00000000000000django-axes-7.0.1/axes/locale/pl/LC_MESSAGES/000077500000000000000000000000001472335743500203335ustar00rootroot00000000000000django-axes-7.0.1/axes/locale/pl/LC_MESSAGES/django.mo000066400000000000000000000027661472335743500221450ustar00rootroot00000000000000,Q@  ) 7A J U a kuz  nlK'9L\en     Account locked: too many login attempts. Contact an admin to unlock your account.Account locked: too many login attempts. Please try again later.Attempt TimeFailed LoginsForm DataGET DataIP AddressLogout TimeMeta DataPOST DataPathUsernameaccess attemptaccess attemptsaccess logaccess logsProject-Id-Version: Report-Msgid-Bugs-To: PO-Revision-Date: 2021-06-16 10:51+0300 Language: pl MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Plural-Forms: nplurals=4; plural=(n==1 ? 0 : (n%10>=2 && n%10<=4) && (n%100<12 || n%100>14) ? 1 : n!=1 && (n%10>=0 && n%10<=1) || (n%10>=5 && n%10<=9) || (n%100>=12 && n%100<=14) ? 2 : 3); Last-Translator: Language-Team: X-Generator: Poedit 3.0 Konto zablokowane: zbyt wiele prób logowania. Skontaktuj się z administratorem, aby odblokować swoje konto.Konto zablokowane: zbyt wiele prób logowania. Spróbuj ponownie później.Czas wystąpieniaNieudane logowaniaDane formularzaDane GETAdres IPCzas wylogowaniaMetadaneDane POSTŚcieżkaNazwa Użytkownikapróba dostępupróby dostępudziennik logowaniadzienniki logowaniadjango-axes-7.0.1/axes/locale/pl/LC_MESSAGES/django.po000066400000000000000000000043321472335743500221370ustar00rootroot00000000000000# SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # FIRST AUTHOR , YEAR. # msgid "" msgstr "" "Project-Id-Version: \n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2021-06-11 23:36+0200\n" "PO-Revision-Date: 2021-06-16 10:51+0300\n" "Language: pl\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=4; plural=(n==1 ? 0 : (n%10>=2 && n%10<=4) && (n" "%100<12 || n%100>14) ? 1 : n!=1 && (n%10>=0 && n%10<=1) || (n%10>=5 && n" "%10<=9) || (n%100>=12 && n%100<=14) ? 2 : 3);\n" "Last-Translator: \n" "Language-Team: \n" "X-Generator: Poedit 3.0\n" #: .\axes\admin.py:26 msgid "Form Data" msgstr "Dane formularza" #: .\axes\admin.py:27 .\axes\admin.py:64 msgid "Meta Data" msgstr "Metadane" #: .\axes\conf.py:89 msgid "Account locked: too many login attempts. Please try again later." msgstr "" "Konto zablokowane: zbyt wiele prób logowania. Spróbuj ponownie później." #: .\axes\conf.py:97 msgid "" "Account locked: too many login attempts. Contact an admin to unlock your " "account." msgstr "" "Konto zablokowane: zbyt wiele prób logowania. Skontaktuj się z " "administratorem, aby odblokować swoje konto." #: .\axes\models.py:6 #, fuzzy msgid "User Agent" msgstr "User Agent" #: .\axes\models.py:8 msgid "IP Address" msgstr "Adres IP" #: .\axes\models.py:10 msgid "Username" msgstr "Nazwa Użytkownika" #: .\axes\models.py:12 #, fuzzy msgid "HTTP Accept" msgstr "HTTP Accept" #: .\axes\models.py:14 msgid "Path" msgstr "Ścieżka" #: .\axes\models.py:16 msgid "Attempt Time" msgstr "Czas wystąpienia" #: .\axes\models.py:25 msgid "GET Data" msgstr "Dane GET" #: .\axes\models.py:27 msgid "POST Data" msgstr "Dane POST" #: .\axes\models.py:29 msgid "Failed Logins" msgstr "Nieudane logowania" #: .\axes\models.py:35 msgid "access attempt" msgstr "próba dostępu" #: .\axes\models.py:36 msgid "access attempts" msgstr "próby dostępu" #: .\axes\models.py:40 msgid "Logout Time" msgstr "Czas wylogowania" #: .\axes\models.py:46 msgid "access log" msgstr "dziennik logowania" #: .\axes\models.py:47 msgid "access logs" msgstr "dzienniki logowania" django-axes-7.0.1/axes/locale/ru/000077500000000000000000000000001472335743500165615ustar00rootroot00000000000000django-axes-7.0.1/axes/locale/ru/LC_MESSAGES/000077500000000000000000000000001472335743500203465ustar00rootroot00000000000000django-axes-7.0.1/axes/locale/ru/LC_MESSAGES/django.mo000066400000000000000000000040411472335743500221440ustar00rootroot00000000000000|Q@S          !1@ P [Bg$K!p   2 ;F-f     Access lock outAccount locked: too many login attempts. Contact an admin to unlock your account.Account locked: too many login attempts. Please try again later.Attempt TimeFailed LoginsForm DataGET DataHTTP AcceptIP AddressLogout TimeMeta DataPOST DataPathUser AgentUsernameaccess attemptaccess attemptsaccess failureaccess failuresaccess logaccess logsProject-Id-Version: PACKAGE VERSION Report-Msgid-Bugs-To: PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE Last-Translator: FULL NAME Language-Team: LANGUAGE Language: MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Plural-Forms: nplurals=2; plural=(n != 1); Доступ запрещенУчетная запись заблокирована: слишком много попыток входа. Свяжитесь с администратором, чтобы разблокировать учетную запись.Учетная запись заблокирована: слишком много попыток входа. Повторите попытку позже.Время попытки входаОшибочные попыткиДанные формыДанные GET-запросаHTTP AcceptIP АдресВремя выходаМетаданныеДанные POST-запросаПутьUser AgentИмя пользователяЗапись о попытке доступаПопытки доступаОшибка доступаОшибки доступаЗапись о доступеЛоги доступаdjango-axes-7.0.1/axes/locale/ru/LC_MESSAGES/django.po000066400000000000000000000053011472335743500221470ustar00rootroot00000000000000# SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # FIRST AUTHOR , YEAR. # #, fuzzy msgid "" msgstr "" "Project-Id-Version: PACKAGE VERSION\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2023-05-13 12:36+0500\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: FULL NAME \n" "Language-Team: LANGUAGE \n" "Language: \n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=2; plural=(n != 1);\n" #: axes/admin.py:27 msgid "Form Data" msgstr "Данные формы" #: axes/admin.py:28 axes/admin.py:65 axes/admin.py:100 msgid "Meta Data" msgstr "Метаданные" #: axes/conf.py:99 msgid "Account locked: too many login attempts. Please try again later." msgstr "" "Учетная запись заблокирована: слишком много попыток входа. Повторите попытку " "позже." #: axes/conf.py:107 msgid "" "Account locked: too many login attempts. Contact an admin to unlock your " "account." msgstr "" "Учетная запись заблокирована: слишком много попыток входа. Свяжитесь с " "администратором, чтобы разблокировать учетную запись." #: axes/models.py:6 msgid "User Agent" msgstr "User Agent" #: axes/models.py:8 msgid "IP Address" msgstr "IP Адрес" #: axes/models.py:10 msgid "Username" msgstr "Имя пользователя" #: axes/models.py:12 msgid "HTTP Accept" msgstr "HTTP Accept" #: axes/models.py:14 msgid "Path" msgstr "Путь" #: axes/models.py:16 msgid "Attempt Time" msgstr "Время попытки входа" #: axes/models.py:26 msgid "Access lock out" msgstr "Доступ запрещен" #: axes/models.py:34 msgid "access failure" msgstr "Ошибка доступа" #: axes/models.py:35 msgid "access failures" msgstr "Ошибки доступа" #: axes/models.py:39 msgid "GET Data" msgstr "Данные GET-запроса" #: axes/models.py:41 msgid "POST Data" msgstr "Данные POST-запроса" #: axes/models.py:43 msgid "Failed Logins" msgstr "Ошибочные попытки" #: axes/models.py:49 msgid "access attempt" msgstr "Запись о попытке доступа" #: axes/models.py:50 msgid "access attempts" msgstr "Попытки доступа" #: axes/models.py:55 msgid "Logout Time" msgstr "Время выхода" #: axes/models.py:61 msgid "access log" msgstr "Запись о доступе" #: axes/models.py:62 msgid "access logs" msgstr "Логи доступа" django-axes-7.0.1/axes/locale/tr/000077500000000000000000000000001472335743500165605ustar00rootroot00000000000000django-axes-7.0.1/axes/locale/tr/LC_MESSAGES/000077500000000000000000000000001472335743500203455ustar00rootroot00000000000000django-axes-7.0.1/axes/locale/tr/LC_MESSAGES/django.mo000066400000000000000000000026041472335743500221460ustar00rootroot00000000000000,Q@  ) 7A J U a kuz  BhRe     (,=Nap   Account locked: too many login attempts. Contact an admin to unlock your account.Account locked: too many login attempts. Please try again later.Attempt TimeFailed LoginsForm DataGET DataIP AddressLogout TimeMeta DataPOST DataPathUsernameaccess attemptaccess attemptsaccess logaccess logsProject-Id-Version: PACKAGE VERSION Report-Msgid-Bugs-To: PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE Last-Translator: FULL NAME Language-Team: LANGUAGE Language: MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Plural-Forms: nplurals=2; plural=(n != 1); Hesap kilitlendi: cok fazla erişim denemesi. Hesabını açtırmak için yöneticiyle iletişimegeçin.Hesap kilitlendi: cok fazla erişim denemesi. Lütfen daha sonra tekrar deneyiniz.Girişim ZamanıGeçersiz GirişlerForm-VerisiGET-VerisiIP-AdresiÇıkış ZamanıMeta-VerisiPOST-VerisiYolKullanıcı Adıerişim denemesierişim denemelerierişim kaydıerişim kayıtlarıdjango-axes-7.0.1/axes/locale/tr/LC_MESSAGES/django.po000066400000000000000000000040331472335743500221470ustar00rootroot00000000000000# SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # FIRST AUTHOR , YEAR. # #, fuzzy msgid "" msgstr "" "Project-Id-Version: PACKAGE VERSION\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2018-07-17 15:56+0200\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: FULL NAME \n" "Language-Team: LANGUAGE \n" "Language: \n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=2; plural=(n != 1);\n" #: axes/admin.py:38 msgid "Form Data" msgstr "Form-Verisi" #: axes/admin.py:41 axes/admin.py:95 msgid "Meta Data" msgstr "Meta-Verisi" #: axes/conf.py:58 msgid "Account locked: too many login attempts. Please try again later." msgstr "" "Hesap kilitlendi: cok fazla erişim denemesi. Lütfen daha sonra tekrar deneyiniz." #: axes/conf.py:61 msgid "" "Account locked: too many login attempts. Contact an admin to unlock your " "account." msgstr "" "Hesap kilitlendi: cok fazla erişim denemesi. Hesabını açtırmak için yöneticiyle iletişime" "geçin." #: axes/models.py:9 msgid "User Agent" msgstr "" #: axes/models.py:15 msgid "IP Address" msgstr "IP-Adresi" #: axes/models.py:21 msgid "Username" msgstr "Kullanıcı Adı" #: axes/models.py:35 msgid "HTTP Accept" msgstr "" #: axes/models.py:40 msgid "Path" msgstr "Yol" #: axes/models.py:45 msgid "Attempt Time" msgstr "Girişim Zamanı" #: axes/models.py:57 msgid "GET Data" msgstr "GET-Verisi" #: axes/models.py:61 msgid "POST Data" msgstr "POST-Verisi" #: axes/models.py:65 msgid "Failed Logins" msgstr "Geçersiz Girişler" #: axes/models.py:76 msgid "access attempt" msgstr "erişim denemesi" #: axes/models.py:77 msgid "access attempts" msgstr "erişim denemeleri" #: axes/models.py:81 msgid "Logout Time" msgstr "Çıkış Zamanı" #: axes/models.py:90 msgid "access log" msgstr "erişim kaydı" #: axes/models.py:91 msgid "access logs" msgstr "erişim kayıtları" django-axes-7.0.1/axes/management/000077500000000000000000000000001472335743500170105ustar00rootroot00000000000000django-axes-7.0.1/axes/management/__init__.py000066400000000000000000000000001472335743500211070ustar00rootroot00000000000000django-axes-7.0.1/axes/management/commands/000077500000000000000000000000001472335743500206115ustar00rootroot00000000000000django-axes-7.0.1/axes/management/commands/__init__.py000066400000000000000000000000001472335743500227100ustar00rootroot00000000000000django-axes-7.0.1/axes/management/commands/axes_list_attempts.py000066400000000000000000000005611472335743500251010ustar00rootroot00000000000000from django.core.management.base import BaseCommand from axes.models import AccessAttempt class Command(BaseCommand): help = "List access attempts" def handle(self, *args, **options): for obj in AccessAttempt.objects.all(): self.stdout.write( f"{obj.ip_address}\t{obj.username}\t{obj.failures_since_start}" ) django-axes-7.0.1/axes/management/commands/axes_reset.py000066400000000000000000000005661472335743500233340ustar00rootroot00000000000000from django.core.management.base import BaseCommand from axes.utils import reset class Command(BaseCommand): help = "Reset all access attempts and lockouts" def handle(self, *args, **options): count = reset() if count: self.stdout.write(f"{count} attempts removed.") else: self.stdout.write("No attempts found.") django-axes-7.0.1/axes/management/commands/axes_reset_failure_logs.py000066400000000000000000000012231472335743500260560ustar00rootroot00000000000000from django.core.management.base import BaseCommand from axes.handlers.proxy import AxesProxyHandler class Command(BaseCommand): help = "Reset access failure log records older than given days." def add_arguments(self, parser): parser.add_argument( "--age", type=int, default=30, help="Maximum age for records to keep in days", ) def handle(self, *args, **options): count = AxesProxyHandler.reset_failure_logs(age_days=options["age"]) if count: self.stdout.write(f"{count} logs removed.") else: self.stdout.write("No logs found.") django-axes-7.0.1/axes/management/commands/axes_reset_ip.py000066400000000000000000000010501472335743500240110ustar00rootroot00000000000000from django.core.management.base import BaseCommand from axes.utils import reset class Command(BaseCommand): help = "Reset all access attempts and lockouts for given IP addresses" def add_arguments(self, parser): parser.add_argument("ip", nargs="+", type=str) def handle(self, *args, **options): count = 0 for ip in options["ip"]: count += reset(ip=ip) if count: self.stdout.write(f"{count} attempts removed.") else: self.stdout.write("No attempts found.") django-axes-7.0.1/axes/management/commands/axes_reset_ip_username.py000066400000000000000000000011141472335743500257110ustar00rootroot00000000000000from django.core.management.base import BaseCommand from axes.utils import reset class Command(BaseCommand): help = "Reset all access attempts and lockouts for a given IP address and username" def add_arguments(self, parser): parser.add_argument("ip", type=str) parser.add_argument("username", type=str) def handle(self, *args, **options): count = reset(ip=options["ip"], username=options["username"]) if count: self.stdout.write(f"{count} attempts removed.") else: self.stdout.write("No attempts found.") django-axes-7.0.1/axes/management/commands/axes_reset_logs.py000066400000000000000000000012031472335743500243450ustar00rootroot00000000000000from django.core.management.base import BaseCommand from axes.handlers.proxy import AxesProxyHandler class Command(BaseCommand): help = "Reset access log records older than given days." def add_arguments(self, parser): parser.add_argument( "--age", type=int, default=30, help="Maximum age for records to keep in days", ) def handle(self, *args, **options): count = AxesProxyHandler.reset_logs(age_days=options["age"]) if count: self.stdout.write(f"{count} logs removed.") else: self.stdout.write("No logs found.") django-axes-7.0.1/axes/management/commands/axes_reset_username.py000066400000000000000000000011031472335743500252170ustar00rootroot00000000000000from django.core.management.base import BaseCommand from axes.utils import reset class Command(BaseCommand): help = "Reset all access attempts and lockouts for given usernames" def add_arguments(self, parser): parser.add_argument("username", nargs="+", type=str) def handle(self, *args, **options): count = 0 for username in options["username"]: count += reset(username=username) if count: self.stdout.write(f"{count} attempts removed.") else: self.stdout.write("No attempts found.") django-axes-7.0.1/axes/middleware.py000066400000000000000000000047521472335743500173730ustar00rootroot00000000000000from typing import Callable from asgiref.sync import iscoroutinefunction, markcoroutinefunction, sync_to_async from django.conf import settings from django.http import HttpRequest, HttpResponse from axes.helpers import get_lockout_response class AxesMiddleware: """ Middleware that calculates necessary HTTP request attributes for attempt monitoring and maps lockout signals into readable HTTP 403 Forbidden responses. If a project uses ``django rest framework`` then the middleware updates the request and checks whether the limit has been exceeded. It's needed only for integration with DRF because it uses its own request object. This middleware recognizes a logout monitoring flag in the request and and uses the ``axes.helpers.get_lockout_response`` handler for returning customizable and context aware lockout message to the end user if necessary. To customize the lockout handling behaviour further, you can subclass this middleware and change the ``__call__`` method to your own liking. Please see the following configuration flags before customizing this handler: - ``AXES_LOCKOUT_TEMPLATE``, - ``AXES_LOCKOUT_URL``, - ``AXES_COOLOFF_MESSAGE``, and - ``AXES_PERMALOCK_MESSAGE``. """ async_capable = True sync_capable = True def __init__(self, get_response: Callable) -> None: self.get_response = get_response if iscoroutinefunction(self.get_response): markcoroutinefunction(self) def __call__(self, request: HttpRequest) -> HttpResponse: # Exit out to async mode, if needed if iscoroutinefunction(self): return self.__acall__(request) response = self.get_response(request) if settings.AXES_ENABLED: if getattr(request, "axes_locked_out", None): credentials = getattr(request, "axes_credentials", None) response = get_lockout_response(request, credentials) # type: ignore return response async def __acall__(self, request: HttpRequest) -> HttpResponse: response = await self.get_response(request) if settings.AXES_ENABLED: if getattr(request, "axes_locked_out", None): credentials = getattr(request, "axes_credentials", None) response = await sync_to_async( get_lockout_response, thread_sensitive=True )( request, credentials ) # type: ignore return response django-axes-7.0.1/axes/migrations/000077500000000000000000000000001472335743500170505ustar00rootroot00000000000000django-axes-7.0.1/axes/migrations/0001_initial.py000066400000000000000000000054161472335743500215210ustar00rootroot00000000000000from django.db import migrations, models class Migration(migrations.Migration): dependencies = [] operations = [ migrations.CreateModel( name="AccessAttempt", fields=[ ( "id", models.AutoField( verbose_name="ID", serialize=False, auto_created=True, primary_key=True, ), ), ("user_agent", models.CharField(max_length=255)), ( "ip_address", models.GenericIPAddressField(null=True, verbose_name="IP Address"), ), ("username", models.CharField(max_length=255, null=True)), ("trusted", models.BooleanField(default=False)), ( "http_accept", models.CharField(max_length=1025, verbose_name="HTTP Accept"), ), ("path_info", models.CharField(max_length=255, verbose_name="Path")), ("attempt_time", models.DateTimeField(auto_now_add=True)), ("get_data", models.TextField(verbose_name="GET Data")), ("post_data", models.TextField(verbose_name="POST Data")), ( "failures_since_start", models.PositiveIntegerField(verbose_name="Failed Logins"), ), ], options={"ordering": ["-attempt_time"], "abstract": False}, ), migrations.CreateModel( name="AccessLog", fields=[ ( "id", models.AutoField( verbose_name="ID", serialize=False, auto_created=True, primary_key=True, ), ), ("user_agent", models.CharField(max_length=255)), ( "ip_address", models.GenericIPAddressField(null=True, verbose_name="IP Address"), ), ("username", models.CharField(max_length=255, null=True)), ("trusted", models.BooleanField(default=False)), ( "http_accept", models.CharField(max_length=1025, verbose_name="HTTP Accept"), ), ("path_info", models.CharField(max_length=255, verbose_name="Path")), ("attempt_time", models.DateTimeField(auto_now_add=True)), ("logout_time", models.DateTimeField(null=True, blank=True)), ], options={"ordering": ["-attempt_time"], "abstract": False}, ), ] django-axes-7.0.1/axes/migrations/0002_auto_20151217_2044.py000066400000000000000000000032721472335743500224720ustar00rootroot00000000000000from django.db import migrations, models class Migration(migrations.Migration): dependencies = [("axes", "0001_initial")] operations = [ migrations.AlterField( model_name="accessattempt", name="ip_address", field=models.GenericIPAddressField( db_index=True, null=True, verbose_name="IP Address" ), ), migrations.AlterField( model_name="accessattempt", name="trusted", field=models.BooleanField(db_index=True, default=False), ), migrations.AlterField( model_name="accessattempt", name="user_agent", field=models.CharField(db_index=True, max_length=255), ), migrations.AlterField( model_name="accessattempt", name="username", field=models.CharField(db_index=True, max_length=255, null=True), ), migrations.AlterField( model_name="accesslog", name="ip_address", field=models.GenericIPAddressField( db_index=True, null=True, verbose_name="IP Address" ), ), migrations.AlterField( model_name="accesslog", name="trusted", field=models.BooleanField(db_index=True, default=False), ), migrations.AlterField( model_name="accesslog", name="user_agent", field=models.CharField(db_index=True, max_length=255), ), migrations.AlterField( model_name="accesslog", name="username", field=models.CharField(db_index=True, max_length=255, null=True), ), ] django-axes-7.0.1/axes/migrations/0003_auto_20160322_0929.py000066400000000000000000000036331472335743500225030ustar00rootroot00000000000000from django.db import models, migrations class Migration(migrations.Migration): dependencies = [("axes", "0002_auto_20151217_2044")] operations = [ migrations.AlterField( model_name="accessattempt", name="failures_since_start", field=models.PositiveIntegerField(verbose_name="Failed Logins"), ), migrations.AlterField( model_name="accessattempt", name="get_data", field=models.TextField(verbose_name="GET Data"), ), migrations.AlterField( model_name="accessattempt", name="http_accept", field=models.CharField(verbose_name="HTTP Accept", max_length=1025), ), migrations.AlterField( model_name="accessattempt", name="ip_address", field=models.GenericIPAddressField( null=True, verbose_name="IP Address", db_index=True ), ), migrations.AlterField( model_name="accessattempt", name="path_info", field=models.CharField(verbose_name="Path", max_length=255), ), migrations.AlterField( model_name="accessattempt", name="post_data", field=models.TextField(verbose_name="POST Data"), ), migrations.AlterField( model_name="accesslog", name="http_accept", field=models.CharField(verbose_name="HTTP Accept", max_length=1025), ), migrations.AlterField( model_name="accesslog", name="ip_address", field=models.GenericIPAddressField( null=True, verbose_name="IP Address", db_index=True ), ), migrations.AlterField( model_name="accesslog", name="path_info", field=models.CharField(verbose_name="Path", max_length=255), ), ] django-axes-7.0.1/axes/migrations/0004_auto_20181024_1538.py000066400000000000000000000042241472335743500225000ustar00rootroot00000000000000from django.db import migrations, models class Migration(migrations.Migration): dependencies = [("axes", "0003_auto_20160322_0929")] operations = [ migrations.AlterModelOptions( name="accessattempt", options={ "verbose_name": "access attempt", "verbose_name_plural": "access attempts", }, ), migrations.AlterModelOptions( name="accesslog", options={ "verbose_name": "access log", "verbose_name_plural": "access logs", }, ), migrations.AlterField( model_name="accessattempt", name="attempt_time", field=models.DateTimeField(auto_now_add=True, verbose_name="Attempt Time"), ), migrations.AlterField( model_name="accessattempt", name="user_agent", field=models.CharField( db_index=True, max_length=255, verbose_name="User Agent" ), ), migrations.AlterField( model_name="accessattempt", name="username", field=models.CharField( db_index=True, max_length=255, null=True, verbose_name="Username" ), ), migrations.AlterField( model_name="accesslog", name="attempt_time", field=models.DateTimeField(auto_now_add=True, verbose_name="Attempt Time"), ), migrations.AlterField( model_name="accesslog", name="logout_time", field=models.DateTimeField( blank=True, null=True, verbose_name="Logout Time" ), ), migrations.AlterField( model_name="accesslog", name="user_agent", field=models.CharField( db_index=True, max_length=255, verbose_name="User Agent" ), ), migrations.AlterField( model_name="accesslog", name="username", field=models.CharField( db_index=True, max_length=255, null=True, verbose_name="Username" ), ), ] django-axes-7.0.1/axes/migrations/0005_remove_accessattempt_trusted.py000066400000000000000000000003321472335743500260530ustar00rootroot00000000000000from django.db import migrations class Migration(migrations.Migration): dependencies = [("axes", "0004_auto_20181024_1538")] operations = [migrations.RemoveField(model_name="accessattempt", name="trusted")] django-axes-7.0.1/axes/migrations/0006_remove_accesslog_trusted.py000066400000000000000000000004211472335743500251560ustar00rootroot00000000000000# Generated by Django 2.0.4 on 2019-03-13 08:55 from django.db import migrations class Migration(migrations.Migration): dependencies = [("axes", "0005_remove_accessattempt_trusted")] operations = [migrations.RemoveField(model_name="accesslog", name="trusted")] django-axes-7.0.1/axes/migrations/0007_alter_accessattempt_unique_together.py000066400000000000000000000025161472335743500274120ustar00rootroot00000000000000# Generated by Django 3.2.7 on 2021-09-13 15:16 from django.db import migrations, router from django.db.models import Count def deduplicate_attempts(apps, schema_editor): AccessAttempt = apps.get_model("axes", "AccessAttempt") db_alias = schema_editor.connection.alias if db_alias != router.db_for_write(AccessAttempt): return duplicated_attempts = ( AccessAttempt.objects.using(db_alias) .values("username", "user_agent", "ip_address") .annotate(Count("id")) .order_by() .filter(id__count__gt=1) ) for attempt in duplicated_attempts: redundant_attempts = AccessAttempt.objects.using(db_alias).filter( username=attempt["username"], user_agent=attempt["user_agent"], ip_address=attempt["ip_address"], )[1:] for redundant_attempt in redundant_attempts: redundant_attempt.delete(using=db_alias) class Migration(migrations.Migration): dependencies = [ ("axes", "0006_remove_accesslog_trusted"), ] operations = [ migrations.RunPython( deduplicate_attempts, reverse_code=migrations.RunPython.noop ), migrations.AlterUniqueTogether( name="accessattempt", unique_together={("username", "ip_address", "user_agent")}, ), ] django-axes-7.0.1/axes/migrations/0008_accessfailurelog.py000066400000000000000000000042221472335743500234040ustar00rootroot00000000000000# Generated by Django 3.2.12 on 2022-03-15 03:00 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("axes", "0007_alter_accessattempt_unique_together"), ] operations = [ migrations.CreateModel( name="AccessFailureLog", fields=[ ( "id", models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID", ), ), ( "user_agent", models.CharField( db_index=True, max_length=255, verbose_name="User Agent" ), ), ( "ip_address", models.GenericIPAddressField( db_index=True, null=True, verbose_name="IP Address" ), ), ( "username", models.CharField( db_index=True, max_length=255, null=True, verbose_name="Username", ), ), ( "http_accept", models.CharField(max_length=1025, verbose_name="HTTP Accept"), ), ("path_info", models.CharField(max_length=255, verbose_name="Path")), ( "attempt_time", models.DateTimeField( auto_now_add=True, verbose_name="Attempt Time" ), ), ( "locked_out", models.BooleanField( blank=True, default=False, verbose_name="Access lock out" ), ), ], options={ "verbose_name": "access failure", "verbose_name_plural": "access failures", }, ), ] django-axes-7.0.1/axes/migrations/0009_add_session_hash.py000066400000000000000000000010241472335743500233650ustar00rootroot00000000000000# Generated by Django 4.2.2 on 2024-04-30 07:57 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("axes", "0008_accessfailurelog"), ] operations = [ migrations.AddField( model_name="accesslog", name="session_hash", field=models.CharField( blank=True, default="", max_length=64, verbose_name="Session key hash (sha256)", ), ), ] django-axes-7.0.1/axes/migrations/__init__.py000066400000000000000000000000001472335743500211470ustar00rootroot00000000000000django-axes-7.0.1/axes/models.py000066400000000000000000000037771472335743500165470ustar00rootroot00000000000000from django.db import models from django.utils.translation import gettext_lazy as _ class AccessBase(models.Model): user_agent = models.CharField(_("User Agent"), max_length=255, db_index=True) ip_address = models.GenericIPAddressField(_("IP Address"), null=True, db_index=True) username = models.CharField(_("Username"), max_length=255, null=True, db_index=True) http_accept = models.CharField(_("HTTP Accept"), max_length=1025) path_info = models.CharField(_("Path"), max_length=255) attempt_time = models.DateTimeField(_("Attempt Time"), auto_now_add=True) class Meta: app_label = "axes" abstract = True ordering = ["-attempt_time"] class AccessFailureLog(AccessBase): locked_out = models.BooleanField( _("Access lock out"), null=False, blank=True, default=False ) def __str__(self): locked_out_str = " locked out" if self.locked_out else "" return f"Failed access: user {self.username}{locked_out_str} on {self.attempt_time} from {self.ip_address}" class Meta: verbose_name = _("access failure") verbose_name_plural = _("access failures") class AccessAttempt(AccessBase): get_data = models.TextField(_("GET Data")) post_data = models.TextField(_("POST Data")) failures_since_start = models.PositiveIntegerField(_("Failed Logins")) def __str__(self): return f"Attempted Access: {self.attempt_time}" class Meta: verbose_name = _("access attempt") verbose_name_plural = _("access attempts") unique_together = [["username", "ip_address", "user_agent"]] class AccessLog(AccessBase): logout_time = models.DateTimeField(_("Logout Time"), null=True, blank=True) session_hash = models.CharField(_("Session key hash (sha256)"), default="", blank=True, max_length=64) def __str__(self): return f"Access Log for {self.username} @ {self.attempt_time}" class Meta: verbose_name = _("access log") verbose_name_plural = _("access logs") django-axes-7.0.1/axes/signals.py000066400000000000000000000033661472335743500167160ustar00rootroot00000000000000from logging import getLogger from django.contrib.auth.signals import ( user_logged_in, user_logged_out, user_login_failed, ) from django.core.signals import setting_changed from django.db.models.signals import post_save, post_delete from django.dispatch import Signal from django.dispatch import receiver from axes.handlers.proxy import AxesProxyHandler from axes.models import AccessAttempt log = getLogger(__name__) # This signal provides the following arguments to any listeners: # request - The current Request object. # username - The username of the User who has been locked out. # ip_address - The IP of the user who has been locked out. user_locked_out = Signal() @receiver(user_login_failed) def handle_user_login_failed(*args, **kwargs): AxesProxyHandler.user_login_failed(*args, **kwargs) @receiver(user_logged_in) def handle_user_logged_in(*args, **kwargs): AxesProxyHandler.user_logged_in(*args, **kwargs) @receiver(user_logged_out) def handle_user_logged_out(*args, **kwargs): AxesProxyHandler.user_logged_out(*args, **kwargs) @receiver(post_save, sender=AccessAttempt) def handle_post_save_access_attempt(*args, **kwargs): AxesProxyHandler.post_save_access_attempt(*args, **kwargs) @receiver(post_delete, sender=AccessAttempt) def handle_post_delete_access_attempt(*args, **kwargs): AxesProxyHandler.post_delete_access_attempt(*args, **kwargs) @receiver(setting_changed) def handle_setting_changed( sender, setting, value, enter, **kwargs ): # pylint: disable=unused-argument """ Reinitialize handler implementation if a relevant setting changes in e.g. application reconfiguration or during testing. """ if setting == "AXES_HANDLER": AxesProxyHandler.get_implementation(force=True) django-axes-7.0.1/axes/utils.py000066400000000000000000000042251472335743500164110ustar00rootroot00000000000000""" Axes utility functions that are publicly available. This module is separate for historical reasons and offers a backwards compatible import path. """ from logging import getLogger from typing import Optional from django.http import HttpRequest from axes.handlers.proxy import AxesProxyHandler from axes.helpers import get_client_ip_address, get_lockout_parameters log = getLogger(__name__) def reset( ip: Optional[str] = None, username: Optional[str] = None, ip_or_username=False ) -> int: """ Reset records that match IP or username, and return the count of removed attempts. This utility method is meant to be used from the CLI or via Python API. """ return AxesProxyHandler.reset_attempts( ip_address=ip, username=username, ip_or_username=ip_or_username ) def reset_request(request: HttpRequest) -> int: """ Reset records that match IP or username, and return the count of removed attempts. This utility method is meant to be used from the CLI or via Python API. """ lockout_paramaters = get_lockout_parameters(request) ip: Optional[str] = get_client_ip_address(request) username = request.GET.get("username", None) ip_required = False username_required = False ip_and_username = False for param in lockout_paramaters: # hack: in works with all iterables, including strings # so this checks works with separate parameters # and with parameters combinations if "username" in param and "ip_address" in param: ip_and_username = True ip_required = True username_required = True break if "username" in param: username_required = True elif "ip_address" in param: ip_required = True ip_or_username = not ip_and_username and ip_required and username_required if not ip_required: ip = None if not username_required: username = None if not ip and not username: return 0 # We don't want to reset everything, if there is some wrong request parameter # TODO: reset based on user_agent? return reset(ip, username, ip_or_username) django-axes-7.0.1/codecov.yml000066400000000000000000000003241472335743500161000ustar00rootroot00000000000000coverage: status: patch: off project: default: # Minimum test coverage required for pass target: 90% # Maximum test coverage change allowed for pass threshold: 20% django-axes-7.0.1/docs/000077500000000000000000000000001472335743500146645ustar00rootroot00000000000000django-axes-7.0.1/docs/10_changelog.rst000066400000000000000000000000531472335743500176430ustar00rootroot00000000000000.. changelog: .. include:: ../CHANGES.rst django-axes-7.0.1/docs/1_requirements.rst000066400000000000000000000012211472335743500203550ustar00rootroot00000000000000.. _requirements: Requirements ============ Axes requires a supported Django version and runs on Python versions 3.9 and above. Refer to the project source code repository in `GitHub `_ and see the `pyproject.toml file `_ and `Python package definition `_ to check if your Django and Python version are supported. The `GitHub Actions builds `_ test Axes compatibility with the Django master branch for future compatibility as well. django-axes-7.0.1/docs/2_installation.rst000066400000000000000000000267601472335743500203530ustar00rootroot00000000000000.. _installation: Installation ============ Axes is easy to install from the PyPI package:: $ pip install django-axes[ipware] # use django-ipware for resolving client IP addresses OR $ pip install django-axes # implement and configure custom AXES_CLIENT_IP_CALLABLE After installing the package, the project settings need to be configured. **1.** Add ``axes`` to your ``INSTALLED_APPS``:: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # Axes app can be in any position in the INSTALLED_APPS list. 'axes', ] **2.** Add ``axes.backends.AxesStandaloneBackend`` to the top of ``AUTHENTICATION_BACKENDS``:: AUTHENTICATION_BACKENDS = [ # AxesStandaloneBackend should be the first backend in the AUTHENTICATION_BACKENDS list. 'axes.backends.AxesStandaloneBackend', # Django ModelBackend is the default authentication backend. 'django.contrib.auth.backends.ModelBackend', ] For backwards compatibility, ``AxesBackend`` can be used in place of ``AxesStandaloneBackend``. The only difference is that ``AxesBackend`` also provides the permissions-checking functionality of Django's ``ModelBackend`` behind the scenes. We recommend using ``AxesStandaloneBackend`` if you have any custom logic to override Django's standard permissions checks. **3.** Add ``axes.middleware.AxesMiddleware`` to your list of ``MIDDLEWARE``:: MIDDLEWARE = [ # The following is the list of default middleware in new Django projects. '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', # AxesMiddleware should be the last middleware in the MIDDLEWARE list. # It only formats user lockout messages and renders Axes lockout responses # on failed user authentication attempts from login views. # If you do not want Axes to override the authentication response # you can skip installing the middleware and use your own views. 'axes.middleware.AxesMiddleware', ] **4.** Run ``python manage.py check`` to check the configuration. **5.** Run ``python manage.py migrate`` to sync the database. Axes is now functional with the default settings and is saving user attempts into your database and locking users out if they exceed the maximum attempts. You should use the ``python manage.py check`` command to verify the correct configuration in development, staging, and production environments. It is probably best to use this step as part of your regular CI workflows to verify that your project is not misconfigured. Axes uses checks to verify your Django settings configuration for security and functionality. Many people have different configurations for their development and production environments, and running the application with misconfigured settings can prevent security features from working. Version 7 breaking changes and upgrading from django-axes version 6 ------------------------------------------------------------------- If you use ``settings.AXES_COOLOFF_TIME`` for configuring a callable that returns the cooloff time, it needs to accept at minimum a ``request`` argument of type ``HttpRequest`` from version 7 onwards. Example: ``AXES_COOLOFF_TIME = lambda request: timedelta(hours=2)`` (new call signature) instead of ``AXES_COOLOFF_TIME = lambda: timedelta(hours=2)`` (old cal signature). Please see configuration documentation and `jazzband/django-axes#1222 `_ for reference. Version 6 breaking changes and upgrading from django-axes version 5 ------------------------------------------------------------------- If you have not specialized ``django-axes`` configuration in any way you do not have to update any of the configuration. The instructions apply to users who have configured ``django-axes`` in their projects and have used flags that are deprecated. The deprecated flags will be removed in the future but are compatible for at least version 6.0 of ``django-axes``. The following flags and configuration have changed: ``django-ipware`` has become an optional dependency. To keep old behaviour, use ``pip install django-axes[ipware]`` in your install script or use ``django-axes[ipware]`` in your requirements file(s) instead of plain ``django-axes``. The new ``django-axes`` package does not include ``django-ipware`` by default but does use ``django-ipware`` if it is installed and no callables for IP address resolution are configured with the ``settings.AXES_CLIENT_IP_CALLABLE`` configuration flag. ``django-ipware`` related flags have changed names. The old flags have been deprecated and will be removed in the future. To keep old behaviour, rename them in your settings file: - ``settings.AXES_PROXY_ORDER`` is now ``settings.AXES_IPWARE_PROXY_ORDER``, - ``settings.AXES_PROXY_COUNT`` is now ``settings.AXES_IPWARE_PROXY_COUNT``, - ``settings.AXES_PROXY_TRUSTED_IPS`` is now ``settings.AXES_IPWARE_PROXY_TRUSTED_IPS``, and - ``settings.AXES_META_PRECEDENCE_ORDER`` is now ``settings.AXES_IPWARE_META_PRECEDENCE_ORDER``. ``settings.AXES_LOCKOUT_PARAMETERS`` configuration flag has been added which supersedes the following configuration keys: #. No configuration for failure tracking in the following items (default behaviour). #. ``settings.AXES_ONLY_USER_FAILURES``, #. ``settings.AXES_LOCK_OUT_BY_COMBINATION_USER_AND_IP``, #. ``settings.AXES_LOCK_OUT_BY_USER_OR_IP``, and #. ``settings.AXES_USE_USER_AGENT``. To keep old behaviour with the new flag, configure the following: #. If you did not use any flags, use ``settings.AXES_LOCKOUT_PARAMETERS = ["ip_address"]``, #. If you used ``settings.AXES_ONLY_USER_FAILURES``, use ``settings.AXES_LOCKOUT_PARAMETERS = ["username"]``, #. If you used ``settings.AXES_LOCK_OUT_BY_USER_OR_IP``, use ``settings.AXES_LOCKOUT_PARAMETERS = ["username", "ip_address"]``, and #. If you used ``settings.AXES_LOCK_OUT_BY_COMBINATION_USER_AND_IP``, use ``settings.AXES_LOCKOUT_PARAMETERS = [["username", "ip_address"]]``, #. If you used ``settings.AXES_USE_USER_AGENT``, add ``"user_agent"`` to your list(s) of lockout parameters. #. ``settings.AXES_USE_USER_AGENT`` would become ``settings.AXES_LOCKOUT_PARAMETERS = [["ip_address", "user_agent"]]`` #. ``settings.AXES_USE_USER_AGENT`` with ``settings.AXES_ONLY_USER_FAILURES`` would become ``settings.AXES_LOCKOUT_PARAMETERS = [["username", "user_agent"]]`` #. ``settings.AXES_USE_USER_AGENT`` with ``settings.AXES_LOCK_OUT_BY_USER_OR_IP`` would become ``settings.AXES_LOCKOUT_PARAMETERS = [["ip_address", "user_agent"], "username"]`` #. ``settings.AXES_USE_USER_AGENT`` with ``settings.AXES_LOCK_OUT_BY_COMBINATION_USER_AND_IP`` would become ``settings.AXES_LOCKOUT_PARAMETERS = [["ip_address", "user_agent", "username"]]`` #. Other combinations of flags were previously not considered; the flags had precedence over each other as described in the documentation but were less-than-trivial to understand in their previous form. The new form is more explicit and flexible, although it requires more in-depth configuration. The new lockout parameters define a combined list of attributes to consider when tracking failed authentication attempts. They can be any combination of ``username``, ``ip_address`` or ``user_agent`` in a list of strings or list of lists of strings. The attributes defined in the lists are combined and saved into the database, cache, or other backend for failed logins. The semantics of the evaluation are available in the documentation and ``axes.helpers.get_client_parameters`` callable. ``settings.AXES_HTTP_RESPONSE_CODE`` default has been changed from ``403`` (Forbidden) to ``429`` (Too Many Requests). To keep the old behavior, set ``settings.AXES_HTTP_RESPONSE_CODE = 403`` in your settings. ``axes.handlers.base.AxesBaseHandler.is_admin_site`` has been deprecated due to misleading naming in favour of better-named ``axes.handlers.base.AxesBaseHandler.is_admin_request``. The old implementation has been kept for backwards compatibility, but will be removed in the future. The old implementation checked if a request is NOT made for an admin site if ``settings.AXES_ONLY_ADMIN_SITE`` was set. The new implementation correctly checks if a request is made for an admin site. ``axes.handlers.cache.AxesCacheHandler`` has been updated to use atomic ``cache.incr`` calls instead of old ``cache.set`` calls in authentication failure tracking to enable better parallel backend support for atomic cache backends like Redis and Memcached. Disabling Axes system checks ---------------------------- If you are implementing custom authentication, request middleware, or signal handlers the Axes checks system might generate false positives in the Django checks framework. You can silence the unnecessary warnings by using the following Django settings:: SILENCED_SYSTEM_CHECKS = ['axes.W003'] Axes has the following warnings codes built in: - ``axes.W001`` for invalid ``CACHES`` configuration. - ``axes.W002`` for invalid ``MIDDLEWARE`` configuration. - ``axes.W003`` for invalid ``AUTHENTICATION_BACKENDS`` configuration. - ``axes.W004`` for deprecated use of ``AXES_*`` setting flags. .. note:: Only disable the Axes system checks and warnings if you know what you are doing. The default checks are implemented to verify and improve your project's security and should only produce necessary warnings due to misconfigured settings. Disabling Axes components in tests ---------------------------------- If you get errors when running tests, try setting the ``AXES_ENABLED`` flag to ``False`` in your test settings:: AXES_ENABLED = False This disables the Axes middleware, authentication backend and signal receivers, which might fix errors with incompatible test configurations. Disabling atomic requests ------------------------- Django offers atomic database transactions that are tied to HTTP requests and toggled on and off with the ``ATOMIC_REQUESTS`` configuration. When ``ATOMIC_REQUESTS`` is set to ``True`` Django will always either perform all database read and write operations in one successful atomic transaction or in a case of failure roll them back, leaving no trace of the failed request in the database. However, sometimes Axes or another plugin can misbehave or not act correctly with other code, preventing the login mechanisms from working due to e.g. exception being thrown in some part of the code, preventing access attempts being logged to database with Axes or causing similar problems. If new attempts or log objects are not being correctly written to the Axes tables, it is possible to configure Django ``ATOMIC_REQUESTS`` setting to to ``False``:: ATOMIC_REQUESTS = False Please note that atomic requests are usually desirable when writing e.g. RESTful APIs, but sometimes it can be problematic and warrant a disable. Before disabling atomic requests or configuring them please read the relevant Django documentation and make sure you know what you are configuring rather than just toggling the flag on and off for testing. Also note that the cache backend can provide correct functionality with Memcached or Redis caches even with exceptions being thrown in the stack. django-axes-7.0.1/docs/3_usage.rst000066400000000000000000000126131472335743500167470ustar00rootroot00000000000000.. _usage: Usage ===== Once Axes is installed and configured, you can login and logout of your application via the ``django.contrib.auth`` views. The attempts will be logged and visible in the Access Attempts section in admin. Axes monitors the views by using the Django login and logout signals and locks out user attempts with a custom authentication backend that checks if requests are allowed to authenticate per the configured rules. By default, Axes will lock out repeated access attempts from the same IP address by monitoring login failures and storing them into the default database. Authenticating users -------------------- Axes needs a ``request`` attribute to be supplied to the stock Django ``authenticate`` method in the ``django.contrib.auth`` module in order to function correctly. If you wish to manually supply the argument to the calls to ``authenticate``, you can use the following snippet in your custom login views, tests, or other code:: def custom_login_view(request) username = ... password = ... user = authenticate( request=request, # this is the important custom argument username=username, password=password, ) if user is not None: login(request, user) If your test setup has problems with the ``request`` argument, you can either supply the argument manually with a blank `HttpRequest()`` object, disable Axes in the test setup by excluding ``axes`` from ``INSTALLED_APPS``, or leave out ``axes.backends.AxesBackend`` from your ``AUTHENTICATION_BACKENDS``. If you are using a 3rd party library that does not supply the ``request`` attribute when calling ``authenticate`` you can implement a customized backend that inherits from ``axes.backends.AxesBackend`` or other backend and overrides the ``authenticate`` method. Resetting attempts and lockouts ------------------------------- When Axes locks an IP address, it is not allowed to login again. You can allow IPs to attempt again by resetting (deleting) the relevant AccessAttempt records in the admin UI, CLI, or your own code. You can also configure automatic cool down periods, IP whitelists, and custom code and handler functions for resetting attempts. Please check out the configuration and customization documentation for further information. .. note:: Please note that the functionality describe here concerns the default database handler. If you have changed the default handler to another class such as the cache handler you have to implement custom reset commands. Resetting attempts from the Django admin UI ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Records can be easily deleted by using the Django admin application. Go to the admin UI and check the ``Access Attempt`` view. Select the attempts you wish the allow again and simply remove them. The blocked user will be allowed to log in again in accordance to the rules. Resetting attempts from command line ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Axes offers a command line interface with ``axes_reset``, ``axes_reset_ip``, ``axes_reset_username``, and ``axes_reset_ip_username`` management commands with the Django ``manage.py`` or ``django-admin`` command helpers: - ``python manage.py axes_reset`` will reset all lockouts and access records. - ``python manage.py axes_reset_ip [ip ...]`` will clear lockouts and records for the given IP addresses. - ``python manage.py axes_reset_username [username ...]`` will clear lockouts and records for the given usernames. - ``python manage.py axes_reset_ip_username [ip] [username]`` will clear lockouts and records for the given IP address and username. - ``python manage.py axes_reset_logs (age)`` will reset (i.e. delete) AccessLog records that are older than the given age where the default is 30 days. Resetting attempts programmatically by APIs ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ In your code, you can use the ``axes.utils.reset`` function. - ``reset()`` will reset all lockouts and access records. - ``reset(ip=ip)`` will clear lockouts and records for the given IP address. - ``reset(username=username)`` will clear lockouts and records for the given username. .. note:: Please note that if you give both ``username`` and ``ip`` arguments to ``reset`` that attempts that have both the set IP and username are reset. The effective behaviour of ``reset`` is to ``and`` the terms instead of ``or`` ing them. Data privacy and GDPR --------------------- Most European countries have quite strict laws regarding data protection and privacy. It's highly recommended and good practice to treat your sensitive user data with care. The general rule here is that you shouldn't store what you don't need. When dealing with brute-force protection, the IP address and the username (often the email address) are most crucial. Given that you can perfectly use `django-axes` without locking the user out by IP but by username, it does make sense to avoid storing the IP address at all. You can not lose what you don't have. You can adjust the AXES settings as follows:: # Block by Username only (i.e.: Same user different IP is still blocked, but different user same IP is not) AXES_LOCKOUT_PARAMETERS = ["username"] # Disable logging the IP-Address of failed login attempts by returning None for attempts to get the IP # Ignore assigning a lambda function to a variable for brevity AXES_CLIENT_IP_CALLABLE = lambda x: None # noqa: E731 django-axes-7.0.1/docs/4_configuration.rst000066400000000000000000001776141472335743500205300ustar00rootroot00000000000000.. _configuration: Configuration ============= Minimal Axes configuration is done with just ``settings.py`` updates. More advanced configuration and integrations might require updates on source code level depending on your project implementation. Configuring project settings ---------------------------- The following ``settings.py`` options are available for customizing Axes behaviour. +------------------------------------------------------+----------------------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | Variable | Default | Explanation | +======================================================+==============================================+===========================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================+ | AXES_ENABLED | True | Enable or disable Axes plugin functionality, for example in test runner setup | +------------------------------------------------------+----------------------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | AXES_FAILURE_LIMIT | 3 | The integer number of login attempts allowed before a record is created for the failed logins. This can also be a callable or a dotted path to callable that returns an integer and all of the following are valid: ``AXES_FAILURE_LIMIT = 42``, ``AXES_FAILURE_LIMIT = lambda *args: 42``, and ``AXES_FAILURE_LIMIT = 'project.app.get_login_failure_limit'``. | +------------------------------------------------------+----------------------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | AXES_LOCK_OUT_AT_FAILURE | True | After the number of allowed login attempts are exceeded, should we lock out this IP (and optional user agent)? | +------------------------------------------------------+----------------------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | AXES_COOLOFF_TIME | None | If set, defines a period of inactivity after which old failed login attempts will be cleared. Can be set to a Python timedelta object, an integer, a float, a callable, or a string path to a callable which takes the request as argument. If an integer or float, will be interpreted as a number of hours: ``AXES_COOLOFF_TIME = 2`` 2 hours, ``AXES_COOLOFF_TIME = 2.0`` 2 hours, 120 minutes, ``AXES_COOLOFF_TIME = 1.7`` 1.7 hours, 102 minutes, 6120 seconds | +------------------------------------------------------+----------------------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | AXES_ONLY_ADMIN_SITE | False | If ``True``, lock is only enabled for admin site. Admin site is determined by checking request path against the path of ``"admin:index"`` view. If admin urls are not registered in current urlconf, all requests will not be locked. | +------------------------------------------------------+----------------------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | AXES_ONLY_USER_FAILURES | False | DEPRECATED: USE ``AXES_LOCKOUT_PARAMETERS`` INSTEAD. If ``True``, only lock based on username, and never lock based on IP if attempts exceed the limit. Otherwise utilize the existing IP and user locking logic. | +------------------------------------------------------+----------------------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | AXES_ENABLE_ADMIN | True | If ``True``, admin views for access attempts and logins are shown in Django admin interface. | +------------------------------------------------------+----------------------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | AXES_LOCK_OUT_BY_COMBINATION_USER_AND_IP | False | DEPRECATED: USE ``AXES_LOCKOUT_PARAMETERS`` INSTEAD. If ``True``, prevent login from IP under a particular username if the attempt limit has been exceeded, otherwise lock out based on IP. | +------------------------------------------------------+----------------------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | AXES_LOCK_OUT_BY_USER_OR_IP | False | DEPRECATED: USE ``AXES_LOCKOUT_PARAMETERS`` INSTEAD. If ``True``, prevent login from if the attempt limit has been exceeded for IP or username. | +------------------------------------------------------+----------------------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | AXES_USE_USER_AGENT | False | DEPRECATED: USE ``AXES_LOCKOUT_PARAMETERS`` INSTEAD. If ``True``, lock out and log based on the IP address and the user agent. This means requests from different user agents but from the same IP are treated differently. This settings has no effect if the ``AXES_ONLY_USER_FAILURES`` setting is active. | +------------------------------------------------------+----------------------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | AXES_HANDLER | 'axes.handlers.database.AxesDatabaseHandler' | The path to the handler class to use. If set, overrides the default signal handler backend. Default: ``'axes.handlers.database.AxesDatabaseHandler'`` | +------------------------------------------------------+----------------------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | AXES_CACHE | 'default' | The name of the cache for Axes to use. | +------------------------------------------------------+----------------------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | AXES_LOCKOUT_TEMPLATE | None | If set, specifies a template to render when a user is locked out. Template receives ``cooloff_timedelta``, ``cooloff_time``, ``username`` and ``failure_limit`` as context variables. | +------------------------------------------------------+----------------------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | AXES_LOCKOUT_URL | None | If set, specifies a URL to redirect to on lockout. If both ``AXES_LOCKOUT_TEMPLATE`` and ``AXES_LOCKOUT_URL`` are set, the template will be used. | +------------------------------------------------------+----------------------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | AXES_VERBOSE | True | If ``True``, you'll see slightly more logging for Axes. | +------------------------------------------------------+----------------------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | AXES_USERNAME_FORM_FIELD | 'username' | The name of the form field that contains your users usernames. | +------------------------------------------------------+----------------------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | AXES_USERNAME_CALLABLE | None | A callable or a string path to callable that takes two arguments for user lookups: ``def get_username(request: HttpRequest, credentials: dict) -> str: ...``. This can be any callable such as ``AXES_USERNAME_CALLABLE = lambda request, credentials: 'username'`` or a full Python module path to callable such as ``AXES_USERNAME_CALLABLE = 'example.get_username``. The ``request`` is a HttpRequest like object and the ``credentials`` is a dictionary like object. ``credentials`` are the ones that were passed to Django ``authenticate()`` in the login flow. If no function is supplied, Axes fetches the username from the ``credentials`` or ``request.POST`` dictionaries based on ``AXES_USERNAME_FORM_FIELD``. | +------------------------------------------------------+----------------------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | AXES_WHITELIST_CALLABLE | None | A callable or a string path to callable that takes two arguments for whitelisting determination and returns True, if user should be whitelisted: ``def is_whitelisted(request: HttpRequest, credentials: dict) -> bool: ...``. This can be any callable similarly to ``AXES_USERNAME_CALLABLE``. | +------------------------------------------------------+----------------------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | AXES_LOCKOUT_CALLABLE | None | A callable or a string path to callable that takes two arguments returns a response. For example: ``def generate_lockout_response(request: HttpRequest, credentials: dict) -> HttpResponse: ...``. This can be any callable similarly to ``AXES_USERNAME_CALLABLE``. If not callable is defined, then the default implementation in ``axes.helpers.get_lockout_response`` is used for determining the correct lockout response that is sent to the requesting client. | +------------------------------------------------------+----------------------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | AXES_CLIENT_IP_CALLABLE | None | A callable or a string path to callable that takes HttpRequest as an argument and returns the resolved IP as a response. For example: ``def get_ip(request: HttpRequest) -> str: ...``. This can be any callable similarly to ``AXES_USERNAME_CALLABLE``. If not callable is defined, then the default implementation in ``axes.helpers.get_client_ip_address`` is used. | +------------------------------------------------------+----------------------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | AXES_PASSWORD_FORM_FIELD | 'password' | The name of the form or credentials field that contains your users password. | +------------------------------------------------------+----------------------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | AXES_SENSITIVE_PARAMETERS | ["username", "ip_address"] | Configures POST and GET parameter values (in addition to the value of ``AXES_PASSWORD_FORM_FIELD``) to mask in login attempt logging. Defaults enable privacy-by-design. | +------------------------------------------------------+----------------------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | AXES_NEVER_LOCKOUT_GET | False | If ``True``, Axes will never lock out HTTP GET requests. | +------------------------------------------------------+----------------------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | AXES_NEVER_LOCKOUT_WHITELIST | False | If ``True``, users can always login from whitelisted IP addresses. | +------------------------------------------------------+----------------------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | AXES_IP_BLACKLIST | None | An iterable of IPs to be blacklisted. Takes precedence over whitelists. For example: ``AXES_IP_BLACKLIST = ['0.0.0.0']``. | +------------------------------------------------------+----------------------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | AXES_IP_WHITELIST | None | An iterable of IPs to be whitelisted. For example: ``AXES_IP_WHITELIST = ['0.0.0.0']``. | +------------------------------------------------------+----------------------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | AXES_DISABLE_ACCESS_LOG | False | If ``True``, disable writing login and logout access logs to database, so the admin interface will not have user login trail for successful user authentication. | +------------------------------------------------------+----------------------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | AXES_ENABLE_ACCESS_FAILURE_LOG | False | If ``True``, enable writing login failure logs to database, so you will have every user login trail for unsuccessful user authentication. | +------------------------------------------------------+----------------------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | AXES_ACCESS_FAILURE_LOG_PER_USER_LIMIT | 1000 | Sets the number of failures to trail for each user. When the access failure log reach this number of records, an automatic removal is ran. | +------------------------------------------------------+----------------------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | AXES_RESET_ON_SUCCESS | False | If ``True``, a successful login will reset the number of failed logins. | +------------------------------------------------------+----------------------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | AXES_ALLOWED_CORS_ORIGINS | "*" | Configures lockout response CORS headers for XHR requests. | +------------------------------------------------------+----------------------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | AXES_HTTP_RESPONSE_CODE | 429 | Sets the http response code returned when ``AXES_FAILURE_LIMIT`` is reached. For example: ``AXES_HTTP_RESPONSE_CODE = 403`` | +------------------------------------------------------+----------------------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | AXES_RESET_COOL_OFF_ON_FAILURE_DURING_LOCKOUT | True | If ``True``, a failed login attempt during lockout will reset the cool off period. | +------------------------------------------------------+----------------------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | AXES_LOCKOUT_PARAMETERS | ["ip_address"] | A list of parameters that Axes uses to lock out users. It can also be callable, which takes an http request or AccesAttempt object and credentials and returns a list of parameters. Each parameter can be a string (a single parameter) or a list of strings (a combined parameter). For example, if you configure ``AXES_LOCKOUT_PARAMETERS = ["ip_address", ["username", "user_agent"]]``, axes will block clients by ip and/or username and user agent combination. See :ref:`customizing-lockout-parameters` for more details. | +------------------------------------------------------+----------------------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ The configuration option precedences for the access attempt monitoring are: 1. Default: only use IP address. 2. ``AXES_ONLY_USER_FAILURES``: only user username (``AXES_USE_USER_AGENT`` has no effect). 3. ``AXES_LOCK_OUT_BY_COMBINATION_USER_AND_IP``: use username and IP address. The ``AXES_USE_USER_AGENT`` setting can be used with username and IP address or just IP address monitoring, but does nothing when the ``AXES_ONLY_USER_FAILURES`` setting is set. Configuring reverse proxies --------------------------- Axes makes use of ``django-ipware`` package to detect the IP address of the client and uses some conservative configuration parameters by default for security. If you are using reverse proxies, you will need to configure one or more of the following settings to suit your set up to correctly resolve client IP addresses: * ``AXES_IPWARE_PROXY_COUNT``: The number of reverse proxies in front of Django as an integer. Default: ``None`` * ``AXES_IPWARE_META_PRECEDENCE_ORDER``: The names of ``request.META`` attributes as a tuple of strings to check to get the client IP address. Check the Django documentation for header naming conventions. Default: ``IPWARE_META_PRECEDENCE_ORDER`` setting if set, else ``('REMOTE_ADDR', )`` .. note:: For reverse proxies or e.g. Heroku, you might also want to fetch IP addresses from a HTTP header such as ``X-Forwarded-For``. To configure this, you can fetch IPs through the ``HTTP_X_FORWARDED_FOR`` key from the ``request.META`` property which contains all the HTTP headers in Django: .. code-block:: python # refer to the Django request and response objects documentation AXES_IPWARE_META_PRECEDENCE_ORDER = [ 'HTTP_X_FORWARDED_FOR', 'REMOTE_ADDR', ] Please note that proxies have different behaviours with the HTTP headers. Make sure that your proxy either strips the incoming value or otherwise makes sure of the validity of the header that is used because **any header values used in application configuration must be secure and trusted**. Otherwise the client can spoof IP addresses by just setting the header in their request and circumvent the IP address monitoring. Normal proxy server behaviours include overriding and appending the header value depending on the platform. Different platforms and gateway services utilize different headers, please refer to your deployment target documentation for up-to-date information on correct configuration. Configuring handlers -------------------- Axes uses handlers for processing signals and events from Django authentication and login attempts. The following handlers are implemented by Axes and can be configured with the ``AXES_HANDLER`` setting in project configuration: - ``axes.handlers.database.AxesDatabaseHandler`` logs attempts to database and creates AccessAttempt and AccessLog records that persist until removed from the database manually or automatically after their cool offs expire (checked on each login event). .. note:: To keep track of concurrent sessions AccessLog stores an hash of ``session_key`` if the session engine is configured. When no session engine is configured each access is stored with the same dummy value, then a logout will cause each *not-logged-out yet* logs to set a logout time. Due to how ``django.contrib.auth`` works it is not possible to correctly track the logout of a session in which the user changed its password, since it will create a new session without firing any logout event. - ``axes.handlers.cache.AxesCacheHandler`` only uses the cache for monitoring attempts and does not persist data other than in the cache backend; this data can be purged automatically depending on your cache configuration, so the cache handler is by design less secure than the database backend but offers higher throughput and can perform better with less bottlenecks. The cache backend should ideally be used with a central cache system such as a Memcached cache and should not rely on individual server state such as the local memory or file based cache does. - ``axes.handlers.dummy.AxesDummyHandler`` does nothing with attempts and can be used to disable Axes handlers if the user does not wish Axes to execute any logic on login signals. Please note that this effectively disables any Axes security features, and is meant to be used on e.g. local development setups and testing deployments where login monitoring is not wanted. To switch to cache based attempt tracking you can do the following:: AXES_HANDLER = 'axes.handlers.cache.AxesCacheHandler' See the cache configuration section for suitable cache backends. Configuring caches ------------------ If you are running Axes with the cache based handler on a deployment with a local Django cache, the Axes lockout and reset functionality might not work predictably if the cache in use is not the same for all the Django processes. Axes needs to cache access attempts application-wide, and e.g. the in-memory cache only caches access attempts per Django process, so for example resets made in the command line might not remove lock-outs that are in a separate process's in-memory cache such as the web server serving your login or admin page. To circumvent this problem, please use somethings else than ``django.core.cache.backends.dummy.DummyCache``, ``django.core.cache.backends.locmem.LocMemCache``, or ``django.core.cache.backends.filebased.FileBasedCache`` as your cache backend in Django cache ``BACKEND`` setting. If changing the ``'default'`` cache is not an option, you can add a cache specifically for use with Axes. This is a two step process. First you need to add an extra cache to ``CACHES`` with a name of your choice:: CACHES = { 'axes': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': '127.0.0.1:11211', } } The next step is to tell Axes to use this cache through adding ``AXES_CACHE`` to your ``settings.py`` file:: AXES_CACHE = 'axes' There are no known problems in e.g. ``MemcachedCache`` or Redis based caches. Configuring authentication backends ----------------------------------- Axes requires authentication backends to pass request objects with the authentication requests for performing monitoring. If you get ``AxesBackendRequestParameterRequired`` exceptions, make sure any libraries and middleware you use pass the request object. Please check the integration documentation for further information. Configuring 3rd party apps -------------------------- Refer to the integration documentation for Axes configuration with third party applications and plugins such as - Django REST Framework - Django Allauth - Django Simple Captcha django-axes-7.0.1/docs/5_customization.rst000066400000000000000000000171551472335743500205630ustar00rootroot00000000000000.. customization: Customization ============= Axes has multiple options for customization including customizing the attempt tracking and lockout handling logic and lockout response formatting. There are public APIs and the whole Axes tracking system is pluggable. You can swap the authentication backend, attempt tracker, failure handlers, database or cache backends and error formatters as you see fit. Check the API reference section for further inspiration on implementing custom authentication backends, middleware, and handlers. Axes uses the stock Django signals for login monitoring and can be customized and extended by using them correctly. Axes listens to the following signals from ``django.contrib.auth.signals`` to log access attempts: * ``user_logged_in`` * ``user_logged_out`` * ``user_login_failed`` You can also use Axes with your own auth module, but you'll need to ensure that it sends the correct signals in order for Axes to log the access attempts. Customizing authentication views -------------------------------- Here is a more detailed example of sending the necessary signals using and a custom auth backend at an endpoint that expects JSON requests. The custom authentication can be swapped out with ``authenticate`` and ``login`` from ``django.contrib.auth``, but beware that those methods take care of sending the necessary signals for you, and there is no need to duplicate them as per the example. ``example/forms.py``:: from django import forms class LoginForm(forms.Form): username = forms.CharField(max_length=128, required=True) password = forms.CharField(max_length=128, required=True) ``example/views.py``:: from django.contrib.auth import signals from django.http import JsonResponse, HttpResponse from django.utils.decorators import method_decorator from django.views import View from django.views.decorators.csrf import csrf_exempt from axes.decorators import axes_dispatch from example.forms import LoginForm from example.authentication import authenticate, login @method_decorator(axes_dispatch, name='dispatch') @method_decorator(csrf_exempt, name='dispatch') class Login(View): """ Custom login view that takes JSON credentials """ http_method_names = ['post'] def post(self, request): form = LoginForm(request.POST) if not form.is_valid(): # inform django-axes of failed login signals.user_login_failed.send( sender=User, request=request, credentials={ 'username': form.cleaned_data.get('username'), }, ) return HttpResponse(status=400) user = authenticate( request=request, username=form.cleaned_data.get('username'), password=form.cleaned_data.get('password'), ) if user is not None: login(request, user) signals.user_logged_in.send( sender=User, request=request, user=user, ) return JsonResponse({ 'message':'success' }, status=200) # inform django-axes of failed login signals.user_login_failed.send( sender=User, request=request, credentials={ 'username': form.cleaned_data.get('username'), }, ) return HttpResponse(status=403) ``urls.py``:: from django.urls import path from example.views import Login urlpatterns = [ path('login/', Login.as_view(), name='login'), ] Customizing username lookups ---------------------------- In special cases, you may have the need to modify the username that is submitted before attempting to authenticate. For example, adding namespacing or removing client-set prefixes. In these cases, ``axes`` needs to know how to make these changes so that it can correctly identify the user without any form cleaning or validation. This is where the ``AXES_USERNAME_CALLABLE`` setting comes in. You can define how to make these modifications in a callable that takes a request object and a credentials dictionary, and provide that callable to ``axes`` via this setting. For example, a function like this could take a post body with something like ``username='prefixed-username'`` and ``namespace=my_namespace`` and turn it into ``my_namespace-username``: ``example/utils.py``:: def get_username(request, credentials): username = credentials.get('username') namespace = credentials.get('namespace') return namespace + '-' + username ``settings.py``:: AXES_USERNAME_CALLABLE = 'example.utils.get_username' .. note:: You still have to make these modifications yourself before calling authenticate. If you want to re-use the same function for consistency, that's fine, but Axes does not inject these changes into the authentication flow for you. Customizing lockout responses ----------------------------- Axes can be configured with ``AXES_LOCKOUT_CALLABLE`` to return a custom lockout response when using the plugin with e.g. DRF (Django REST Framework) or other third party libraries which require specialized formats such as JSON or XML response formats or customized response status codes. An example of usage could be e.g. a custom view for processing lockouts. ``example/views.py``:: from django.http import JsonResponse def lockout(request, credentials, *args, **kwargs): return JsonResponse({"status": "Locked out due to too many login failures"}, status=403) ``settings.py``:: AXES_LOCKOUT_CALLABLE = "example.views.lockout" .. _customizing-lockout-parameters: Customizing lockout parameters ------------------------------ Axes can be configured with ``AXES_LOCKOUT_PARAMETERS`` to lock out users not only by IP address. ``AXES_LOCKOUT_PARAMETERS`` can be a list of strings (which represents a separate lockout parameter) or nested lists of strings (which represents lockout parameters used in combination) or a callable which accepts HttpRequest or AccessAttempt and credentials and returns a list of the same form as described earlier. Example ``AXES_LOCKOUT_PARAMETERS`` configuration: ``settings.py``:: AXES_LOCKOUT_PARAMETERS = ["ip_address", ["username", "user_agent"]] This way, axes will lock out users using ip_address and/or combination of username and user agent Example of callable ``AXES_LOCKOUT_PARAMETERS``: ``example/utils.py``:: from django.http import HttpRequest def get_lockout_parameters(request_or_attempt, credentials): if isinstance(request_or_attempt, HttpRequest): is_localhost = request.META.get("REMOTE_ADDR") == "127.0.0.1" else: is_localhost = request_or_attempt.ip_address == "127.0.0.1" if is_localhost: return ["username"] return ["ip_address", "username"] ``settings.py``:: AXES_LOCKOUT_PARAMETERS = "example.utils.get_lockout_parameters" This way, if client ip_address is localhost, axes will lockout client only by username. In other case, axes will lockout client by username and/or ip_address. Customizing client ip address lookups ------------------------------------- Axes can be configured with ``AXES_CLIENT_IP_CALLABLE`` to use custom client ip address lookup logic. ``example/utils.py``:: def get_client_ip(request): return request.META.get("REMOTE_ADDR") ``settings.py``:: AXES_CLIENT_IP_CALLABLE = "example.utils.get_client_ip" django-axes-7.0.1/docs/6_integration.rst000066400000000000000000000222711472335743500201720ustar00rootroot00000000000000.. _integration: Integration =========== Axes is intended to be pluggable and usable with custom authentication solutions. This document describes the integration with some popular 3rd party packages such as Django Allauth, Django REST Framework, and other tools. In the following table **Compatible** means that a component should be fully compatible out-of-the-box, **Functional** means that a component should be functional after configuration, and **Incompatible** means that a component has been reported as non-functional with Axes. ======================= ============= ============ ============ ============== Project Version Compatible Functional Incompatible ======================= ============= ============ ============ ============== Django REST Framework |check| Django Allauth |check| Django Simple Captcha |check| Django OAuth Toolkit |check| Django Reversion |check| Django Auth LDAP |check| ======================= ============= ============ ============ ============== .. |check| unicode:: U+2713 .. |lt| unicode:: U+003C .. |lte| unicode:: U+2264 .. |gte| unicode:: U+2265 .. |gt| unicode:: U+003E Please note that project compatibility depends on multiple different factors such as Django version, Axes version, and 3rd party package versions and their unique combinations per project. .. note:: This documentation is mostly provided by Axes users. If you have your own compatibility tweaks and customizations that enable you to use Axes with other tools or have better implementations than the solutions provided here, please do feel free to open an issue or a pull request in GitHub! Integration with Django Allauth ------------------------------- Axes relies on having login information stored under ``AXES_USERNAME_FORM_FIELD`` key both in ``request.POST`` and in ``credentials`` dict passed to ``user_login_failed`` signal. This is not the case with Allauth. Allauth always uses the ``login`` key in post POST data but it becomes ``username`` key in ``credentials`` dict in signal handler. To overcome this you need to use custom login form that duplicates the value of ``username`` key under a ``login`` key in that dict and set ``AXES_USERNAME_FORM_FIELD = 'login'``. You also need to decorate ``dispatch()`` and ``form_invalid()`` methods of the Allauth login view. ``settings.py``:: AXES_USERNAME_FORM_FIELD = 'login' ``example/forms.py``:: from allauth.account.forms import LoginForm class AxesLoginForm(LoginForm): """ Extended login form class that supplied the user credentials for Axes compatibility. """ def user_credentials(self): credentials = super().user_credentials() credentials['login'] = credentials.get('email') or credentials.get('username') return credentials ``example/urls.py``:: from django.utils.decorators import method_decorator from allauth.account.views import LoginView from axes.decorators import axes_dispatch from axes.decorators import axes_form_invalid from example.forms import AxesLoginForm LoginView.dispatch = method_decorator(axes_dispatch)(LoginView.dispatch) LoginView.form_invalid = method_decorator(axes_form_invalid)(LoginView.form_invalid) urlpatterns = [ # Override allauth default login view with a patched view path('accounts/login/', LoginView.as_view(form_class=AxesLoginForm), name='account_login'), path('accounts/', include('allauth.urls')), ] Integration with Django REST Framework -------------------------------------- .. warning:: The following guide only covers authentication schemes that rely on Django's ``authenticate()`` function. Other schemes (e.g. ``TokenAuthentication``) are currently not supported. Django Axes requires REST Framework to be connected via lockout signals for correct functionality. You can use the following snippet in your project signals such as ``example/signals.py``:: from django.dispatch import receiver from axes.signals import user_locked_out from rest_framework.exceptions import PermissionDenied @receiver(user_locked_out) def raise_permission_denied(*args, **kwargs): raise PermissionDenied("Too many failed login attempts") And then configure your application to load it in ``examples/apps.py``:: from django import apps class AppConfig(apps.AppConfig): name = "example" def ready(self): from example import signals # noqa Please check the Django signals documentation for more information: https://docs.djangoproject.com/en/3.2/topics/signals/ When a user login fails a signal is emitted and PermissionDenied raises a HTTP 403 reply which interrupts the login process. This functionality was handled in the middleware for a time, but that resulted in extra database requests being made for each and every web request, and was migrated to signals. Integration with Django Simple Captcha -------------------------------------- Axes supports Captcha with the Django Simple Captcha package in the following manner. ``settings.py``:: AXES_LOCKOUT_URL = '/locked' ``example/urls.py``:: url(r'^locked/$', locked_out, name='locked_out'), ``example/forms.py``:: class AxesCaptchaForm(forms.Form): captcha = CaptchaField() ``example/views.py``:: from axes.utils import reset_request from django.http.response import HttpResponseRedirect from django.shortcuts import render from django.urls import reverse_lazy from .forms import AxesCaptchaForm def locked_out(request): if request.POST: form = AxesCaptchaForm(request.POST) if form.is_valid(): reset_request(request) return HttpResponseRedirect(reverse_lazy('auth_login')) else: form = AxesCaptchaForm() return render(request, 'accounts/captcha.html', {'form': form}) ``example/templates/example/captcha.html``::
{% csrf_token %} {{ form.captcha.errors }} {{ form.captcha }}
Integration with Django OAuth Toolkit ------------------------------------- Django OAuth toolkit is not designed to work with Axes, but some users have reported that they have configured validator classes to function correctly. ``example/validators.py``:: from django.contrib.auth import authenticate from django.http import HttpRequest, QueryDict from oauth2_provider.oauth2_validators import OAuth2Validator from axes.helpers import get_client_ip_address, get_client_user_agent class AxesOAuth2Validator(OAuth2Validator): def validate_user(self, username, password, client, request, *args, **kwargs): """ Check username and password correspond to a valid and active User Set defaults for necessary request object attributes for Axes compatibility. The ``request`` argument is not a Django ``HttpRequest`` object. """ _request = request if request and not isinstance(request, HttpRequest): request = HttpRequest() request.uri = _request.uri request.method = request.http_method = _request.http_method request.META = request.headers = _request.headers request._params = _request._params request.decoded_body = _request.decoded_body request.axes_ip_address = get_client_ip_address(request) request.axes_user_agent = get_client_user_agent(request) body = QueryDict(str(_request.body), mutable=True) if request.method == 'GET': request.GET = body elif request.method == 'POST': request.POST = body user = authenticate(request=request, username=username, password=password) if user is not None and user.is_active: request = _request request.user = user return True return False ``settings.py``:: OAUTH2_PROVIDER = { 'OAUTH2_VALIDATOR_CLASS': 'example.validators.AxesOAuth2Validator', 'SCOPES': {'read': 'Read scope', 'write': 'Write scope'}, } Integration with Django Reversion --------------------------------- Django Reversion is not designed to work with Axes, but some users have reported that they have configured a workaround with a monkeypatch function that functions correctly. ``example/monkeypatch.py``:: from django.urls import resolve from reversion import views def _request_creates_revision(request): view_name = resolve(request.path_info).url_name if view_name and view_name.endswith('login'): return False return request.method not in ["OPTIONS", "GET", "HEAD"] views._request_creates_revision = _request_creates_revision django-axes-7.0.1/docs/7_architecture.rst000066400000000000000000000070151472335743500203310ustar00rootroot00000000000000.. _architecture: Architecture ============ Axes is based on the existing Django authentication backend architecture and framework for recognizing users and aims to be compatible with the stock design and implementation of Django while offering extensibility and configurability for using the Axes authentication monitoring and logging for users of the package as well as 3rd party package vendors such as Django REST Framework, Django Allauth, Python Social Auth and so forth. The development of custom 3rd party package support are active goals, but you should check the up-to-date documentation and implementation of Axes for current compatibility before using Axes with custom solutions and make sure that authentication monitoring is working correctly. This document describes the Django authentication flow and how Axes augments it to achieve authentication and login monitoring and lock users out on too many access attempts. Django Axes authentication flow ------------------------------- Axes offers a few additions to the Django authentication flow that implement the login monitoring and lockouts through a swappable **handler** API and configuration flags that users and package vendors can use to customize Axes or their own projects as they best see fit. The following diagram visualizes the Django login flow and highlights the following extra steps that Axes adds to it with the **1. Authentication backend**, **2. Signal receivers**, and **3. Middleware**. .. image:: images/flow.png :alt: Django Axes augmented authentication flow with custom authentication backend, signal receivers, and middleware When a user tries to log in in Django, the login is usually performed by running a number of authentication backends that check user login information by calling the ``authenticate`` function, which either returns a Django compatible ``User`` object or a ``None``. If an authentication backend does not approve a user login, it can raise a ``PermissionDenied`` exception, which immediately skips the rest of the authentication backends, triggers the ``user_login_failed`` signal, and then returns a ``None`` to the calling function, indicating that the login failed. Axes implements authentication blocking with the custom ``AxesBackend`` authentication backend which checks every request coming through the Django authentication flow and verifies they are not blocked, and allows the requests to go through if the check passes. If the authentication attempt matches a lockout rule, e.g. it is from a blacklisted IP or exceeds the maximum configured authentication attempts, it is blocked by raising the ``PermissionDenied`` exception in the backend. Axes monitors logins with the ``user_login_failed`` signal receiver and records authentication failures from both the ``AxesBackend`` and other authentication backends and tracks the failed attempts by tracking the attempt IP address, username, user agent, or all of them. If the lockout rules match, then Axes marks the request as locked by setting a special attribute into the request. The ``AxesMiddleware`` then processes the request, returning a lockout response to the user, if the flag has been set. Axes assumes that the login views either call the ``authenticate`` method to log in users or otherwise take care of notifying Axes of authentication attempts and failures the same way Django does via authentication signals. The login flows can be customized and the Axes authentication backend, middleware, and signal receivers can easily be swapped to alternative implementations. django-axes-7.0.1/docs/8_reference.rst000066400000000000000000000006261472335743500176070ustar00rootroot00000000000000.. _reference: API reference ============= Axes offers extensible APIs that you can customize to your liking. You can specialize the following base classes or alternatively use third party modules as long as they implement the following APIs. .. automodule:: axes.handlers.base :members: .. automodule:: axes.backends :members: :show-inheritance: .. automodule:: axes.middleware :members: django-axes-7.0.1/docs/9_contributing.rst000066400000000000000000000000641472335743500203550ustar00rootroot00000000000000.. _contributing: .. include:: ../CONTRIBUTING.rst django-axes-7.0.1/docs/Makefile000066400000000000000000000164021472335743500163270ustar00rootroot00000000000000# 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 https://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 coverage 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 " applehelp to make an Apple Help Book" @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)" @echo " coverage to run coverage check of 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/DjangoAxes.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/DjangoAxes.qhc" applehelp: $(SPHINXBUILD) -b applehelp $(ALLSPHINXOPTS) $(BUILDDIR)/applehelp @echo @echo "Build finished. The help book is in $(BUILDDIR)/applehelp." @echo "N.B. You won't be able to view it unless you put it in" \ "~/Library/Documentation/Help or install it in your application" \ "bundle." devhelp: $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp @echo @echo "Build finished." @echo "To view the help file:" @echo "# mkdir -p $$HOME/.local/share/devhelp/DjangoAxes" @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/DjangoAxes" @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." coverage: $(SPHINXBUILD) -b coverage $(ALLSPHINXOPTS) $(BUILDDIR)/coverage @echo "Testing of coverage in the sources finished, look at the " \ "results in $(BUILDDIR)/coverage/python.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." django-axes-7.0.1/docs/conf.py000066400000000000000000000077141472335743500161740ustar00rootroot00000000000000""" Sphinx documentation generator configuration. More information on the configuration options is available at: https://www.sphinx-doc.org/en/master/usage/configuration.html """ import sphinx_rtd_theme from pkg_resources import get_distribution import django from django.conf import settings settings.configure(INSTALLED_APPS=["django", "django.contrib.auth", "axes"], DEBUG=True) django.setup() # -- Extra custom configuration ------------------------------------------ title = "django-axes documentation" description = ("Keep track of failed login attempts in Django-powered sites.",) # -- General configuration ------------------------------------------------ # 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"] # Add any paths that contain templates here, relative to this directory. templates_path = ["_templates"] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: source_suffix = ['.rst', '.md'] source_suffix = ".rst" # The master toctree document. master_doc = "index" # General information about the project. project = "django-axes" copyright = "2016, Jazzband" author = "Jazzband" # The full version, including alpha/beta/rc tags. release = get_distribution("django-axes").version # The short X.Y version. version = ".".join(release.split(".")[:2]) # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # # This is also used if you do content translation via gettext catalogs. # Usually you set "language" from the command line for these cases. language = None # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ["_build"] # The name of the Pygments (syntax highlighting) style to use. pygments_style = "sphinx" # If true, `todo` and `todoList` produce output, else they produce nothing. todo_include_todos = 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 = "sphinx_rtd_theme" # Add any paths that contain custom themes here, relative to this directory. html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] # 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"] # Custom sidebar templates, maps document names to template names. html_sidebars = { "**": ["globaltoc.html", "relations.html", "sourcelink.html", "searchbox.html"] } # Output file base name for HTML help builder. htmlhelp_basename = "DjangoAxesdoc" # -- Options for LaTeX output --------------------------------------------- latex_elements = { "papersize": "a4paper", "pointsize": "12pt", "preamble": "", "figure_align": "htbp", } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto, manual, or own class]). latex_documents = [(master_doc, "DjangoAxes.tex", title, author, "manual")] # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [(master_doc, "djangoaxes", description, [author], 1)] # -- 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 = [ ( master_doc, "DjangoAxes", title, author, "DjangoAxes", description, "Miscellaneous", ) ] django-axes-7.0.1/docs/images/000077500000000000000000000000001472335743500161315ustar00rootroot00000000000000django-axes-7.0.1/docs/images/flow.png000066400000000000000000004036451472335743500176220ustar00rootroot00000000000000PNG  IHDR5{ }zTXtmxGraphModelMWǮ캎 ts:9L.sghJiY$μj膴ʫ, ~` A>GW8?WY_:UF?QR바?05kgu ȿ>SjbZ]`ɂ*?۪y-dI30C wg'伕=0Hwc-5T9o)OFLQ%r( *}"gu[y=w"]禛ZQ\\,2 981r' sf~fF#F?Js OLK#T䰫\@|j+EfpQȖJq?!ˆUή0Ϗ`#:R*IP>7 s9)RZJP?ey©J9KMQUvOn7i체K 4~VЌדRVKig9 |aXƹ?hT 7rv}q1XOfY^(຋Qh5>_kJ5klYU<{D(ό@C/ 2@!iiWC2A ]*.nA~>1@S0! U̹)O,wXr~ݒ`z‚tQ=h10T!gⱙu}`ONИa,8 8HҦν)N2)y*-6t=hOeaH9p/Me\2oF:f@1VFXwpٺQF9%ZE 8hj!) ᲟTq ~y6myf{j9\6N `&A"DƣmS^S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4%Ƌ5?ߤ yoDNOO;RZ9CASީ1i{2 ˆ0D6W䕤f"숺$&2$1ӝP4Q, 5)*H4.{q`!yn ؋k{}_~p0Ajdk !H!B/#5Om؀,IM @pR Rdp(װ <'5"DcdNIjnԋ$5RcI p,;P&J"/#5 t)yR2k( ab=0Ԥ]DDE}k"Z"̻!z3 n#Rؐ"wPb4 5Wr]?]E+O+gаoy\ {df._19r|V6ϑ3#`2Rè=B˷^1M}3ߞ%9o_q*Jɱ CH މ:P[E&8"ᕸM}~m_HᨌtveR22n oiuC&X^ !.&IM̒GjDlgH4&iU9C|d/}Mh"&ɛAYNyH+ӹ~@)}27,,Rx#8€DW|P'Q`Q  'x^_ʏ!KCY( "ouDGy HY9 ci"ϛn):Is3'l4k2oBښ 55Y*.껝chsyL{L{~ݜ޷Ho[dZM&أ}3@eK?GoEp83k5RI$ "5QyhpO DojJ\ qq|:!o0##'5S8TXo5$- CX ef摚 a߅VF"Hq~˳Z\읷B_7(Ae5 Pddi<: !^ uaF~<K%:P{K gC 'yl15s)M;I&$12sj{}cpL5wVG9ɮMC];$x:qr7zT amfT''xQ.R3.. V@6$1Eup;)hKGDODBdd; oØeJ`- ^7LIruwHw;|_Ew 2i\G-;vwR)Ó@Yk-$1+xOw%0- _H^xq.{i>{H d[o];)6IH K.aH`ULj7\-r^f"!g}v&ɜc뒜$1|g\)J`]!o;_^{k￿;([J %{ ({dk}⫯ʔOì߸$Lj:33&ʤ&?vƖ-%؝x9x+R(INmƟ\J`H]/^vzIENDB`django-axes-7.0.1/docs/index.rst000066400000000000000000000005441472335743500165300ustar00rootroot00000000000000.. _index: django-axes documentation ========================= Contents -------- .. toctree:: :maxdepth: 2 :numbered: 1 1_requirements 2_installation 3_usage 4_configuration 5_customization 6_integration 7_architecture 8_reference 9_contributing 10_changelog Indices and tables ------------------ * :ref:`search` django-axes-7.0.1/manage.py000066400000000000000000000003711472335743500155370ustar00rootroot00000000000000#!/usr/bin/env python 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) django-axes-7.0.1/mypy.ini000066400000000000000000000001511472335743500154300ustar00rootroot00000000000000[mypy] python_version = 3.9 ignore_missing_imports = True [mypy-axes.migrations.*] ignore_errors = True django-axes-7.0.1/pyproject.toml000066400000000000000000000024011472335743500166450ustar00rootroot00000000000000[build-system] requires = ["setuptools>=30.3.0", "wheel", "setuptools_scm"] [tool.pytest.ini_options] testpaths = "tests" addopts = "--cov axes --cov-append --cov-branch --cov-report term-missing --cov-report=xml" DJANGO_SETTINGS_MODULE = "tests.settings" [tool.tox] legacy_tox_ini = """ [tox] envlist = py{39,310,311,312}-dj42 py{310,311,312}-dj50 py{310,311,312,313}-dj51 py311-djmain py311-djqa [gh-actions] python = 3.9: py39 3.10: py310 3.11: py311 3.12: py312 3.13: py313 [gh-actions:env] DJANGO = 4.2: dj42 5.0: dj50 5.1: dj51 main: djmain qa: djqa # Normal test environment runs pytest which orchestrates other tools [testenv] deps = -r requirements-test.txt dj42: django>=4.1,<4.2 dj50: django>=5.0,<5.1 dj51: django>=5.1,<5.2 djmain: https://github.com/django/django/archive/main.tar.gz usedevelop = true commands = pytest setenv = PYTHONDONTWRITEBYTECODE=1 # Django development version is allowed to fail the test matrix ignore_outcome = djmain: True ignore_errors = djmain: True # QA runs type checks, linting, and code formatting checks [testenv:py313-djqa] deps = -r requirements-qa.txt commands = mypy axes prospector black -t py39 --check --diff axes """ django-axes-7.0.1/requirements-qa.txt000066400000000000000000000000571472335743500176210ustar00rootroot00000000000000black==24.10.0 mypy==1.13.0 prospector==1.12.1 django-axes-7.0.1/requirements-test.txt000066400000000000000000000001631472335743500201750ustar00rootroot00000000000000-e . django-ipware>=3 coverage==7.6.4 pytest==8.3.3 pytest-cov==5.0.0 pytest-django==4.9.0 pytest-subtests==0.13.1 django-axes-7.0.1/requirements.txt000066400000000000000000000001311472335743500172130ustar00rootroot00000000000000-e . -r requirements-qa.txt -r requirements-test.txt sphinx_rtd_theme==3.0.1 tox==4.23.2 django-axes-7.0.1/setup.py000066400000000000000000000045621472335743500154550ustar00rootroot00000000000000#!/usr/bin/env python from setuptools import setup, find_packages setup( name="django-axes", description="Keep track of failed login attempts in Django-powered sites.", long_description="\n".join( [ open("README.rst", encoding="utf-8").read(), open("CHANGES.rst", encoding="utf-8").read(), ] ), keywords="authentication django pci security", author=", ".join( [ "Josh VanderLinden", "Philip Neustrom", "Michael Blume", "Alex Clark", "Camilo Nova", "Aleksi Hakli", ] ), author_email="security@jazzband.co", maintainer="Jazzband", maintainer_email="security@jazzband.co", url="https://github.com/jazzband/django-axes", project_urls={ "Documentation": "https://django-axes.readthedocs.io/", "Source": "https://github.com/jazzband/django-axes", "Tracker": "https://github.com/jazzband/django-axes/issues", }, license="MIT", package_dir={"axes": "axes"}, use_scm_version=True, setup_requires=["setuptools_scm"], python_requires=">=3.7", install_requires=[ "django>=3.2", "asgiref>=3.6.0", ], extras_require={ "ipware": "django-ipware>=3", }, include_package_data=True, packages=find_packages(exclude=["tests"]), classifiers=[ "Development Status :: 5 - Production/Stable", "Environment :: Web Environment", "Environment :: Plugins", "Framework :: Django", "Framework :: Django :: 4.2", "Framework :: Django :: 5.0", "Framework :: Django :: 5.1", "Intended Audience :: Developers", "Intended Audience :: System Administrators", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Programming Language :: Python", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", "Programming Language :: Python :: Implementation :: CPython", "Topic :: Internet :: Log Analysis", "Topic :: Security", "Topic :: System :: Logging", ], zip_safe=False, ) django-axes-7.0.1/tests/000077500000000000000000000000001472335743500150765ustar00rootroot00000000000000django-axes-7.0.1/tests/__init__.py000066400000000000000000000000001472335743500171750ustar00rootroot00000000000000django-axes-7.0.1/tests/base.py000066400000000000000000000136401472335743500163660ustar00rootroot00000000000000from random import choice from string import ascii_letters, digits from time import sleep from django.contrib.auth import get_user_model from django.http import HttpRequest from django.test import TestCase from django.urls import reverse from django.utils.timezone import now from axes.conf import settings from axes.helpers import ( get_cache, get_client_http_accept, get_client_ip_address, get_client_path_info, get_client_user_agent, get_cool_off, get_credentials, get_failure_limit, ) from axes.models import AccessAttempt, AccessLog, AccessFailureLog from axes.utils import reset def custom_failure_limit(request, credentials): return 3 class AxesTestCase(TestCase): """ Test case using custom settings for testing. """ VALID_USERNAME = "axes-valid-username" VALID_PASSWORD = "axes-valid-password" VALID_EMAIL = "axes-valid-email@example.com" VALID_USER_AGENT = "axes-user-agent" VALID_IP_ADDRESS = "127.0.0.1" INVALID_USERNAME = "axes-invalid-username" INVALID_PASSWORD = "axes-invalid-password" INVALID_EMAIL = "axes-invalid-email@example.com" LOCKED_MESSAGE = "Account locked: too many login attempts." LOGOUT_MESSAGE = "Logged out" LOGIN_FORM_KEY = '' STATUS_SUCCESS = 200 ALLOWED = 302 BLOCKED = 429 def setUp(self): """ Create a valid user for login. """ self.username = self.VALID_USERNAME self.password = self.VALID_PASSWORD self.email = self.VALID_EMAIL self.ip_address = self.VALID_IP_ADDRESS self.user_agent = self.VALID_USER_AGENT self.path_info = reverse("admin:login") self.user = get_user_model().objects.create_superuser( username=self.username, password=self.password, email=self.email ) self.request = HttpRequest() self.request.method = "POST" self.request.META["REMOTE_ADDR"] = self.ip_address self.request.META["HTTP_USER_AGENT"] = self.user_agent self.request.META["PATH_INFO"] = self.path_info self.request.axes_attempt_time = now() self.request.axes_ip_address = get_client_ip_address(self.request) self.request.axes_user_agent = get_client_user_agent(self.request) self.request.axes_path_info = get_client_path_info(self.request) self.request.axes_http_accept = get_client_http_accept(self.request) self.request.axes_failures_since_start = None self.request.axes_locked_out = False self.credentials = get_credentials(self.username) def tearDown(self): get_cache().clear() def get_kwargs_with_defaults(self, **kwargs): defaults = { "user_agent": self.user_agent, "ip_address": self.ip_address, "username": self.username, } defaults.update(kwargs) return defaults def create_attempt(self, **kwargs): kwargs = self.get_kwargs_with_defaults(**kwargs) kwargs.setdefault("failures_since_start", 1) return AccessAttempt.objects.create(**kwargs) def create_log(self, **kwargs): return AccessLog.objects.create(**self.get_kwargs_with_defaults(**kwargs)) def create_failure_log(self, **kwargs): return AccessFailureLog.objects.create(**self.get_kwargs_with_defaults(**kwargs)) def reset(self, ip=None, username=None): return reset(ip, username) def login( self, is_valid_username=False, is_valid_password=False, remote_addr=None, **kwargs ): """ Login a user. A valid credential is used when is_valid_username is True, otherwise it will use a random string to make a failed login. """ if is_valid_username: username = self.VALID_USERNAME else: username = "".join(choice(ascii_letters + digits) for _ in range(10)) if is_valid_password: password = self.VALID_PASSWORD else: password = self.INVALID_PASSWORD post_data = {"username": username, "password": password, **kwargs} return self.client.post( reverse("admin:login"), post_data, REMOTE_ADDR=remote_addr or self.ip_address, HTTP_USER_AGENT=self.user_agent, ) def logout(self): return self.client.post( reverse("admin:logout"), REMOTE_ADDR=self.ip_address, HTTP_USER_AGENT=self.user_agent, ) def check_login(self): response = self.login(is_valid_username=True, is_valid_password=True) self.assertNotContains( response, self.LOGIN_FORM_KEY, status_code=self.ALLOWED, html=True ) def almost_lockout(self): for _ in range(1, get_failure_limit(None, None)): response = self.login() self.assertContains(response, self.LOGIN_FORM_KEY, html=True) def lockout(self): self.almost_lockout() return self.login() def check_lockout(self): response = self.lockout() if settings.AXES_LOCK_OUT_AT_FAILURE == True: self.assertContains(response, self.LOCKED_MESSAGE, status_code=self.BLOCKED) else: self.assertNotContains( response, self.LOCKED_MESSAGE, status_code=self.STATUS_SUCCESS ) def cool_off(self): sleep(get_cool_off().total_seconds()) def check_logout(self): response = self.logout() self.assertContains( response, self.LOGOUT_MESSAGE, status_code=self.STATUS_SUCCESS ) def check_handler(self): """ Check a handler and its basic functionality with lockouts, cool offs, login, and logout. This is a check that is intended to successfully run for each and every new handler. """ self.check_lockout() self.cool_off() self.check_login() self.check_logout() django-axes-7.0.1/tests/settings.py000066400000000000000000000042771472335743500173220ustar00rootroot00000000000000DATABASES = {"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}} CACHES = { "default": { # This cache backend is OK to use in development and testing # but has the potential to break production setups with more than on process # due to each process having their own local memory based cache "BACKEND": "django.core.cache.backends.locmem.LocMemCache" } } SITE_ID = 1 MIDDLEWARE = [ "django.middleware.common.CommonMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "axes.middleware.AxesMiddleware", ] AUTHENTICATION_BACKENDS = [ "axes.backends.AxesStandaloneBackend", "django.contrib.auth.backends.ModelBackend", ] # Use MD5 for tests as it is considerably faster than other options # note that this should never be used in any online setting # where users actually log in to the system due to easy exploitability PASSWORD_HASHERS = ["django.contrib.auth.hashers.MD5PasswordHasher"] ROOT_URLCONF = "tests.urls" INSTALLED_APPS = [ "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.sites", "django.contrib.messages", "django.contrib.admin", "axes", ] 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", ] }, } ] LOGGING = { "version": 1, "disable_existing_loggers": False, "handlers": {"console": {"class": "logging.StreamHandler"}}, "loggers": {"axes": {"handlers": ["console"], "level": "INFO", "propagate": False}}, } SECRET_KEY = "too-secret-for-test" USE_I18N = False USE_TZ = False LOGIN_REDIRECT_URL = "/admin/" AXES_FAILURE_LIMIT = 10 DEFAULT_AUTO_FIELD = "django.db.models.AutoField" django-axes-7.0.1/tests/test_admin.py000066400000000000000000000022501472335743500175760ustar00rootroot00000000000000from contextlib import suppress from importlib import reload from django.contrib import admin from django.test import override_settings import axes.admin from axes.models import AccessAttempt, AccessLog, AccessFailureLog from tests.base import AxesTestCase class AxesEnableAdminFlag(AxesTestCase): def setUp(self): with suppress(admin.sites.NotRegistered): admin.site.unregister(AccessAttempt) with suppress(admin.sites.NotRegistered): admin.site.unregister(AccessLog) with suppress(admin.sites.NotRegistered): admin.site.unregister(AccessFailureLog) @override_settings(AXES_ENABLE_ADMIN=False) def test_disable_admin(self): reload(axes.admin) self.assertFalse(admin.site.is_registered(AccessAttempt)) self.assertFalse(admin.site.is_registered(AccessLog)) self.assertFalse(admin.site.is_registered(AccessFailureLog)) def test_enable_admin_by_default(self): reload(axes.admin) self.assertTrue(admin.site.is_registered(AccessAttempt)) self.assertTrue(admin.site.is_registered(AccessLog)) self.assertTrue(admin.site.is_registered(AccessFailureLog)) django-axes-7.0.1/tests/test_attempts.py000066400000000000000000000136631472335743500203610ustar00rootroot00000000000000from unittest.mock import patch from django.http import HttpRequest from django.test import override_settings, RequestFactory from django.utils.timezone import now from axes.attempts import get_cool_off_threshold from axes.models import AccessAttempt from axes.utils import reset, reset_request from tests.base import AxesTestCase class GetCoolOffThresholdTestCase(AxesTestCase): @override_settings(AXES_COOLOFF_TIME=42) def test_get_cool_off_threshold(self): timestamp = now() request = RequestFactory().post("/") with patch("axes.attempts.now", return_value=timestamp): request.axes_attempt_time = timestamp threshold_now = get_cool_off_threshold(request) request.axes_attempt_time = None threshold_none = get_cool_off_threshold(request) self.assertEqual(threshold_now, threshold_none) @override_settings(AXES_COOLOFF_TIME=None) def test_get_cool_off_threshold_error(self): with self.assertRaises(TypeError): get_cool_off_threshold() class ResetTestCase(AxesTestCase): def test_reset(self): self.create_attempt() reset() self.assertFalse(AccessAttempt.objects.count()) def test_reset_ip(self): self.create_attempt(ip_address=self.ip_address) reset(ip=self.ip_address) self.assertFalse(AccessAttempt.objects.count()) def test_reset_username(self): self.create_attempt(username=self.username) reset(username=self.username) self.assertFalse(AccessAttempt.objects.count()) class ResetResponseTestCase(AxesTestCase): USERNAME_1 = "foo_username" USERNAME_2 = "bar_username" IP_1 = "127.1.0.1" IP_2 = "127.1.0.2" def setUp(self): super().setUp() self.create_attempt() self.create_attempt(username=self.USERNAME_1, ip_address=self.IP_1) self.create_attempt(username=self.USERNAME_1, ip_address=self.IP_2) self.create_attempt(username=self.USERNAME_2, ip_address=self.IP_1) self.create_attempt(username=self.USERNAME_2, ip_address=self.IP_2) self.request = HttpRequest() def test_reset(self): reset_request(self.request) self.assertEqual(AccessAttempt.objects.count(), 5) def test_reset_ip(self): self.request.META["REMOTE_ADDR"] = self.IP_1 reset_request(self.request) self.assertEqual(AccessAttempt.objects.count(), 3) def test_reset_username(self): self.request.GET["username"] = self.USERNAME_1 reset_request(self.request) self.assertEqual(AccessAttempt.objects.count(), 5) def test_reset_ip_username(self): self.request.GET["username"] = self.USERNAME_1 self.request.META["REMOTE_ADDR"] = self.IP_1 reset_request(self.request) self.assertEqual(AccessAttempt.objects.count(), 3) @override_settings(AXES_LOCKOUT_PARAMETERS=["username"]) def test_reset_user_failures(self): reset_request(self.request) self.assertEqual(AccessAttempt.objects.count(), 5) @override_settings(AXES_LOCKOUT_PARAMETERS=["username"]) def test_reset_ip_user_failures(self): self.request.META["REMOTE_ADDR"] = self.IP_1 reset_request(self.request) self.assertEqual(AccessAttempt.objects.count(), 5) @override_settings(AXES_LOCKOUT_PARAMETERS=["username"]) def test_reset_username_user_failures(self): self.request.GET["username"] = self.USERNAME_1 reset_request(self.request) self.assertEqual(AccessAttempt.objects.count(), 3) @override_settings(AXES_LOCKOUT_PARAMETERS=["username"]) def test_reset_ip_username_user_failures(self): self.request.GET["username"] = self.USERNAME_1 self.request.META["REMOTE_ADDR"] = self.IP_1 reset_request(self.request) self.assertEqual(AccessAttempt.objects.count(), 3) @override_settings(AXES_LOCKOUT_PARAMETERS=["username", "ip_address"]) def test_reset_user_or_ip(self): reset_request(self.request) self.assertEqual(AccessAttempt.objects.count(), 5) @override_settings(AXES_LOCKOUT_PARAMETERS=["username", "ip_address"]) def test_reset_ip_user_or_ip(self): self.request.META["REMOTE_ADDR"] = self.IP_1 reset_request(self.request) self.assertEqual(AccessAttempt.objects.count(), 3) @override_settings(AXES_LOCKOUT_PARAMETERS=["username", "ip_address"]) def test_reset_username_user_or_ip(self): self.request.GET["username"] = self.USERNAME_1 reset_request(self.request) self.assertEqual(AccessAttempt.objects.count(), 3) @override_settings(AXES_LOCKOUT_PARAMETERS=["username", "ip_address"]) def test_reset_ip_username_user_or_ip(self): self.request.GET["username"] = self.USERNAME_1 self.request.META["REMOTE_ADDR"] = self.IP_1 reset_request(self.request) self.assertEqual(AccessAttempt.objects.count(), 2) @override_settings(AXES_LOCKOUT_PARAMETERS=[["username", "ip_address"]]) def test_reset_user_and_ip(self): reset_request(self.request) self.assertEqual(AccessAttempt.objects.count(), 5) @override_settings(AXES_LOCKOUT_PARAMETERS=[["username", "ip_address"]]) def test_reset_ip_user_and_ip(self): self.request.META["REMOTE_ADDR"] = self.IP_1 reset_request(self.request) self.assertEqual(AccessAttempt.objects.count(), 3) @override_settings(AXES_LOCKOUT_PARAMETERS=[["username", "ip_address"]]) def test_reset_username_user_and_ip(self): self.request.GET["username"] = self.USERNAME_1 reset_request(self.request) self.assertEqual(AccessAttempt.objects.count(), 3) @override_settings(AXES_LOCKOUT_PARAMETERS=[["username", "ip_address"]]) def test_reset_ip_username_user_and_ip(self): self.request.GET["username"] = self.USERNAME_1 self.request.META["REMOTE_ADDR"] = self.IP_1 reset_request(self.request) self.assertEqual(AccessAttempt.objects.count(), 4) django-axes-7.0.1/tests/test_backends.py000066400000000000000000000013531472335743500202630ustar00rootroot00000000000000from unittest.mock import patch, MagicMock from axes.backends import AxesBackend from axes.exceptions import ( AxesBackendRequestParameterRequired, AxesBackendPermissionDenied, ) from tests.base import AxesTestCase class BackendTestCase(AxesTestCase): def test_authenticate_raises_on_missing_request(self): request = None with self.assertRaises(AxesBackendRequestParameterRequired): AxesBackend().authenticate(request) @patch("axes.handlers.proxy.AxesProxyHandler.is_allowed", return_value=False) def test_authenticate_raises_on_locked_request(self, _): request = MagicMock() with self.assertRaises(AxesBackendPermissionDenied): AxesBackend().authenticate(request) django-axes-7.0.1/tests/test_checks.py000066400000000000000000000102371472335743500177520ustar00rootroot00000000000000from django.core.checks import run_checks, Warning # pylint: disable=redefined-builtin from django.test import override_settings, modify_settings from axes.backends import AxesStandaloneBackend from axes.checks import Messages, Hints, Codes from tests.base import AxesTestCase class CacheCheckTestCase(AxesTestCase): @override_settings( AXES_HANDLER="axes.handlers.cache.AxesCacheHandler", CACHES={ "default": { "BACKEND": "django.core.cache.backends.db.DatabaseCache", "LOCATION": "axes_cache", } }, ) def test_cache_check(self): warnings = run_checks() self.assertEqual(warnings, []) @override_settings( AXES_HANDLER="axes.handlers.cache.AxesCacheHandler", CACHES={ "default": {"BACKEND": "django.core.cache.backends.locmem.LocMemCache"} }, ) def test_cache_check_warnings(self): warnings = run_checks() warning = Warning( msg=Messages.CACHE_INVALID, hint=Hints.CACHE_INVALID, id=Codes.CACHE_INVALID ) self.assertEqual(warnings, [warning]) @override_settings( AXES_HANDLER="axes.handlers.database.AxesDatabaseHandler", CACHES={ "default": {"BACKEND": "django.core.cache.backends.locmem.LocMemCache"} }, ) def test_cache_check_does_not_produce_check_warnings_with_database_handler(self): warnings = run_checks() self.assertEqual(warnings, []) class MiddlewareCheckTestCase(AxesTestCase): @modify_settings(MIDDLEWARE={"remove": ["axes.middleware.AxesMiddleware"]}) def test_cache_check_warnings(self): warnings = run_checks() warning = Warning( msg=Messages.MIDDLEWARE_INVALID, hint=Hints.MIDDLEWARE_INVALID, id=Codes.MIDDLEWARE_INVALID, ) self.assertEqual(warnings, [warning]) class AxesSpecializedBackend(AxesStandaloneBackend): pass class BackendCheckTestCase(AxesTestCase): @modify_settings( AUTHENTICATION_BACKENDS={"remove": ["axes.backends.AxesStandaloneBackend"]} ) def test_backend_missing(self): warnings = run_checks() warning = Warning( msg=Messages.BACKEND_INVALID, hint=Hints.BACKEND_INVALID, id=Codes.BACKEND_INVALID, ) self.assertEqual(warnings, [warning]) @override_settings( AUTHENTICATION_BACKENDS=["tests.test_checks.AxesSpecializedBackend"] ) def test_specialized_backend(self): warnings = run_checks() self.assertEqual(warnings, []) @override_settings( AUTHENTICATION_BACKENDS=["tests.test_checks.AxesNotDefinedBackend"] ) def test_import_error(self): with self.assertRaises(ImportError): run_checks() @override_settings(AUTHENTICATION_BACKENDS=["module.not_defined"]) def test_module_not_found_error(self): with self.assertRaises(ModuleNotFoundError): run_checks() class DeprecatedSettingsTestCase(AxesTestCase): def setUp(self): self.disable_success_access_log_warning = Warning( msg=Messages.SETTING_DEPRECATED.format( deprecated_setting="AXES_DISABLE_SUCCESS_ACCESS_LOG" ), hint=Hints.SETTING_DEPRECATED, id=Codes.SETTING_DEPRECATED, ) @override_settings(AXES_DISABLE_SUCCESS_ACCESS_LOG=True) def test_deprecated_success_access_log_flag(self): warnings = run_checks() self.assertEqual(warnings, [self.disable_success_access_log_warning]) class ConfCheckTestCase(AxesTestCase): @override_settings(AXES_USERNAME_CALLABLE="module.not_defined") def test_invalid_import_path(self): warnings = run_checks() warning = Warning( msg=Messages.CALLABLE_INVALID.format( callable_setting="AXES_USERNAME_CALLABLE" ), hint=Hints.CALLABLE_INVALID, id=Codes.CALLABLE_INVALID, ) self.assertEqual(warnings, [warning]) @override_settings(AXES_COOLOFF_TIME=lambda: 1) def test_valid_callable(self): warnings = run_checks() self.assertEqual(warnings, []) django-axes-7.0.1/tests/test_decorators.py000066400000000000000000000036231472335743500206600ustar00rootroot00000000000000from unittest.mock import MagicMock, patch from django.http import HttpResponse from axes.decorators import axes_dispatch, axes_form_invalid from tests.base import AxesTestCase class DecoratorTestCase(AxesTestCase): SUCCESS_RESPONSE = HttpResponse(status=200, content="Dispatched") LOCKOUT_RESPONSE = HttpResponse(status=429, content="Locked out") def setUp(self): self.request = MagicMock() self.cls = MagicMock(return_value=self.request) self.func = MagicMock(return_value=self.SUCCESS_RESPONSE) @patch("axes.handlers.proxy.AxesProxyHandler.is_allowed", return_value=False) @patch("axes.decorators.get_lockout_response", return_value=LOCKOUT_RESPONSE) def test_axes_dispatch_locks_out(self, _, __): response = axes_dispatch(self.func)(self.request) self.assertEqual(response.content, self.LOCKOUT_RESPONSE.content) @patch("axes.handlers.proxy.AxesProxyHandler.is_allowed", return_value=True) @patch("axes.decorators.get_lockout_response", return_value=LOCKOUT_RESPONSE) def test_axes_dispatch_dispatches(self, _, __): response = axes_dispatch(self.func)(self.request) self.assertEqual(response.content, self.SUCCESS_RESPONSE.content) @patch("axes.handlers.proxy.AxesProxyHandler.is_allowed", return_value=False) @patch("axes.decorators.get_lockout_response", return_value=LOCKOUT_RESPONSE) def test_axes_form_invalid_locks_out(self, _, __): response = axes_form_invalid(self.func)(self.cls) self.assertEqual(response.content, self.LOCKOUT_RESPONSE.content) @patch("axes.handlers.proxy.AxesProxyHandler.is_allowed", return_value=True) @patch("axes.decorators.get_lockout_response", return_value=LOCKOUT_RESPONSE) def test_axes_form_invalid_dispatches(self, _, __): response = axes_form_invalid(self.func)(self.cls) self.assertEqual(response.content, self.SUCCESS_RESPONSE.content) django-axes-7.0.1/tests/test_failures.py000066400000000000000000000013761472335743500203300ustar00rootroot00000000000000from axes.models import AccessFailureLog from tests.base import AxesTestCase from axes.helpers import get_failure_limit from django.test import override_settings @override_settings(AXES_ENABLE_ACCESS_FAILURE_LOG=True) class FailureLogTestCase(AxesTestCase): def test_failure_log(self): self.login(is_valid_username=True, is_valid_password=False) self.assertEqual(AccessFailureLog.objects.count(), 1) self.assertTrue(AccessFailureLog.objects.filter(username=self.VALID_USERNAME).exists()) self.assertTrue(AccessFailureLog.objects.filter(ip_address=self.ip_address).exists()) def test_failure_locked_out(self): self.check_lockout() self.assertEqual(AccessFailureLog.objects.filter(locked_out=True).count(), 1) django-axes-7.0.1/tests/test_handlers.py000066400000000000000000000532501472335743500203140ustar00rootroot00000000000000from platform import python_implementation from unittest.mock import MagicMock, patch from pytest import mark from django.core.cache import cache from django.test import override_settings from django.urls import reverse from django.utils import timezone from django.utils.timezone import timedelta from axes.conf import settings from axes.handlers.proxy import AxesProxyHandler from axes.helpers import get_client_str from axes.models import AccessAttempt, AccessLog, AccessFailureLog from tests.base import AxesTestCase @override_settings(AXES_HANDLER="axes.handlers.base.AxesHandler") class AxesHandlerTestCase(AxesTestCase): @override_settings(AXES_IP_BLACKLIST=["127.0.0.1"]) def test_is_allowed_with_blacklisted_ip_address(self): self.assertFalse(AxesProxyHandler.is_allowed(self.request)) @override_settings( AXES_NEVER_LOCKOUT_WHITELIST=True, AXES_IP_WHITELIST=["127.0.0.1"] ) def test_is_allowed_with_whitelisted_ip_address(self): self.assertTrue(AxesProxyHandler.is_allowed(self.request)) @override_settings(AXES_NEVER_LOCKOUT_GET=True) def test_is_allowed_with_whitelisted_method(self): self.request.method = "GET" self.assertTrue(AxesProxyHandler.is_allowed(self.request)) @override_settings(AXES_LOCK_OUT_AT_FAILURE=False) def test_is_allowed_no_lock_out(self): self.assertTrue(AxesProxyHandler.is_allowed(self.request)) @override_settings(AXES_ONLY_ADMIN_SITE=True) def test_only_admin_site(self): request = MagicMock() request.path = "/test/" self.assertTrue(AxesProxyHandler.is_allowed(self.request)) def test_is_admin_site(self): request = MagicMock() tests = ( # (AXES_ONLY_ADMIN_SITE, URL, Expected) (True, "/test/", True), (True, reverse("admin:index"), False), (False, "/test/", False), (False, reverse("admin:index"), False), ) for setting_value, url, expected in tests: with override_settings(AXES_ONLY_ADMIN_SITE=setting_value): request.path = url with self.assertWarns(DeprecationWarning): self.assertEqual(AxesProxyHandler().is_admin_site(request), expected) def test_is_admin_request(self): request = MagicMock() tests = ( # (URL, Expected) ("/test/", False), (reverse("admin:index"), True), ) for url, expected in tests: request.path = url self.assertEqual(AxesProxyHandler().is_admin_request(request), expected) @override_settings(ROOT_URLCONF="tests.urls_empty") @override_settings(AXES_ONLY_ADMIN_SITE=True) def test_is_admin_site_no_admin_site(self): request = MagicMock() request.path = "/admin/" with self.assertWarns(DeprecationWarning): self.assertTrue(AxesProxyHandler().is_admin_site(self.request)) @override_settings(ROOT_URLCONF="tests.urls_empty") def test_is_admin_request_no_admin_site(self): request = MagicMock() request.path = "/admin/" self.assertFalse(AxesProxyHandler().is_admin_request(self.request)) def test_is_admin_request_no_path(self): self.assertFalse(AxesProxyHandler().is_admin_request(self.request)) class AxesProxyHandlerTestCase(AxesTestCase): def setUp(self): self.sender = MagicMock() self.credentials = MagicMock() self.request = MagicMock() self.user = MagicMock() self.instance = MagicMock() @patch("axes.handlers.proxy.AxesProxyHandler.implementation", None) def test_setting_changed_signal_triggers_handler_reimport(self): self.assertIsNone(AxesProxyHandler.implementation) with self.settings(AXES_HANDLER="axes.handlers.database.AxesDatabaseHandler"): self.assertIsNotNone(AxesProxyHandler.implementation) @patch("axes.handlers.proxy.AxesProxyHandler.implementation") def test_user_login_failed(self, handler): self.assertFalse(handler.user_login_failed.called) AxesProxyHandler.user_login_failed(self.sender, self.credentials, self.request) self.assertTrue(handler.user_login_failed.called) @patch("axes.handlers.proxy.AxesProxyHandler.implementation") def test_user_logged_in(self, handler): self.assertFalse(handler.user_logged_in.called) AxesProxyHandler.user_logged_in(self.sender, self.request, self.user) self.assertTrue(handler.user_logged_in.called) @patch("axes.handlers.proxy.AxesProxyHandler.implementation") def test_user_logged_out(self, handler): self.assertFalse(handler.user_logged_out.called) AxesProxyHandler.user_logged_out(self.sender, self.request, self.user) self.assertTrue(handler.user_logged_out.called) @patch("axes.handlers.proxy.AxesProxyHandler.implementation") def test_post_save_access_attempt(self, handler): self.assertFalse(handler.post_save_access_attempt.called) AxesProxyHandler.post_save_access_attempt(self.instance) self.assertTrue(handler.post_save_access_attempt.called) @patch("axes.handlers.proxy.AxesProxyHandler.implementation") def test_post_delete_access_attempt(self, handler): self.assertFalse(handler.post_delete_access_attempt.called) AxesProxyHandler.post_delete_access_attempt(self.instance) self.assertTrue(handler.post_delete_access_attempt.called) class AxesHandlerBaseTestCase(AxesTestCase): def check_whitelist(self, log): with override_settings( AXES_NEVER_LOCKOUT_WHITELIST=True, AXES_IP_WHITELIST=[self.ip_address] ): AxesProxyHandler.user_login_failed( sender=None, request=self.request, credentials=self.credentials ) client_str = get_client_str( self.username, self.ip_address, self.user_agent, self.path_info, self.request, ) log.info.assert_called_with( "AXES: Login failed from whitelisted client %s.", client_str ) def check_empty_request(self, log, handler): AxesProxyHandler.user_login_failed(sender=None, credentials={}, request=None) log.error.assert_called_with( f"AXES: {handler}.user_login_failed does not function without a request." ) @override_settings(AXES_HANDLER="axes.handlers.database.AxesDatabaseHandler") class ResetAttemptsTestCase(AxesHandlerBaseTestCase): """Resetting attempts is currently implemented only for database handler""" USERNAME_1 = "foo_username" USERNAME_2 = "bar_username" IP_1 = "127.1.0.1" IP_2 = "127.1.0.2" def setUp(self): super().setUp() self.create_attempt() self.create_attempt(username=self.USERNAME_1, ip_address=self.IP_1) self.create_attempt(username=self.USERNAME_1, ip_address=self.IP_2) self.create_attempt(username=self.USERNAME_2, ip_address=self.IP_1) self.create_attempt(username=self.USERNAME_2, ip_address=self.IP_2) def test_handler_reset_attempts(self): self.assertEqual(5, AxesProxyHandler.reset_attempts()) self.assertFalse(AccessAttempt.objects.count()) def test_handler_reset_attempts_username(self): self.assertEqual(2, AxesProxyHandler.reset_attempts(username=self.USERNAME_1)) self.assertEqual(AccessAttempt.objects.count(), 3) self.assertEqual( AccessAttempt.objects.filter(ip_address=self.USERNAME_1).count(), 0 ) def test_handler_reset_attempts_ip(self): self.assertEqual(2, AxesProxyHandler.reset_attempts(ip_address=self.IP_1)) self.assertEqual(AccessAttempt.objects.count(), 3) self.assertEqual(AccessAttempt.objects.filter(ip_address=self.IP_1).count(), 0) def test_handler_reset_attempts_ip_and_username(self): self.assertEqual( 1, AxesProxyHandler.reset_attempts( ip_address=self.IP_1, username=self.USERNAME_1 ), ) self.assertEqual(AccessAttempt.objects.count(), 4) self.assertEqual(AccessAttempt.objects.filter(ip_address=self.IP_1).count(), 1) self.create_attempt(username=self.USERNAME_1, ip_address=self.IP_1) self.assertEqual( 1, AxesProxyHandler.reset_attempts( ip_address=self.IP_1, username=self.USERNAME_2 ), ) self.assertEqual( 1, AxesProxyHandler.reset_attempts( ip_address=self.IP_2, username=self.USERNAME_1 ), ) def test_handler_reset_attempts_ip_or_username(self): self.assertEqual( 3, AxesProxyHandler.reset_attempts( ip_address=self.IP_1, username=self.USERNAME_1, ip_or_username=True ), ) self.assertEqual(AccessAttempt.objects.count(), 2) self.assertEqual(AccessAttempt.objects.filter(ip_address=self.IP_1).count(), 0) self.assertEqual( AccessAttempt.objects.filter(ip_address=self.USERNAME_1).count(), 0 ) @override_settings( AXES_HANDLER="axes.handlers.database.AxesDatabaseHandler", AXES_COOLOFF_TIME=timedelta(seconds=2), AXES_RESET_ON_SUCCESS=True, AXES_ENABLE_ACCESS_FAILURE_LOG=True, ) class AxesDatabaseHandlerTestCase(AxesHandlerBaseTestCase): def test_handler_reset_attempts(self): self.create_attempt() self.assertEqual(1, AxesProxyHandler.reset_attempts()) self.assertFalse(AccessAttempt.objects.count()) def test_handler_reset_logs(self): self.create_log() self.assertEqual(1, AxesProxyHandler.reset_logs()) self.assertFalse(AccessLog.objects.count()) def test_handler_reset_logs_older_than_42_days(self): self.create_log() then = timezone.now() - timezone.timedelta(days=90) with patch("django.utils.timezone.now", return_value=then): self.create_log() self.assertEqual(AccessLog.objects.count(), 2) self.assertEqual(1, AxesProxyHandler.reset_logs(age_days=42)) self.assertEqual(AccessLog.objects.count(), 1) def test_handler_reset_failure_logs(self): self.create_failure_log() self.assertEqual(1, AxesProxyHandler.reset_failure_logs()) self.assertFalse(AccessFailureLog.objects.count()) def test_handler_reset_failure_logs_older_than_42_days(self): self.create_failure_log() then = timezone.now() - timezone.timedelta(days=90) with patch("django.utils.timezone.now", return_value=then): self.create_failure_log() self.assertEqual(AccessFailureLog.objects.count(), 2) self.assertEqual(1, AxesProxyHandler.reset_failure_logs(age_days=42)) self.assertEqual(AccessFailureLog.objects.count(), 1) def test_handler_remove_out_of_limit_failure_logs(self): _more = 10 for i in range(settings.AXES_ACCESS_FAILURE_LOG_PER_USER_LIMIT + _more): self.create_failure_log() self.assertEqual( _more, AxesProxyHandler.remove_out_of_limit_failure_logs(username=self.username), ) @override_settings(AXES_RESET_ON_SUCCESS=True) def test_handler(self): self.check_handler() @override_settings(AXES_RESET_ON_SUCCESS=False) def test_handler_without_reset(self): self.check_handler() @override_settings(AXES_FAILURE_LIMIT=lambda *args: 3) def test_handler_callable_failure_limit(self): self.check_handler() @override_settings(AXES_FAILURE_LIMIT="tests.base.custom_failure_limit") def test_handler_str_failure_limit(self): self.check_handler() @override_settings(AXES_FAILURE_LIMIT=None) def test_handler_invalid_failure_limit(self): with self.assertRaises(TypeError): self.check_handler() @override_settings(AXES_LOCK_OUT_AT_FAILURE=False) def test_handler_without_lockout(self): self.check_handler() @patch("axes.handlers.database.log") def test_empty_request(self, log): self.check_empty_request(log, "AxesDatabaseHandler") @patch("axes.handlers.database.log") def test_whitelist(self, log): self.check_whitelist(log) @override_settings(AXES_LOCKOUT_PARAMETERS=["username"]) @patch("axes.handlers.database.log") def test_user_login_failed_only_user_failures_with_none_username(self, log): credentials = {"username": None, "password": "test"} sender = MagicMock() AxesProxyHandler.user_login_failed(sender, credentials, self.request) attempt = AccessAttempt.objects.all() self.assertEqual(0, AccessAttempt.objects.count()) log.warning.assert_called_with( "AXES: Username is None and username is the only one lockout parameter, new record will NOT be created." ) def test_user_login_failed_with_none_username(self): credentials = {"username": None, "password": "test"} sender = MagicMock() AxesProxyHandler.user_login_failed(sender, credentials, self.request) attempt = AccessAttempt.objects.all() self.assertEqual(1, AccessAttempt.objects.filter(username__isnull=True).count()) def test_user_login_failed_multiple_username(self): configurations = ( (2, 1, {}, ["admin", "admin1"]), ( 2, 1, {"AXES_LOCKOUT_PARAMETERS": [["ip_address", "user_agent"]]}, ["admin", "admin1"], ), (2, 1, {"AXES_LOCKOUT_PARAMETERS": ["username"]}, ["admin", "admin1"]), ( 2, 1, {"AXES_LOCKOUT_PARAMETERS": [["username", "ip_address"]]}, ["admin", "admin1"], ), ( 1, 2, {"AXES_LOCKOUT_PARAMETERS": [["username", "ip_address"]]}, ["admin", "admin"], ), ( 1, 2, {"AXES_LOCKOUT_PARAMETERS": ["username", "ip_address"]}, ["admin", "admin"], ), ( 2, 1, {"AXES_LOCKOUT_PARAMETERS": ["username", "ip_address"]}, ["admin", "admin1"], ), ) for ( total_attempts_count, failures_since_start, overrides, usernames, ) in configurations: with self.settings(**overrides): with self.subTest( total_attempts_count=total_attempts_count, failures_since_start=failures_since_start, settings=overrides, ): self.login(username=usernames[0]) attempt = AccessAttempt.objects.get(username=usernames[0]) self.assertEqual(1, attempt.failures_since_start) # check the number of failures associated to the attempt self.login(username=usernames[1]) attempt = AccessAttempt.objects.get(username=usernames[1]) self.assertEqual(failures_since_start, attempt.failures_since_start) # check the number of distinct attempts self.assertEqual( total_attempts_count, AccessAttempt.objects.count() ) AccessAttempt.objects.all().delete() @override_settings(AXES_HANDLER="axes.handlers.cache.AxesCacheHandler") class ResetAttemptsCacheHandlerTestCase(AxesHandlerBaseTestCase): """Test reset attempts for the cache handler""" USERNAME_1 = "foo_username" USERNAME_2 = "bar_username" IP_1 = "127.1.0.1" IP_2 = "127.1.0.2" def set_up_login_attempts(self): """Set up the login attempts.""" self.login(username=self.USERNAME_1, remote_addr=self.IP_1) self.login(username=self.USERNAME_1, remote_addr=self.IP_2) self.login(username=self.USERNAME_2, remote_addr=self.IP_1) self.login(username=self.USERNAME_2, remote_addr=self.IP_2) def check_failures(self, failures, username=None, ip_address=None): if ip_address is None and username is None: raise NotImplementedError("Must supply ip_address or username") try: prev_ip = self.request.META["REMOTE_ADDR"] credentials = {"username": username} if username else {} if ip_address is not None: self.request.META["REMOTE_ADDR"] = ip_address self.assertEqual( failures, AxesProxyHandler.get_failures(self.request, credentials=credentials), ) finally: self.request.META["REMOTE_ADDR"] = prev_ip def test_handler_reset_attempts(self): with self.assertRaises(NotImplementedError): AxesProxyHandler.reset_attempts() @override_settings(AXES_LOCKOUT_PARAMETERS=["username"]) def test_handler_reset_attempts_username(self): self.set_up_login_attempts() self.assertEqual( 2, AxesProxyHandler.get_failures( self.request, credentials={"username": self.USERNAME_1} ), ) self.assertEqual( 2, AxesProxyHandler.get_failures( self.request, credentials={"username": self.USERNAME_2} ), ) self.assertEqual(1, AxesProxyHandler.reset_attempts(username=self.USERNAME_1)) self.assertEqual( 0, AxesProxyHandler.get_failures( self.request, credentials={"username": self.USERNAME_1} ), ) self.assertEqual( 2, AxesProxyHandler.get_failures( self.request, credentials={"username": self.USERNAME_2} ), ) def test_handler_reset_attempts_ip(self): self.set_up_login_attempts() self.check_failures(2, ip_address=self.IP_1) self.assertEqual(1, AxesProxyHandler.reset_attempts(ip_address=self.IP_1)) self.check_failures(0, ip_address=self.IP_1) self.check_failures(2, ip_address=self.IP_2) @override_settings(AXES_LOCKOUT_PARAMETERS=[["username", "ip_address"]]) def test_handler_reset_attempts_ip_and_username(self): self.set_up_login_attempts() self.check_failures(1, username=self.USERNAME_1, ip_address=self.IP_1) self.check_failures(1, username=self.USERNAME_2, ip_address=self.IP_1) self.check_failures(1, username=self.USERNAME_1, ip_address=self.IP_2) self.assertEqual( 1, AxesProxyHandler.reset_attempts( ip_address=self.IP_1, username=self.USERNAME_1 ), ) self.check_failures(0, username=self.USERNAME_1, ip_address=self.IP_1) self.check_failures(1, username=self.USERNAME_2, ip_address=self.IP_1) self.check_failures(1, username=self.USERNAME_1, ip_address=self.IP_2) def test_handler_reset_attempts_ip_or_username(self): with self.assertRaises(NotImplementedError): AxesProxyHandler.reset_attempts() @override_settings( AXES_HANDLER="axes.handlers.cache.AxesCacheHandler", AXES_COOLOFF_TIME=timedelta(seconds=1), ) class AxesCacheHandlerTestCase(AxesHandlerBaseTestCase): @override_settings(AXES_RESET_ON_SUCCESS=True) def test_handler(self): self.check_handler() @override_settings(AXES_RESET_ON_SUCCESS=False) def test_handler_without_reset(self): self.check_handler() @override_settings(AXES_LOCK_OUT_AT_FAILURE=False) def test_handler_without_lockout(self): self.check_handler() @patch("axes.handlers.cache.log") def test_empty_request(self, log): self.check_empty_request(log, "AxesCacheHandler") @patch("axes.handlers.cache.log") def test_whitelist(self, log): self.check_whitelist(log) @override_settings(AXES_LOCKOUT_PARAMETERS=["username"]) @patch.object(cache, "set") @patch("axes.handlers.cache.log") def test_user_login_failed_only_user_failures_with_none_username( self, log, cache_set ): credentials = {"username": None, "password": "test"} sender = MagicMock() AxesProxyHandler.user_login_failed(sender, credentials, self.request) self.assertFalse(cache_set.called) log.warning.assert_called_with( "AXES: Username is None and username is the only one lockout parameter, new record will NOT be created." ) @patch.object(cache, "add") def test_user_login_failed_with_none_username(self, cache_add): credentials = {"username": None, "password": "test"} sender = MagicMock() AxesProxyHandler.user_login_failed(sender, credentials, self.request) self.assertTrue(cache_add.called) @override_settings(AXES_HANDLER="axes.handlers.dummy.AxesDummyHandler") class AxesDummyHandlerTestCase(AxesHandlerBaseTestCase): def test_handler(self): for _ in range(settings.AXES_FAILURE_LIMIT): self.login() self.check_login() def test_handler_is_allowed(self): self.assertEqual(True, AxesProxyHandler.is_allowed(self.request, {})) def test_handler_get_failures(self): self.assertEqual(0, AxesProxyHandler.get_failures(self.request, {})) @override_settings(AXES_HANDLER="axes.handlers.test.AxesTestHandler") class AxesTestHandlerTestCase(AxesHandlerBaseTestCase): def test_handler_reset_attempts(self): self.assertEqual(0, AxesProxyHandler.reset_attempts()) def test_handler_reset_logs(self): self.assertEqual(0, AxesProxyHandler.reset_logs()) def test_handler_is_allowed(self): self.assertEqual(True, AxesProxyHandler.is_allowed(self.request, {})) def test_handler_get_failures(self): self.assertEqual(0, AxesProxyHandler.get_failures(self.request, {})) django-axes-7.0.1/tests/test_helpers.py000066400000000000000000001176221472335743500201620ustar00rootroot00000000000000from datetime import timedelta from hashlib import sha256 from unittest.mock import patch from django.contrib.auth import get_user_model from django.http import HttpRequest, HttpResponse, HttpResponseRedirect, JsonResponse from django.test import RequestFactory, override_settings from axes.apps import AppConfig from axes.helpers import ( cleanse_parameters, get_cache_timeout, get_client_cache_keys, get_client_ip_address, get_client_parameters, get_client_str, get_client_username, get_cool_off, get_cool_off_iso8601, get_lockout_response, is_client_ip_address_blacklisted, is_client_ip_address_whitelisted, is_client_method_whitelisted, is_ip_address_in_blacklist, is_ip_address_in_whitelist, is_user_attempt_whitelisted, toggleable, ) from axes.models import AccessAttempt from tests.base import AxesTestCase @override_settings(AXES_ENABLED=False) class AxesDisabledTestCase(AxesTestCase): def test_initialize(self): AppConfig.logging_initialized = False AppConfig.initialize() self.assertFalse(AppConfig.logging_initialized) def test_toggleable(self): def is_true(): return True self.assertTrue(is_true()) self.assertIsNone(toggleable(is_true)()) class CacheTestCase(AxesTestCase): @override_settings(AXES_COOLOFF_TIME=3) # hours def test_get_cache_timeout_integer(self): timeout_seconds = float(60 * 60 * 3) self.assertEqual(get_cache_timeout(), timeout_seconds) @override_settings(AXES_COOLOFF_TIME=timedelta(seconds=420)) def test_get_cache_timeout_timedelta(self): self.assertEqual(get_cache_timeout(), 420) @override_settings(AXES_COOLOFF_TIME=None) def test_get_cache_timeout_none(self): self.assertEqual(get_cache_timeout(), None) def test_get_increasing_cache_timeout_by_username(self): user_durations = { "ben": timedelta(minutes=5), "jen": timedelta(minutes=10), } def _callback(request): username = request.POST["username"] if request else object() previous_duration = user_durations.get(username, timedelta()) user_durations[username] = previous_duration + timedelta(minutes=5) return user_durations[username] rf = RequestFactory() ben_req = rf.post("/", data={"username": "ben"}) jen_req = rf.post("/", data={"username": "jen"}) james_req = rf.post("/", data={"username": "james"}) with override_settings(AXES_COOLOFF_TIME=_callback): with self.subTest("no username"): self.assertEqual(get_cache_timeout(), 300) with self.subTest("ben"): self.assertEqual(get_cache_timeout(ben_req), 600) self.assertEqual(get_cache_timeout(ben_req), 900) self.assertEqual(get_cache_timeout(ben_req), 1200) with self.subTest("jen"): self.assertEqual(get_cache_timeout(jen_req), 900) with self.subTest("james"): self.assertEqual(get_cache_timeout(james_req), 300) class TimestampTestCase(AxesTestCase): def test_iso8601(self): """ Test get_cool_off_iso8601 correctly translates datetime.timedelta to ISO 8601 formatted duration. """ expected = { timedelta(days=1, hours=25, minutes=42, seconds=8): "P2DT1H42M8S", timedelta(days=7, seconds=342): "P7DT5M42S", timedelta(days=0, hours=2, minutes=42): "PT2H42M", timedelta(hours=20, seconds=42): "PT20H42S", timedelta(seconds=300): "PT5M", timedelta(seconds=9005): "PT2H30M5S", timedelta(minutes=9005): "P6DT6H5M", timedelta(days=15): "P15D", } for delta, iso_duration in expected.items(): with self.subTest(iso_duration): self.assertEqual(get_cool_off_iso8601(delta), iso_duration) @override_settings(AXES_SENSITIVE_PARAMETERS=[]) class ClientStringTestCase(AxesTestCase): @staticmethod def get_expected_client_str(*args, **kwargs): client_str_template = '{{username: "{0}", ip_address: "{1}", user_agent: "{2}", path_info: "{3}"}}' return client_str_template.format(*args, **kwargs) @override_settings(AXES_VERBOSE=True) def test_verbose_ip_only_client_details(self): username = "test@example.com" ip_address = "127.0.0.1" user_agent = "Googlebot/2.1 (+http://www.googlebot.com/bot.html)" path_info = "/admin/" expected = self.get_expected_client_str( username, ip_address, user_agent, path_info, self.request ) actual = get_client_str( username, ip_address, user_agent, path_info, self.request ) self.assertEqual(expected, actual) @override_settings(AXES_VERBOSE=True) def test_imbalanced_quotes(self): username = "butterfly.. },,," ip_address = "127.0.0.1" user_agent = "Googlebot/2.1 (+http://www.googlebot.com/bot.html)" path_info = "/admin/" expected = self.get_expected_client_str( username, ip_address, user_agent, path_info, self.request ) actual = get_client_str( username, ip_address, user_agent, path_info, self.request ) self.assertEqual(expected, actual) @override_settings(AXES_VERBOSE=True) def test_verbose_ip_only_client_details_tuple(self): username = "test@example.com" ip_address = "127.0.0.1" user_agent = "Googlebot/2.1 (+http://www.googlebot.com/bot.html)" path_info = ("admin", "login") expected = self.get_expected_client_str( username, ip_address, user_agent, path_info[0], self.request ) actual = get_client_str( username, ip_address, user_agent, path_info, self.request ) self.assertEqual(expected, actual) @override_settings(AXES_VERBOSE=False) def test_non_verbose_ip_only_client_details(self): username = "test@example.com" ip_address = "127.0.0.1" user_agent = "Googlebot/2.1 (+http://www.googlebot.com/bot.html)" path_info = "/admin/" expected = '{ip_address: "127.0.0.1", path_info: "/admin/"}' actual = get_client_str( username, ip_address, user_agent, path_info, self.request ) self.assertEqual(expected, actual) @override_settings(AXES_LOCKOUT_PARAMETERS=["username"]) @override_settings(AXES_VERBOSE=True) def test_verbose_user_only_client_details(self): username = "test@example.com" ip_address = "127.0.0.1" user_agent = "Googlebot/2.1 (+http://www.googlebot.com/bot.html)" path_info = "/admin/" expected = self.get_expected_client_str( username, ip_address, user_agent, path_info, self.request ) actual = get_client_str( username, ip_address, user_agent, path_info, self.request ) self.assertEqual(expected, actual) @override_settings(AXES_LOCKOUT_PARAMETERS=["username"]) @override_settings(AXES_VERBOSE=False) def test_non_verbose_user_only_client_details(self): username = "test@example.com" ip_address = "127.0.0.1" user_agent = "Googlebot/2.1 (+http://www.googlebot.com/bot.html)" path_info = "/admin/" expected = '{username: "test@example.com", path_info: "/admin/"}' actual = get_client_str( username, ip_address, user_agent, path_info, self.request ) self.assertEqual(expected, actual) @override_settings(AXES_LOCKOUT_PARAMETERS=[["username", "ip_address"]]) @override_settings(AXES_VERBOSE=True) def test_verbose_user_ip_combo_client_details(self): username = "test@example.com" ip_address = "127.0.0.1" user_agent = "Googlebot/2.1 (+http://www.googlebot.com/bot.html)" path_info = "/admin/" expected = self.get_expected_client_str( username, ip_address, user_agent, path_info, self.request ) actual = get_client_str( username, ip_address, user_agent, path_info, self.request ) self.assertEqual(expected, actual) @override_settings(AXES_LOCKOUT_PARAMETERS=[["username", "ip_address"]]) @override_settings(AXES_VERBOSE=False) def test_non_verbose_user_ip_combo_client_details(self): username = "test@example.com" ip_address = "127.0.0.1" user_agent = "Googlebot/2.1 (+http://www.googlebot.com/bot.html)" path_info = "/admin/" expected = '{username: "test@example.com", ip_address: "127.0.0.1", path_info: "/admin/"}' actual = get_client_str( username, ip_address, user_agent, path_info, self.request ) self.assertEqual(expected, actual) @override_settings(AXES_LOCKOUT_PARAMETERS=[["ip_address", "user_agent"]]) @override_settings(AXES_VERBOSE=True) def test_verbose_user_agent_client_details(self): username = "test@example.com" ip_address = "127.0.0.1" user_agent = "Googlebot/2.1 (+http://www.googlebot.com/bot.html)" path_info = "/admin/" expected = self.get_expected_client_str( username, ip_address, user_agent, path_info, self.request ) actual = get_client_str( username, ip_address, user_agent, path_info, self.request ) self.assertEqual(expected, actual) @override_settings(AXES_LOCKOUT_PARAMETERS=[["ip_address", "user_agent"]]) @override_settings(AXES_VERBOSE=False) def test_non_verbose_user_agent_client_details(self): username = "test@example.com" ip_address = "127.0.0.1" user_agent = "Googlebot/2.1 (+http://www.googlebot.com/bot.html)" path_info = "/admin/" expected = '{ip_address: "127.0.0.1", user_agent: "Googlebot/2.1 (+http://www.googlebot.com/bot.html)", path_info: "/admin/"}' actual = get_client_str( username, ip_address, user_agent, path_info, self.request ) self.assertEqual(expected, actual) @override_settings( AXES_CLIENT_STR_CALLABLE="tests.test_helpers.get_dummy_client_str" ) def test_get_client_str_callable_return_str(self): self.assertEqual( get_client_str( "username", "ip_address", "user_agent", "path_info", self.request ), "client string", ) @override_settings( AXES_CLIENT_STR_CALLABLE="tests.test_helpers.get_dummy_client_str_using_request" ) def test_get_client_str_callable_using_request(self): self.request.user = self.user self.assertEqual( get_client_str( "username", "ip_address", "user_agent", "path_info", self.request ), self.email, ) @override_settings(AXES_SENSITIVE_PARAMETERS=["username"]) def test_get_client_str_with_sensitive_parameters(self): username = "test@example.com" ip_address = "127.0.0.1" user_agent = "Googlebot/2.1 (+http://www.googlebot.com/bot.html)" path_info = "/admin/" expected = self.get_expected_client_str( "********************", ip_address, user_agent, path_info, self.request ) actual = get_client_str( username, ip_address, user_agent, path_info, self.request ) self.assertEqual(expected, actual) def get_dummy_client_str(username, ip_address, user_agent, path_info, request): return "client string" def get_dummy_client_str_using_request( username, ip_address, user_agent, path_info, request ): return f"{request.user.email}" def get_dummy_lockout_parameters(request, credentials=None): return ["ip_address", ["username", "user_agent"]] class ClientParametersTestCase(AxesTestCase): @override_settings(AXES_LOCKOUT_PARAMETERS=["username"]) def test_get_filter_kwargs_user(self): self.assertEqual( get_client_parameters(self.username, self.ip_address, self.user_agent, self.request, self.credentials), [{"username": self.username}], ) def test_get_filter_kwargs_ip(self): self.assertEqual( get_client_parameters(self.username, self.ip_address, self.user_agent, self.request, self.credentials), [{"ip_address": self.ip_address}], ) @override_settings(AXES_LOCKOUT_PARAMETERS=[["username", "ip_address"]]) def test_get_filter_kwargs_user_and_ip(self): self.assertEqual( get_client_parameters(self.username, self.ip_address, self.user_agent, self.request, self.credentials), [{"username": self.username, "ip_address": self.ip_address}], ) @override_settings(AXES_LOCKOUT_PARAMETERS=[["username", "user_agent"]]) def test_get_filter_kwargs_user_and_user_agent(self): self.assertEqual( get_client_parameters(self.username, self.ip_address, self.user_agent, self.request, self.credentials), [{"username": self.username, "user_agent": self.user_agent}], ) @override_settings(AXES_LOCKOUT_PARAMETERS=["ip_address", ["username", "user_agent"]]) def test_get_filter_kwargs_ip_or_user_and_user_agent(self): self.assertEqual( get_client_parameters(self.username, self.ip_address, self.user_agent, self.request, self.credentials), [{"ip_address": self.ip_address}, {"username": self.username, "user_agent": self.user_agent}], ) @override_settings(AXES_LOCKOUT_PARAMETERS=[["ip_address", "user_agent"], ["username", "user_agent"]]) def test_get_filter_kwargs_ip_and_user_agent_or_user_and_user_agent(self): self.assertEqual( get_client_parameters(self.username, self.ip_address, self.user_agent, self.request, self.credentials), [{"ip_address": self.ip_address, "user_agent": self.user_agent}, {"username": self.username, "user_agent": self.user_agent}], ) @override_settings(AXES_LOCKOUT_PARAMETERS=["username", "ip_address"]) def test_get_filter_kwargs_user_or_ip(self): self.assertEqual( get_client_parameters(self.username, self.ip_address, self.user_agent, self.request, self.credentials), [{"username": self.username}, {"ip_address": self.ip_address}], ) @override_settings(AXES_LOCKOUT_PARAMETERS=["username", "ip_address", "user_agent"]) def test_get_filter_kwargs_user_or_ip_or_user_agent(self): self.assertEqual( get_client_parameters(self.username, self.ip_address, self.user_agent, self.request, self.credentials), [{"username": self.username}, {"ip_address": self.ip_address}, {"user_agent": self.user_agent}], ) @override_settings(AXES_LOCKOUT_PARAMETERS=[["ip_address", "user_agent"]]) def test_get_filter_kwargs_ip_and_agent(self): self.assertEqual( get_client_parameters(self.username, self.ip_address, self.user_agent, self.request, self.credentials), [{"ip_address": self.ip_address, "user_agent": self.user_agent}], ) @override_settings( AXES_LOCKOUT_PARAMETERS=[["username", "ip_address", "user_agent"]] ) def test_get_filter_kwargs_user_ip_agent(self): self.assertEqual( get_client_parameters(self.username, self.ip_address, self.user_agent, self.request, self.credentials), [ { "username": self.username, "ip_address": self.ip_address, "user_agent": self.user_agent, }, ], ) @override_settings(AXES_LOCKOUT_PARAMETERS=["wrong_param"]) @patch("axes.helpers.log") def test_get_filter_kwargs_invalid_parameter(self, log): with self.assertRaises(ValueError): get_client_parameters( self.username, self.ip_address, self.user_agent, self.request, self.credentials, ) log.exception.assert_called_with( ( "wrong_param lockout parameter is not allowed. " "Allowed lockout parameters: username, ip_address, user_agent" ) ) @override_settings(AXES_LOCKOUT_PARAMETERS=[["ip_address", "wrong_param"]]) @patch("axes.helpers.log") def test_get_filter_kwargs_invalid_combined_parameter(self, log): with self.assertRaises(ValueError): get_client_parameters( self.username, self.ip_address, self.user_agent, self.request, self.credentials, ) log.exception.assert_called_with( ( "wrong_param lockout parameter is not allowed. " "Allowed lockout parameters: username, ip_address, user_agent" ) ) @override_settings(AXES_LOCKOUT_PARAMETERS=get_dummy_lockout_parameters) def test_get_filter_kwargs_callable_lockout_parameters(self): self.assertEqual( get_client_parameters( self.username, self.ip_address, self.user_agent, self.request, self.credentials, ), [ { "ip_address": self.ip_address, }, { "username": self.username, "user_agent": self.user_agent, }, ], ) @override_settings( AXES_LOCKOUT_PARAMETERS="tests.test_helpers.get_dummy_lockout_parameters" ) def test_get_filter_kwargs_callable_str_lockout_parameters(self): self.assertEqual( get_client_parameters( self.username, self.ip_address, self.user_agent, self.request, self.credentials, ), [ { "ip_address": self.ip_address, }, { "username": self.username, "user_agent": self.user_agent, }, ], ) @override_settings( AXES_LOCKOUT_PARAMETERS=lambda request, credentials: ["username"] ) def test_get_filter_kwargs_callable_lambda_lockout_parameters(self): self.assertEqual( get_client_parameters( self.username, self.ip_address, self.user_agent, self.request, self.credentials, ), [ { "username": self.username, }, ], ) @override_settings(AXES_LOCKOUT_PARAMETERS=True) def test_get_filter_kwargs_not_list_or_callable(self): with self.assertRaises(TypeError): get_client_parameters( self.username, self.ip_address, self.user_agent, self.request, self.credentials, ) @override_settings(AXES_LOCKOUT_PARAMETERS=lambda: None) def test_get_filter_kwargs_invalid_callable_too_few_arguments(self): with self.assertRaises(TypeError): get_client_parameters( self.username, self.ip_address, self.user_agent, self.request, self.credentials, ) @override_settings(AXES_LOCKOUT_PARAMETERS=lambda request, credentials, extra: None) def test_get_filter_kwargs_invalid_callable_too_many_arguments(self): with self.assertRaises(TypeError): get_client_parameters( self.username, self.ip_address, self.user_agent, self.request, self.credentials, ) @override_settings( AXES_LOCKOUT_PARAMETERS=lambda request, credentials: ["wrong_param"] ) @patch("axes.helpers.log") def test_get_filter_kwargs_callable_invalid_lockout_param(self, log): with self.assertRaises(ValueError): get_client_parameters( self.username, self.ip_address, self.user_agent, self.request, self.credentials, ) log.exception.assert_called_with( ( "wrong_param lockout parameter is not allowed. " "Allowed lockout parameters: username, ip_address, user_agent" ) ) @override_settings( AXES_LOCKOUT_PARAMETERS=lambda request, credentials: [ ["ip_address", "wrong_param"] ] ) @patch("axes.helpers.log") def test_get_filter_kwargs_callable_invalid_combined_lockout_param(self, log): with self.assertRaises(ValueError): get_client_parameters( self.username, self.ip_address, self.user_agent, self.request, self.credentials, ) log.exception.assert_called_with( ( "wrong_param lockout parameter is not allowed. " "Allowed lockout parameters: username, ip_address, user_agent" ) ) class ClientCacheKeyTestCase(AxesTestCase): def test_get_cache_keys(self): """ Test the cache key format. """ cache_hash_digest = sha256(self.ip_address.encode()).hexdigest() cache_hash_key = f"axes-{cache_hash_digest}" # Getting cache key from request request_factory = RequestFactory() request = request_factory.post( "/admin/login/", data={"username": self.username, "password": "test"} ) self.assertEqual([cache_hash_key], get_client_cache_keys(request)) # Getting cache key from AccessAttempt Object attempt = AccessAttempt( user_agent="", ip_address=self.ip_address, username=self.username, get_data="", post_data="", http_accept=request.META.get("HTTP_ACCEPT", ""), path_info=request.META.get("PATH_INFO", ""), failures_since_start=0, ) self.assertEqual([cache_hash_key], get_client_cache_keys(attempt)) def test_get_cache_key_empty_ip_address(self): """ Simulate an empty IP address in the request. """ empty_ip_address = "" cache_hash_digest = sha256(empty_ip_address.encode()).hexdigest() cache_hash_key = f"axes-{cache_hash_digest}" # Getting cache key from request request_factory = RequestFactory() request = request_factory.post( "/admin/login/", data={"username": self.username, "password": "test"}, REMOTE_ADDR=empty_ip_address, ) self.assertEqual([cache_hash_key], get_client_cache_keys(request)) # Getting cache key from AccessAttempt Object attempt = AccessAttempt( user_agent="", ip_address=empty_ip_address, username=self.username, get_data="", post_data="", http_accept=request.META.get("HTTP_ACCEPT", ""), path_info=request.META.get("PATH_INFO", ""), failures_since_start=0, ) self.assertEqual([cache_hash_key], get_client_cache_keys(attempt)) def test_get_cache_key_credentials(self): """ Test the cache key format. """ ip_address = self.ip_address cache_hash_digest = sha256(ip_address.encode()).hexdigest() cache_hash_key = f"axes-{cache_hash_digest}" # Getting cache key from request request_factory = RequestFactory() request = request_factory.post( "/admin/login/", data={"username": self.username, "password": "test"} ) # Difference between the upper test: new call signature with credentials credentials = {"username": self.username} self.assertEqual([cache_hash_key], get_client_cache_keys(request, credentials)) # Getting cache key from AccessAttempt Object attempt = AccessAttempt( user_agent="", ip_address=ip_address, username=self.username, get_data="", post_data="", http_accept=request.META.get("HTTP_ACCEPT", ""), path_info=request.META.get("PATH_INFO", ""), failures_since_start=0, ) self.assertEqual([cache_hash_key], get_client_cache_keys(attempt)) class UsernameTestCase(AxesTestCase): @override_settings(AXES_USERNAME_FORM_FIELD="username") def test_default_get_client_username(self): expected = "test-username" request = HttpRequest() request.POST["username"] = expected actual = get_client_username(request) self.assertEqual(expected, actual) def test_default_get_client_username_drf(self): class DRFRequest: def __init__(self): self.data = {} self.POST = {} expected = "test-username" request = DRFRequest() request.data["username"] = expected actual = get_client_username(request) self.assertEqual(expected, actual) @override_settings(AXES_USERNAME_FORM_FIELD="username") def test_default_get_client_username_credentials(self): expected = "test-username" expected_in_credentials = "test-credentials-username" request = HttpRequest() request.POST["username"] = expected credentials = {"username": expected_in_credentials} actual = get_client_username(request, credentials) self.assertEqual(expected_in_credentials, actual) def sample_customize_username(request, credentials): return "prefixed-" + request.POST.get("username") @override_settings(AXES_USERNAME_FORM_FIELD="username") @override_settings(AXES_USERNAME_CALLABLE=sample_customize_username) def test_custom_get_client_username_from_request(self): provided = "test-username" expected = "prefixed-" + provided provided_in_credentials = "test-credentials-username" request = HttpRequest() request.POST["username"] = provided credentials = {"username": provided_in_credentials} actual = get_client_username(request, credentials) self.assertEqual(expected, actual) def sample_customize_username_credentials(request, credentials): return "prefixed-" + credentials.get("username") @override_settings(AXES_USERNAME_FORM_FIELD="username") @override_settings(AXES_USERNAME_CALLABLE=sample_customize_username_credentials) def test_custom_get_client_username_from_credentials(self): provided = "test-username" provided_in_credentials = "test-credentials-username" expected_in_credentials = "prefixed-" + provided_in_credentials request = HttpRequest() request.POST["username"] = provided credentials = {"username": provided_in_credentials} actual = get_client_username(request, credentials) self.assertEqual(expected_in_credentials, actual) @override_settings( AXES_USERNAME_CALLABLE=lambda request, credentials: "example" ) # pragma: no cover def test_get_client_username(self): self.assertEqual(get_client_username(HttpRequest(), {}), "example") @override_settings(AXES_USERNAME_CALLABLE=lambda request: None) # pragma: no cover def test_get_client_username_invalid_callable_too_few_arguments(self): with self.assertRaises(TypeError): get_client_username(HttpRequest(), {}) @override_settings( AXES_USERNAME_CALLABLE=lambda request, credentials, extra: None ) # pragma: no cover def test_get_client_username_invalid_callable_too_many_arguments(self): with self.assertRaises(TypeError): get_client_username(HttpRequest(), {}) @override_settings(AXES_USERNAME_CALLABLE=True) def test_get_client_username_not_callable(self): with self.assertRaises(TypeError): get_client_username(HttpRequest(), {}) @override_settings(AXES_USERNAME_CALLABLE="tests.test_helpers.get_username") def test_get_client_username_str(self): self.assertEqual(get_client_username(HttpRequest(), {}), "username") def get_username(request, credentials: dict) -> str: return "username" def get_ip(request: HttpRequest) -> str: return "127.0.0.1" class ClientIpAddressTestCase(AxesTestCase): @override_settings(AXES_CLIENT_IP_CALLABLE=get_ip) def test_get_client_ip_address(self): self.assertEqual(get_client_ip_address(HttpRequest()), "127.0.0.1") @override_settings(AXES_CLIENT_IP_CALLABLE="tests.test_helpers.get_ip") def test_get_client_ip_address_str(self): self.assertEqual(get_client_ip_address(HttpRequest()), "127.0.0.1") @override_settings( AXES_CLIENT_IP_CALLABLE=lambda request: "127.0.0.1" ) # pragma: no cover def test_get_client_ip_address_lambda(self): self.assertEqual(get_client_ip_address(HttpRequest()), "127.0.0.1") @override_settings(AXES_CLIENT_IP_CALLABLE=True) def test_get_client_ip_address_not_callable(self): with self.assertRaises(TypeError): get_client_ip_address(HttpRequest()) @override_settings(AXES_CLIENT_IP_CALLABLE=lambda: None) # pragma: no cover def test_get_client_ip_address_invalid_callable_too_few_arguments(self): with self.assertRaises(TypeError): get_client_ip_address(HttpRequest()) @override_settings( AXES_CLIENT_IP_CALLABLE=lambda request, extra: None ) # pragma: no cover def test_get_client_ip_address_invalid_callable_too_many_arguments(self): with self.assertRaises(TypeError): get_client_ip_address(HttpRequest()) def test_get_client_ip_address_with_ipware(self): request = HttpRequest() request.META["REMOTE_ADDR"] = "127.0.0.2" self.assertEqual(get_client_ip_address(request, use_ipware=True), "127.0.0.2") def test_get_client_ip_address_without_ipware(self): request = HttpRequest() request.META["REMOTE_ADDR"] = "127.0.0.3" self.assertEqual(get_client_ip_address(request, use_ipware=False), "127.0.0.3") class IPWhitelistTestCase(AxesTestCase): def setUp(self): self.request = HttpRequest() self.request.method = "POST" self.request.META["REMOTE_ADDR"] = "127.0.0.1" self.request.axes_ip_address = "127.0.0.1" @override_settings(AXES_IP_WHITELIST=None) def test_ip_in_whitelist_none(self): self.assertFalse(is_ip_address_in_whitelist("127.0.0.2")) @override_settings(AXES_IP_WHITELIST=["127.0.0.1"]) def test_ip_in_whitelist(self): self.assertTrue(is_ip_address_in_whitelist("127.0.0.1")) self.assertFalse(is_ip_address_in_whitelist("127.0.0.2")) @override_settings(AXES_IP_BLACKLIST=None) def test_ip_in_blacklist_none(self): self.assertFalse(is_ip_address_in_blacklist("127.0.0.2")) @override_settings(AXES_IP_BLACKLIST=["127.0.0.1"]) def test_ip_in_blacklist(self): self.assertTrue(is_ip_address_in_blacklist("127.0.0.1")) self.assertFalse(is_ip_address_in_blacklist("127.0.0.2")) @override_settings(AXES_IP_BLACKLIST=["127.0.0.1"]) def test_is_client_ip_address_blacklisted_ip_in_blacklist(self): self.assertTrue(is_client_ip_address_blacklisted(self.request)) @override_settings(AXES_IP_BLACKLIST=["127.0.0.2"]) def test_is_is_client_ip_address_blacklisted_ip_not_in_blacklist(self): self.assertFalse(is_client_ip_address_blacklisted(self.request)) @override_settings(AXES_NEVER_LOCKOUT_WHITELIST=True) @override_settings(AXES_IP_WHITELIST=["127.0.0.1"]) def test_is_client_ip_address_blacklisted_ip_in_whitelist(self): self.assertFalse(is_client_ip_address_blacklisted(self.request)) @override_settings(AXES_ONLY_WHITELIST=True) @override_settings(AXES_IP_WHITELIST=["127.0.0.2"]) def test_is_already_locked_ip_not_in_whitelist(self): self.assertTrue(is_client_ip_address_blacklisted(self.request)) @override_settings(AXES_NEVER_LOCKOUT_WHITELIST=True) @override_settings(AXES_IP_WHITELIST=["127.0.0.1"]) def test_is_client_ip_address_whitelisted_never_lockout(self): self.assertTrue(is_client_ip_address_whitelisted(self.request)) @override_settings(AXES_ONLY_WHITELIST=True) @override_settings(AXES_IP_WHITELIST=["127.0.0.1"]) def test_is_client_ip_address_whitelisted_only_allow(self): self.assertTrue(is_client_ip_address_whitelisted(self.request)) @override_settings(AXES_ONLY_WHITELIST=True) @override_settings(AXES_IP_WHITELIST=["127.0.0.2"]) def test_is_client_ip_address_whitelisted_not(self): self.assertFalse(is_client_ip_address_whitelisted(self.request)) class MethodWhitelistTestCase(AxesTestCase): def setUp(self): self.request = HttpRequest() self.request.method = "GET" @override_settings(AXES_NEVER_LOCKOUT_GET=True) def test_is_client_method_whitelisted(self): self.assertTrue(is_client_method_whitelisted(self.request)) @override_settings(AXES_NEVER_LOCKOUT_GET=False) def test_is_client_method_whitelisted_not(self): self.assertFalse(is_client_method_whitelisted(self.request)) class LockoutResponseTestCase(AxesTestCase): def setUp(self): self.request = HttpRequest() @override_settings(AXES_COOLOFF_TIME=42) def test_get_lockout_response_cool_off(self): get_lockout_response(request=self.request) @override_settings(AXES_LOCKOUT_TEMPLATE="example.html") @patch("axes.helpers.render") def test_get_lockout_response_lockout_template(self, render): self.assertFalse(render.called) get_lockout_response(request=self.request) self.assertTrue(render.called) @override_settings(AXES_LOCKOUT_URL="https://example.com") def test_get_lockout_response_lockout_url(self): response = get_lockout_response(request=self.request) self.assertEqual(type(response), HttpResponseRedirect) def test_get_lockout_response_lockout_json(self): self.request.META["HTTP_X_REQUESTED_WITH"] = "XMLHttpRequest" response = get_lockout_response(request=self.request) self.assertEqual(type(response), JsonResponse) def test_get_lockout_response_lockout_response(self): response = get_lockout_response(request=self.request) self.assertEqual(type(response), HttpResponse) def mock_get_cool_off_str(req): return timedelta(seconds=30) class AxesCoolOffTestCase(AxesTestCase): @override_settings(AXES_COOLOFF_TIME=None) def test_get_cool_off_none(self): self.assertIsNone(get_cool_off()) @override_settings(AXES_COOLOFF_TIME=2) def test_get_cool_off_int(self): self.assertEqual(get_cool_off(), timedelta(hours=2)) @override_settings(AXES_COOLOFF_TIME=2.0) def test_get_cool_off_float(self): self.assertEqual(get_cool_off(), timedelta(minutes=120)) @override_settings(AXES_COOLOFF_TIME=0.25) def test_get_cool_off_float_lt_0(self): self.assertEqual(get_cool_off(), timedelta(minutes=15)) @override_settings(AXES_COOLOFF_TIME=1.7) def test_get_cool_off_float_gt_0(self): self.assertEqual(get_cool_off(), timedelta(seconds=6120)) @override_settings(AXES_COOLOFF_TIME=lambda r: timedelta(seconds=30)) def test_get_cool_off_callable(self): self.assertEqual(get_cool_off(), timedelta(seconds=30)) @override_settings(AXES_COOLOFF_TIME="tests.test_helpers.mock_get_cool_off_str") def test_get_cool_off_path(self): self.assertEqual(get_cool_off(), timedelta(seconds=30)) def mock_is_whitelisted(request, credentials): return True class AxesWhitelistTestCase(AxesTestCase): def setUp(self): self.user_model = get_user_model() self.user = self.user_model.objects.create(username="jane.doe") self.request = HttpRequest() self.credentials = dict() def test_is_whitelisted(self): self.assertFalse(is_user_attempt_whitelisted(self.request, self.credentials)) @override_settings(AXES_WHITELIST_CALLABLE=mock_is_whitelisted) def test_is_whitelisted_override_callable(self): self.assertTrue(is_user_attempt_whitelisted(self.request, self.credentials)) @override_settings(AXES_WHITELIST_CALLABLE="tests.test_helpers.mock_is_whitelisted") def test_is_whitelisted_override_path(self): self.assertTrue(is_user_attempt_whitelisted(self.request, self.credentials)) @override_settings(AXES_WHITELIST_CALLABLE=42) def test_is_whitelisted_override_invalid(self): with self.assertRaises(TypeError): is_user_attempt_whitelisted(self.request, self.credentials) def mock_get_lockout_response(request, credentials): return HttpResponse(status=400) class AxesLockoutTestCase(AxesTestCase): def setUp(self): self.request = HttpRequest() self.credentials = dict() def test_get_lockout_response(self): response = get_lockout_response(self.request, self.credentials) self.assertEqual(429, response.status_code) @override_settings(AXES_HTTP_RESPONSE_CODE=403) def test_get_lockout_response_with_custom_http_response_code(self): response = get_lockout_response(self.request, self.credentials) self.assertEqual(403, response.status_code) @override_settings(AXES_LOCKOUT_CALLABLE=mock_get_lockout_response) def test_get_lockout_response_override_callable(self): response = get_lockout_response(self.request, self.credentials) self.assertEqual(400, response.status_code) @override_settings( AXES_LOCKOUT_CALLABLE="tests.test_helpers.mock_get_lockout_response" ) def test_get_lockout_response_override_path(self): response = get_lockout_response(self.request, self.credentials) self.assertEqual(400, response.status_code) @override_settings(AXES_LOCKOUT_CALLABLE=42) def test_get_lockout_response_override_invalid(self): with self.assertRaises(TypeError): get_lockout_response(self.request, self.credentials) class AxesCleanseParamsTestCase(AxesTestCase): def setUp(self): self.parameters = { "username": "test_user", "password": "test_password", "other_sensitive_data": "sensitive", } @override_settings(AXES_SENSITIVE_PARAMETERS=[]) def test_cleanse_parameters(self): cleansed = cleanse_parameters(self.parameters) self.assertEqual("test_user", cleansed["username"]) self.assertEqual("********************", cleansed["password"]) self.assertEqual("sensitive", cleansed["other_sensitive_data"]) @override_settings(AXES_SENSITIVE_PARAMETERS=["other_sensitive_data"]) def test_cleanse_parameters_override_sensitive(self): cleansed = cleanse_parameters(self.parameters) self.assertEqual("test_user", cleansed["username"]) self.assertEqual("********************", cleansed["password"]) self.assertEqual("********************", cleansed["other_sensitive_data"]) @override_settings(AXES_SENSITIVE_PARAMETERS=["other_sensitive_data"]) @override_settings(AXES_PASSWORD_FORM_FIELD="username") def test_cleanse_parameters_override_both(self): cleansed = cleanse_parameters(self.parameters) self.assertEqual("********************", cleansed["username"]) self.assertEqual("********************", cleansed["password"]) self.assertEqual("********************", cleansed["other_sensitive_data"]) @override_settings(AXES_SENSITIVE_PARAMETERS=[]) @override_settings(AXES_PASSWORD_FORM_FIELD=None) def test_cleanse_parameters_override_empty(self): cleansed = cleanse_parameters(self.parameters) self.assertEqual("test_user", cleansed["username"]) self.assertEqual("********************", cleansed["password"]) self.assertEqual("sensitive", cleansed["other_sensitive_data"]) django-axes-7.0.1/tests/test_logging.py000066400000000000000000000111741472335743500201410ustar00rootroot00000000000000from unittest.mock import patch from django.test import override_settings from axes import __version__ from axes.apps import AppConfig from axes.models import AccessAttempt, AccessLog from tests.base import AxesTestCase _BEGIN = "AXES: BEGIN version %s, %s" _VERSION = __version__ @patch("axes.apps.AppConfig.initialized", False) @patch("axes.apps.log") class AppsTestCase(AxesTestCase): def test_axes_config_log_re_entrant(self, log): """ Test that initialize call count does not increase on repeat calls. """ AppConfig.initialize() calls = log.info.call_count AppConfig.initialize() self.assertTrue( calls == log.info.call_count and calls > 0, "AxesConfig.initialize needs to be re-entrant", ) @override_settings(AXES_VERBOSE=False) def test_axes_config_log_not_verbose(self, log): AppConfig.initialize() self.assertFalse(log.info.called) @override_settings(AXES_LOCKOUT_PARAMETERS=["username"]) def test_axes_config_log_user_only(self, log): AppConfig.initialize() log.info.assert_called_with(_BEGIN, _VERSION, "blocking by username") def test_axes_config_log_ip_only(self, log): AppConfig.initialize() log.info.assert_called_with(_BEGIN, _VERSION, "blocking by ip_address") @override_settings(AXES_LOCKOUT_PARAMETERS=[["username", "ip_address"]]) def test_axes_config_log_user_ip(self, log): AppConfig.initialize() log.info.assert_called_with( _BEGIN, _VERSION, "blocking by combination of username and ip_address" ) @override_settings(AXES_LOCKOUT_PARAMETERS=["username", "ip_address"]) def test_axes_config_log_user_or_ip(self, log): AppConfig.initialize() log.info.assert_called_with(_BEGIN, _VERSION, "blocking by username or ip_address") class AccessLogTestCase(AxesTestCase): def test_access_log_on_logout(self): """ Test a valid logout and make sure the logout_time is updated only for that. """ self.login(is_valid_username=True, is_valid_password=True) latest_log = AccessLog.objects.latest("id") self.assertIsNone(latest_log.logout_time) other_log = self.create_log(session_hash='not-the-session') self.assertIsNone(other_log.logout_time) response = self.logout() self.assertContains(response, "Logged out") other_log.refresh_from_db() self.assertIsNone(other_log.logout_time) latest_log.refresh_from_db() self.assertIsNotNone(latest_log.logout_time) @override_settings(DATA_UPLOAD_MAX_NUMBER_FIELDS=1500) def test_log_data_truncated(self): """ Test that get_query_str properly truncates data to the max_length (default 1024). """ # An impossibly large post dict extra_data = {"too-large-field": "x" * 2 ** 16} self.login(**extra_data) self.assertEqual(len(AccessAttempt.objects.latest("id").post_data), 1024) @override_settings(AXES_DISABLE_ACCESS_LOG=True) def test_valid_logout_without_success_log(self): AccessLog.objects.all().delete() response = self.login(is_valid_username=True, is_valid_password=True) response = self.logout() self.assertEqual(AccessLog.objects.all().count(), 0) self.assertContains(response, "Logged out", html=True) @override_settings(AXES_DISABLE_ACCESS_LOG=True) def test_valid_login_without_success_log(self): """ Test that a valid login does not generate an AccessLog when DISABLE_SUCCESS_ACCESS_LOG is True. """ AccessLog.objects.all().delete() response = self.login(is_valid_username=True, is_valid_password=True) self.assertEqual(response.status_code, 302) self.assertEqual(AccessLog.objects.all().count(), 0) @override_settings(AXES_DISABLE_ACCESS_LOG=True) def test_valid_logout_without_log(self): AccessLog.objects.all().delete() response = self.login(is_valid_username=True, is_valid_password=True) response = self.logout() self.assertEqual(AccessLog.objects.count(), 0) self.assertContains(response, "Logged out", html=True) @override_settings(AXES_DISABLE_ACCESS_LOG=True) def test_non_valid_login_without_log(self): """ Test that a non-valid login does generate an AccessLog when DISABLE_ACCESS_LOG is True. """ AccessLog.objects.all().delete() response = self.login(is_valid_username=True, is_valid_password=False) self.assertEqual(response.status_code, 200) self.assertEqual(AccessLog.objects.all().count(), 0) django-axes-7.0.1/tests/test_login.py000066400000000000000000001125221472335743500176220ustar00rootroot00000000000000""" Integration tests for the login handling. TODO: Clean up the tests in this module. """ from datetime import timedelta from importlib import import_module from time import sleep from django.contrib.auth import get_user_model, login, logout from django.http import HttpRequest from django.test import override_settings, TestCase from django.urls import reverse from axes.conf import settings from axes.helpers import get_cache, make_cache_key_list, get_cool_off, get_failure_limit from axes.models import AccessAttempt from tests.base import AxesTestCase class DjangoLoginTestCase(TestCase): def setUp(self): engine = import_module(settings.SESSION_ENGINE) self.request = HttpRequest() self.request.session = engine.SessionStore() self.username = "john.doe" self.password = "hunter2" self.user = get_user_model().objects.create(username=self.username, is_staff=True) self.user.set_password(self.password) self.user.save() self.user.backend = "django.contrib.auth.backends.ModelBackend" class DjangoContribAuthLoginTestCase(DjangoLoginTestCase): def test_login(self): login(self.request, self.user) def test_logout(self): login(self.request, self.user) logout(self.request) @override_settings(AXES_ENABLED=False) class DjangoTestClientLoginTestCase(DjangoLoginTestCase): def test_client_login(self): self.client.login(username=self.username, password=self.password) response = self.client.get(reverse("admin:index")) self.assertEqual(response.status_code, 200) def test_client_logout(self): self.client.login(username=self.username, password=self.password) self.client.logout() response = self.client.get(reverse("admin:index")) self.assertEqual(response.status_code, 302) def test_client_force_login(self): self.client.force_login(self.user) response = self.client.get(reverse("admin:index")) self.assertEqual(response.status_code, 200) class DatabaseLoginTestCase(AxesTestCase): """ Test for lockouts under different configurations and circumstances to prevent false positives and false negatives. Always block attempted logins for the same user from the same IP. Always allow attempted logins for a different user from a different IP. """ IP_1 = "10.1.1.1" IP_2 = "10.2.2.2" IP_3 = "10.2.2.3" USER_1 = "valid-user-1" USER_2 = "valid-user-2" USER_3 = "valid-user-3" EMAIL_1 = "valid-email-1@example.com" EMAIL_2 = "valid-email-2@example.com" VALID_USERNAME = USER_1 VALID_EMAIL = EMAIL_1 VALID_PASSWORD = "valid-password" VALID_IP_ADDRESS = IP_1 WRONG_PASSWORD = "wrong-password" LOCKED_MESSAGE = "Account locked: too many login attempts." LOGIN_FORM_KEY = '' ATTEMPT_NOT_BLOCKED = 200 ALLOWED = 302 BLOCKED = 429 def _login(self, username, password, ip_addr="127.0.0.1", user_agent="test-browser", **kwargs): """ Login a user and get the response. IP address can be configured to test IP blocking functionality. """ post_data = {"username": username, "password": password} post_data.update(kwargs) return self.client.post( reverse("admin:login"), post_data, REMOTE_ADDR=ip_addr, HTTP_USER_AGENT=user_agent, ) def _lockout_user_from_ip(self, username, ip_addr, user_agent="test-browser"): for _ in range(settings.AXES_FAILURE_LIMIT): response = self._login( username=username, password=self.WRONG_PASSWORD, ip_addr=ip_addr, user_agent=user_agent, ) return response def _lockout_user1_from_ip1(self): return self._lockout_user_from_ip(username=self.USER_1, ip_addr=self.IP_1) def setUp(self): """ Create two valid users for authentication. """ super().setUp() self.user2 = get_user_model().objects.create_superuser( username=self.USER_2, email=self.EMAIL_2, password=self.VALID_PASSWORD, is_staff=True, is_superuser=True, ) def test_login(self): """ Test a valid login for a real username. """ response = self._login(self.username, self.password) self.assertNotContains( response, self.LOGIN_FORM_KEY, status_code=self.ALLOWED, html=True ) def test_lockout_limit_once(self): """ Test the login lock trying to login one more time than failure limit. """ response = self.lockout() self.assertContains(response, self.LOCKED_MESSAGE, status_code=self.BLOCKED) def test_lockout_limit_many(self): """ Test the login lock trying to login a lot of times more than failure limit. """ self.lockout() for _ in range(settings.AXES_FAILURE_LIMIT): response = self.login() self.assertContains(response, self.LOCKED_MESSAGE, status_code=self.BLOCKED) def attempt_count(self): return AccessAttempt.objects.count() @override_settings(AXES_RESET_ON_SUCCESS=False) def test_reset_on_success_false(self): self.almost_lockout() self.login(is_valid_username=True, is_valid_password=True) response = self.login() self.assertContains(response, self.LOCKED_MESSAGE, status_code=self.BLOCKED) self.assertTrue(self.attempt_count()) @override_settings(AXES_RESET_ON_SUCCESS=True) def test_reset_on_success_true(self): self.almost_lockout() self.assertTrue(self.attempt_count()) self.login(is_valid_username=True, is_valid_password=True) self.assertFalse(self.attempt_count()) response = self.lockout() self.assertContains(response, self.LOCKED_MESSAGE, status_code=self.BLOCKED) self.assertTrue(self.attempt_count()) @override_settings(AXES_LOCKOUT_PARAMETERS=[["username", "ip_address"]]) def test_lockout_by_combination_user_and_ip(self): """ Test login failure when lockout parameters is combination of username and ip_address. """ # test until one try before the limit for _ in range(1, settings.AXES_FAILURE_LIMIT): response = self.login(is_valid_username=True, is_valid_password=False) # Check if we are in the same login page self.assertContains(response, self.LOGIN_FORM_KEY, html=True) # So, we shouldn't have gotten a lock-out yet. # But we should get one now response = self.login(is_valid_username=True, is_valid_password=False) self.assertContains(response, self.LOCKED_MESSAGE, status_code=429) @override_settings(AXES_LOCKOUT_PARAMETERS=["username"]) def test_lockout_by_only_user_failures(self): """ Test login failure when lockout parameter is username. """ # test until one try before the limit for _ in range(1, settings.AXES_FAILURE_LIMIT): response = self._login(self.username, self.WRONG_PASSWORD) # Check if we are in the same login page self.assertContains(response, self.LOGIN_FORM_KEY, html=True) # So, we shouldn't have gotten a lock-out yet. # But we should get one now response = self._login(self.username, self.WRONG_PASSWORD) self.assertContains(response, self.LOCKED_MESSAGE, status_code=self.BLOCKED) # reset the username only and make sure we can log in now even though our IP has failed each time self.reset(username=self.username) response = self._login(self.username, self.password) # Check if we are still in the login page self.assertNotContains( response, self.LOGIN_FORM_KEY, status_code=self.ALLOWED, html=True ) # now create failure_limit + 1 failed logins and then we should still # be able to login with valid_username for _ in range(settings.AXES_FAILURE_LIMIT): response = self._login(self.username, self.password) # Check if we can still log in with valid user response = self._login(self.username, self.password) self.assertNotContains( response, self.LOGIN_FORM_KEY, status_code=self.ALLOWED, html=True ) @override_settings(AXES_LOCKOUT_PARAMETERS=["user_agent"]) def test_lockout_by_user_agent_only(self): """ Test login failure when lockout parameter is only user_agent """ # User is locked out with "test-browser" user agent. self._lockout_user_from_ip(username="username", ip_addr=self.IP_1, user_agent="test-browser") # Test he is locked: response = self._login("username", self.VALID_PASSWORD, ip_addr=self.IP_1, user_agent="test-browser") self.assertEqual(response.status_code, self.BLOCKED) # Test he is locked with another username: response = self._login("username2", self.VALID_PASSWORD, ip_addr=self.IP_1, user_agent="test-browser") self.assertEqual(response.status_code, self.BLOCKED) # Test he is locked with another ip: response = self._login("username", self.VALID_PASSWORD, ip_addr=self.IP_2, user_agent="test-browser") self.assertEqual(response.status_code, self.BLOCKED) # Test with another user agent: response = self._login("username", self.VALID_PASSWORD, ip_addr=self.IP_1, user_agent="test-browser-2") self.assertEqual(response.status_code, self.ATTEMPT_NOT_BLOCKED) @override_settings(AXES_LOCKOUT_PARAMETERS=["ip_address", "username", "user_agent"]) def test_lockout_by_all_parameters(self): # User is locked out with "test-browser" user agent. self._lockout_user_from_ip(username="username", ip_addr=self.IP_1, user_agent="test-browser") # Test he is locked: response = self._login("username", self.VALID_PASSWORD, ip_addr=self.IP_1, user_agent="test-browser") self.assertEqual(response.status_code, self.BLOCKED) # Test he is locked by username: response = self._login("username", self.VALID_PASSWORD, ip_addr=self.IP_2, user_agent="test-browser2") self.assertEqual(response.status_code, self.BLOCKED) # Test he is locked by ip: response = self._login("username2", self.VALID_PASSWORD, ip_addr=self.IP_1, user_agent="test-browser2") self.assertEqual(response.status_code, self.BLOCKED) # Test he is locked by user_agent: response = self._login("username2", self.VALID_PASSWORD, ip_addr=self.IP_2, user_agent="test-browser") self.assertEqual(response.status_code, self.BLOCKED) # Test he is allowed to login with different username, ip and user_agent response = self._login("username2", self.VALID_PASSWORD, ip_addr=self.IP_2, user_agent="test-browser2") self.assertEqual(response.status_code, self.ATTEMPT_NOT_BLOCKED) @override_settings(AXES_LOCKOUT_PARAMETERS=[["ip_address", "username", "user_agent"]]) def test_lockout_by_combination_of_all_parameters(self): # User is locked out with "test-browser" user agent. self._lockout_user_from_ip(username="username", ip_addr=self.IP_1, user_agent="test-browser") # Test he is locked: response = self._login("username", self.VALID_PASSWORD, ip_addr=self.IP_1, user_agent="test-browser") self.assertEqual(response.status_code, self.BLOCKED) # Test he is allowed to login with different username: response = self._login("username2", self.VALID_PASSWORD, ip_addr=self.IP_1, user_agent="test-browser") self.assertEqual(response.status_code, self.ATTEMPT_NOT_BLOCKED) # Test he is allowed to login with different IP: response = self._login("username", self.VALID_PASSWORD, ip_addr=self.IP_2, user_agent="test-browser") self.assertEqual(response.status_code, self.ATTEMPT_NOT_BLOCKED) # Test he is allowed to login with different user_agent: response = self._login("username", self.VALID_PASSWORD, ip_addr=self.IP_1, user_agent="test-browser2") self.assertEqual(response.status_code, self.ATTEMPT_NOT_BLOCKED) # Test he is allowed to login with different username, ip and user_agent response = self._login("username2", self.VALID_PASSWORD, ip_addr=self.IP_2, user_agent="test-browser2") self.assertEqual(response.status_code, self.ATTEMPT_NOT_BLOCKED) @override_settings(AXES_LOCKOUT_PARAMETERS=["ip_address", ["username", "user_agent"]]) def test_lockout_by_ip_or_username_and_user_agent(self): # User is locked out with "test-browser" user agent. self._lockout_user_from_ip(username="username", ip_addr=self.IP_1, user_agent="test-browser") # Test he is locked: response = self._login("username", self.VALID_PASSWORD, ip_addr=self.IP_1, user_agent="test-browser") self.assertEqual(response.status_code, self.BLOCKED) # Test he is locked by ip: response = self._login("username2", self.VALID_PASSWORD, ip_addr=self.IP_1, user_agent="test-browser2") self.assertEqual(response.status_code, self.BLOCKED) # Test he is locked by username and user_agent: response = self._login("username", self.VALID_PASSWORD, ip_addr=self.IP_2, user_agent="test-browser") self.assertEqual(response.status_code, self.BLOCKED) # Test he is allowed to login with different username and ip response = self._login("username2", self.VALID_PASSWORD, ip_addr=self.IP_2, user_agent="test-browser") self.assertEqual(response.status_code, self.ATTEMPT_NOT_BLOCKED) # Test he is allowed to login with different user_agent and ip response = self._login("username", self.VALID_PASSWORD, ip_addr=self.IP_2, user_agent="test-browser2") self.assertEqual(response.status_code, self.ATTEMPT_NOT_BLOCKED) # Test he is allowed to login with different username, ip and user_agent response = self._login("username2", self.VALID_PASSWORD, ip_addr=self.IP_2, user_agent="test-browser2") self.assertEqual(response.status_code, self.ATTEMPT_NOT_BLOCKED) @override_settings(AXES_LOCKOUT_PARAMETERS=[["ip_address", "user_agent"], ["username", "user_agent"]]) def test_lockout_by_ip_and_user_agent_or_username_and_user_agent(self): # User is locked out with "test-browser" user agent. self._lockout_user_from_ip(username="username", ip_addr=self.IP_1, user_agent="test-browser") # Test he is locked: response = self._login("username", self.VALID_PASSWORD, ip_addr=self.IP_1, user_agent="test-browser") self.assertEqual(response.status_code, self.BLOCKED) # Test he is locked by ip and user_agent: response = self._login("username2", self.VALID_PASSWORD, ip_addr=self.IP_1, user_agent="test-browser") self.assertEqual(response.status_code, self.BLOCKED) # Test he is locked by username and user_agent: response = self._login("username", self.VALID_PASSWORD, ip_addr=self.IP_2, user_agent="test-browser") self.assertEqual(response.status_code, self.BLOCKED) # Test he is allowed to login with different username and ip response = self._login("username2", self.VALID_PASSWORD, ip_addr=self.IP_2, user_agent="test-browser") self.assertEqual(response.status_code, self.ATTEMPT_NOT_BLOCKED) # Test he is allowed to login with different user_agent response = self._login("username", self.VALID_PASSWORD, ip_addr=self.IP_1, user_agent="test-browser2") self.assertEqual(response.status_code, self.ATTEMPT_NOT_BLOCKED) # Test he is allowed to login with different username, ip and user_agent response = self._login("username2", self.VALID_PASSWORD, ip_addr=self.IP_2, user_agent="test-browser2") self.assertEqual(response.status_code, self.ATTEMPT_NOT_BLOCKED) # Test for true and false positives when blocking by IP *OR* user (default) # Cache disabled. Default settings. def test_lockout_by_ip_blocks_when_same_user_same_ip_without_cache(self): # User 1 is locked out from IP 1. self._lockout_user1_from_ip1() # User 1 is still blocked from IP 1. response = self._login(self.USER_1, self.VALID_PASSWORD, ip_addr=self.IP_1) self.assertEqual(response.status_code, self.BLOCKED) def test_lockout_by_ip_allows_when_same_user_diff_ip_without_cache(self): # User 1 is locked out from IP 1. self._lockout_user1_from_ip1() # User 1 can still login from IP 2. response = self._login(self.USER_1, self.VALID_PASSWORD, ip_addr=self.IP_2) self.assertEqual(response.status_code, self.ALLOWED) def test_lockout_by_ip_blocks_when_diff_user_same_ip_without_cache(self): # User 1 is locked out from IP 1. self._lockout_user1_from_ip1() # User 2 is also locked out from IP 1. response = self._login(self.USER_2, self.VALID_PASSWORD, ip_addr=self.IP_1) self.assertEqual(response.status_code, self.BLOCKED) def test_lockout_by_ip_allows_when_diff_user_diff_ip_without_cache(self): # User 1 is locked out from IP 1. self._lockout_user1_from_ip1() # User 2 can still login from IP 2. response = self._login(self.USER_2, self.VALID_PASSWORD, ip_addr=self.IP_2) self.assertEqual(response.status_code, self.ALLOWED) # Test for true and false positives when blocking by user only. # Cache disabled. When AXES_ONLY_USER_FAILURES = True @override_settings(AXES_LOCKOUT_PARAMETERS=["username"]) def test_lockout_by_user_blocks_when_same_user_same_ip_without_cache(self): # User 1 is locked out from IP 1. self._lockout_user1_from_ip1() # User 1 is still blocked from IP 1. response = self._login(self.USER_1, self.VALID_PASSWORD, ip_addr=self.IP_1) self.assertEqual(response.status_code, self.BLOCKED) @override_settings(AXES_LOCKOUT_PARAMETERS=["username"]) def test_lockout_by_user_blocks_when_same_user_diff_ip_without_cache(self): # User 1 is locked out from IP 1. self._lockout_user1_from_ip1() # User 1 is also locked out from IP 2. response = self._login(self.USER_1, self.VALID_PASSWORD, ip_addr=self.IP_2) self.assertEqual(response.status_code, self.BLOCKED) @override_settings(AXES_LOCKOUT_PARAMETERS=["username"]) def test_lockout_by_user_allows_when_diff_user_same_ip_without_cache(self): # User 1 is locked out from IP 1. self._lockout_user1_from_ip1() # User 2 can still login from IP 1. response = self._login(self.USER_2, self.VALID_PASSWORD, ip_addr=self.IP_1) self.assertEqual(response.status_code, self.ALLOWED) @override_settings(AXES_LOCKOUT_PARAMETERS=["username"]) def test_lockout_by_user_allows_when_diff_user_diff_ip_without_cache(self): # User 1 is locked out from IP 1. self._lockout_user1_from_ip1() # User 2 can still login from IP 2. response = self._login(self.USER_2, self.VALID_PASSWORD, ip_addr=self.IP_2) self.assertEqual(response.status_code, self.ALLOWED) @override_settings(AXES_LOCKOUT_PARAMETERS=["username"]) def test_lockout_by_user_with_empty_username_allows_other_users_without_cache(self): # User with empty username is locked out from IP 1. self._lockout_user_from_ip(username="", ip_addr=self.IP_1) # Still possible to access the login page response = self.client.get(reverse("admin:login"), REMOTE_ADDR=self.IP_1) self.assertContains(response, self.LOGIN_FORM_KEY, status_code=200, html=True) # Test for true and false positives when blocking by user and IP together. # Cache disabled. When LOCK_OUT_BY_COMBINATION_USER_AND_IP = True @override_settings(AXES_LOCKOUT_PARAMETERS=[["username", "ip_address"]]) def test_lockout_by_user_and_ip_blocks_when_same_user_same_ip_without_cache(self): # User 1 is locked out from IP 1. self._lockout_user1_from_ip1() # User 1 is still blocked from IP 1. response = self._login(self.USER_1, self.VALID_PASSWORD, ip_addr=self.IP_1) self.assertEqual(response.status_code, self.BLOCKED) @override_settings(AXES_LOCKOUT_PARAMETERS=[["username", "ip_address"]]) def test_lockout_by_user_and_ip_allows_when_same_user_diff_ip_without_cache(self): # User 1 is locked out from IP 1. self._lockout_user1_from_ip1() # User 1 can still login from IP 2. response = self._login(self.USER_1, self.VALID_PASSWORD, ip_addr=self.IP_2) self.assertEqual(response.status_code, self.ALLOWED) @override_settings(AXES_LOCKOUT_PARAMETERS=[["username", "ip_address"]]) def test_lockout_by_user_and_ip_allows_when_diff_user_same_ip_without_cache(self): # User 1 is locked out from IP 1. self._lockout_user1_from_ip1() # User 2 can still login from IP 1. response = self._login(self.USER_2, self.VALID_PASSWORD, ip_addr=self.IP_1) self.assertEqual(response.status_code, self.ALLOWED) @override_settings(AXES_LOCKOUT_PARAMETERS=[["username", "ip_address"]]) def test_lockout_by_user_and_ip_allows_when_diff_user_diff_ip_without_cache(self): # User 1 is locked out from IP 1. self._lockout_user1_from_ip1() # User 2 can still login from IP 2. response = self._login(self.USER_2, self.VALID_PASSWORD, ip_addr=self.IP_2) self.assertEqual(response.status_code, self.ALLOWED) @override_settings(AXES_LOCKOUT_PARAMETERS=[["username", "ip_address"]]) def test_lockout_by_user_and_ip_with_empty_username_allows_other_users_without_cache( self, ): # User with empty username is locked out from IP 1. self._lockout_user_from_ip(username="", ip_addr=self.IP_1) # Still possible to access the login page response = self.client.get(reverse("admin:login"), REMOTE_ADDR=self.IP_1) self.assertContains(response, self.LOGIN_FORM_KEY, status_code=200, html=True) @override_settings(AXES_LOCKOUT_PARAMETERS=[["ip_address", "user_agent"]]) def test_lockout_by_user_still_allows_login_with_differnet_user_agent(self): # User with empty username is locked out with "test-browser" user agent. self._lockout_user_from_ip(username="username", ip_addr=self.IP_1, user_agent="test-browser") # Test he is locked: response = self._login("username", self.VALID_PASSWORD, ip_addr=self.IP_1, user_agent="test-browser") self.assertEqual(response.status_code, self.BLOCKED) # Test with another user agent: response = self._login("username", self.VALID_PASSWORD, ip_addr=self.IP_1, user_agent="test-browser-2") self.assertEqual(response.status_code, self.ATTEMPT_NOT_BLOCKED) # Test for true and false positives when blocking by IP *OR* user (default) # With cache enabled. Default criteria. def test_lockout_by_ip_blocks_when_same_user_same_ip_using_cache(self): # User 1 is locked out from IP 1. self._lockout_user1_from_ip1() # User 1 is still blocked from IP 1. response = self._login(self.USER_1, self.VALID_PASSWORD, ip_addr=self.IP_1) self.assertEqual(response.status_code, self.BLOCKED) def test_lockout_by_ip_allows_when_same_user_diff_ip_using_cache(self): # User 1 is locked out from IP 1. self._lockout_user1_from_ip1() # User 1 can still login from IP 2. response = self._login(self.USER_1, self.VALID_PASSWORD, ip_addr=self.IP_2) self.assertEqual(response.status_code, self.ALLOWED) def test_lockout_by_ip_blocks_when_diff_user_same_ip_using_cache(self): # User 1 is locked out from IP 1. self._lockout_user1_from_ip1() # User 2 is also locked out from IP 1. response = self._login(self.USER_2, self.VALID_PASSWORD, ip_addr=self.IP_1) self.assertEqual(response.status_code, self.BLOCKED) def test_lockout_by_ip_allows_when_diff_user_diff_ip_using_cache(self): # User 1 is locked out from IP 1. self._lockout_user1_from_ip1() # User 2 can still login from IP 2. response = self._login(self.USER_2, self.VALID_PASSWORD, ip_addr=self.IP_2) self.assertEqual(response.status_code, self.ALLOWED) @override_settings(AXES_LOCKOUT_PARAMETERS=["username"]) def test_lockout_by_user_with_empty_username_allows_other_users_using_cache(self): # User with empty username is locked out from IP 1. self._lockout_user_from_ip(username="", ip_addr=self.IP_1) # Still possible to access the login page response = self.client.get(reverse("admin:login"), REMOTE_ADDR=self.IP_1) self.assertContains(response, self.LOGIN_FORM_KEY, status_code=200, html=True) # Test for true and false positives when blocking by user only. # With cache enabled. When AXES_ONLY_USER_FAILURES = True @override_settings(AXES_LOCKOUT_PARAMETERS=["username"]) def test_lockout_by_user_blocks_when_same_user_same_ip_using_cache(self): # User 1 is locked out from IP 1. self._lockout_user1_from_ip1() # User 1 is still blocked from IP 1. response = self._login(self.USER_1, self.VALID_PASSWORD, ip_addr=self.IP_1) self.assertEqual(response.status_code, self.BLOCKED) @override_settings(AXES_LOCKOUT_PARAMETERS=["username"]) def test_lockout_by_user_blocks_when_same_user_diff_ip_using_cache(self): # User 1 is locked out from IP 1. self._lockout_user1_from_ip1() # User 1 is also locked out from IP 2. response = self._login(self.USER_1, self.VALID_PASSWORD, ip_addr=self.IP_2) self.assertEqual(response.status_code, self.BLOCKED) @override_settings(AXES_LOCKOUT_PARAMETERS=["username"]) def test_lockout_by_user_allows_when_diff_user_same_ip_using_cache(self): # User 1 is locked out from IP 1. self._lockout_user1_from_ip1() # User 2 can still login from IP 1. response = self._login(self.USER_2, self.VALID_PASSWORD, ip_addr=self.IP_1) self.assertEqual(response.status_code, self.ALLOWED) @override_settings(AXES_LOCKOUT_PARAMETERS=["username"]) def test_lockout_by_user_allows_when_diff_user_diff_ip_using_cache(self): # User 1 is locked out from IP 1. self._lockout_user1_from_ip1() # User 2 can still login from IP 2. response = self._login(self.USER_2, self.VALID_PASSWORD, ip_addr=self.IP_2) self.assertEqual(response.status_code, self.ALLOWED) # Test for true and false positives when blocking by user and IP together. # With cache enabled. When LOCK_OUT_BY_COMBINATION_USER_AND_IP = True @override_settings(AXES_LOCKOUT_PARAMETERS=[["username", "ip_address"]]) def test_lockout_by_user_and_ip_blocks_when_same_user_same_ip_using_cache(self): # User 1 is locked out from IP 1. self._lockout_user1_from_ip1() # User 1 is still blocked from IP 1. response = self._login(self.USER_1, self.VALID_PASSWORD, ip_addr=self.IP_1) self.assertEqual(response.status_code, self.BLOCKED) @override_settings(AXES_LOCKOUT_PARAMETERS=[["username", "ip_address"]]) def test_lockout_by_user_and_ip_allows_when_same_user_diff_ip_using_cache(self): # User 1 is locked out from IP 1. self._lockout_user1_from_ip1() # User 1 can still login from IP 2. response = self._login(self.USER_1, self.VALID_PASSWORD, ip_addr=self.IP_2) self.assertEqual(response.status_code, self.ALLOWED) @override_settings(AXES_LOCKOUT_PARAMETERS=[["username", "ip_address"]]) def test_lockout_by_user_and_ip_allows_when_diff_user_same_ip_using_cache(self): # User 1 is locked out from IP 1. self._lockout_user1_from_ip1() # User 2 can still login from IP 1. response = self._login(self.USER_2, self.VALID_PASSWORD, ip_addr=self.IP_1) self.assertEqual(response.status_code, self.ALLOWED) @override_settings(AXES_LOCKOUT_PARAMETERS=[["username", "ip_address"]]) def test_lockout_by_user_and_ip_allows_when_diff_user_diff_ip_using_cache(self): # User 1 is locked out from IP 1. self._lockout_user1_from_ip1() # User 2 can still login from IP 2. response = self._login(self.USER_2, self.VALID_PASSWORD, ip_addr=self.IP_2) self.assertEqual(response.status_code, self.ALLOWED) @override_settings( AXES_LOCKOUT_PARAMETERS=[["username", "ip_address"]], AXES_FAILURE_LIMIT=2 ) def test_lockout_by_user_and_ip_allows_when_diff_user_same_ip_using_cache_multiple_attempts( self, ): # User 1 is locked out from IP 1. response = self._login(self.USER_1, self.WRONG_PASSWORD, self.IP_1) self.assertEqual(response.status_code, self.ATTEMPT_NOT_BLOCKED) # Second attempt from different IP response = self._login(self.USER_1, self.WRONG_PASSWORD, self.IP_2) self.assertEqual(response.status_code, self.ATTEMPT_NOT_BLOCKED) # Second attempt from same IP, different username response = self._login(self.USER_2, self.WRONG_PASSWORD, self.IP_1) self.assertEqual(response.status_code, self.ATTEMPT_NOT_BLOCKED) # User 1 is blocked from IP 1 response = self._login(self.USER_1, self.WRONG_PASSWORD, ip_addr=self.IP_1) self.assertContains(response, self.LOCKED_MESSAGE, status_code=self.BLOCKED) # User 1 is blocked from IP 2 response = self._login(self.USER_1, self.WRONG_PASSWORD, ip_addr=self.IP_2) self.assertContains(response, self.LOCKED_MESSAGE, status_code=self.BLOCKED) # User 2 can still login from IP 2, only he has 1 attempt left response = self._login(self.USER_2, self.VALID_PASSWORD, ip_addr=self.IP_2) self.assertEqual(response.status_code, self.ALLOWED) @override_settings(AXES_LOCKOUT_PARAMETERS=[["username", "ip_address"]]) def test_lockout_by_user_and_ip_with_empty_username_allows_other_users_using_cache( self, ): # User with empty username is locked out from IP 1. self._lockout_user_from_ip(username="", ip_addr=self.IP_1) # Still possible to access the login page response = self.client.get(reverse("admin:login"), REMOTE_ADDR=self.IP_1) self.assertContains(response, self.LOGIN_FORM_KEY, status_code=200, html=True) # Test for true and false positives when blocking by user or IP together. # With cache enabled. When AXES_LOCK_OUT_BY_USER_OR_IP = True @override_settings(AXES_LOCKOUT_PARAMETERS=["username", "ip_address"]) def test_lockout_by_user_or_ip_blocks_when_same_user_same_ip_using_cache(self): # User 1 is locked out from IP 1. self._lockout_user1_from_ip1() # User 1 is still blocked from IP 1. response = self._login(self.USER_1, self.VALID_PASSWORD, ip_addr=self.IP_1) self.assertEqual(response.status_code, self.BLOCKED) @override_settings(AXES_LOCKOUT_PARAMETERS=["username", "ip_address"]) def test_lockout_by_user_or_ip_allows_when_same_user_diff_ip_using_cache(self): # User 1 is locked out from IP 1. self._lockout_user1_from_ip1() # User 1 is blocked out from IP 1 response = self._login(self.USER_1, self.VALID_PASSWORD, ip_addr=self.IP_2) self.assertEqual(response.status_code, self.BLOCKED) @override_settings(AXES_LOCKOUT_PARAMETERS=["username", "ip_address"]) def test_lockout_by_user_or_ip_allows_when_diff_user_same_ip_using_cache(self): # User 1 is locked out from IP 1. self._lockout_user1_from_ip1() # User 2 can still login from IP 1. response = self._login(self.USER_2, self.VALID_PASSWORD, ip_addr=self.IP_1) self.assertEqual(response.status_code, self.BLOCKED) @override_settings( AXES_LOCKOUT_PARAMETERS=["username", "ip_address"], AXES_FAILURE_LIMIT=3 ) def test_lockout_by_user_or_ip_allows_when_diff_user_same_ip_using_cache_multiple_attempts( self, ): # User 1 is locked out from IP 1. response = self._login(self.USER_1, self.WRONG_PASSWORD, self.IP_1) self.assertEqual(response.status_code, self.ATTEMPT_NOT_BLOCKED) # Second attempt from different IP response = self._login(self.USER_1, self.WRONG_PASSWORD, self.IP_2) self.assertEqual(response.status_code, self.ATTEMPT_NOT_BLOCKED) # User 1 is blocked on all IPs, he reached 2 attempts response = self._login(self.USER_1, self.WRONG_PASSWORD, ip_addr=self.IP_2) self.assertContains(response, self.LOCKED_MESSAGE, status_code=self.BLOCKED) response = self._login(self.USER_1, self.WRONG_PASSWORD, ip_addr=self.IP_3) self.assertContains(response, self.LOCKED_MESSAGE, status_code=self.BLOCKED) # IP 1 has still one attempt left response = self._login(self.USER_2, self.WRONG_PASSWORD, self.IP_1) self.assertEqual(response.status_code, self.ATTEMPT_NOT_BLOCKED) # But now IP 1 is blocked for all attempts response = self._login(self.USER_1, self.WRONG_PASSWORD, ip_addr=self.IP_1) self.assertContains(response, self.LOCKED_MESSAGE, status_code=self.BLOCKED) response = self._login(self.USER_2, self.WRONG_PASSWORD, ip_addr=self.IP_1) self.assertContains(response, self.LOCKED_MESSAGE, status_code=self.BLOCKED) response = self._login(self.USER_3, self.WRONG_PASSWORD, ip_addr=self.IP_1) self.assertContains(response, self.LOCKED_MESSAGE, status_code=self.BLOCKED) @override_settings( AXES_LOCKOUT_PARAMETERS=["username", "ip_address"], AXES_FAILURE_LIMIT=3 ) def test_lockout_by_user_or_ip_allows_when_diff_user_same_ip_using_cache_multiple_failed_attempts( self, ): """Test, if the failed attempts make also impact on the attempt count""" # User 1 is locked out from IP 1. response = self._login(self.USER_1, self.WRONG_PASSWORD, self.IP_1) self.assertEqual(response.status_code, self.ATTEMPT_NOT_BLOCKED) # Second attempt from different IP response = self._login(self.USER_1, self.WRONG_PASSWORD, self.IP_2) self.assertEqual(response.status_code, self.ATTEMPT_NOT_BLOCKED) # Second attempt from same IP, different username response = self._login(self.USER_2, self.WRONG_PASSWORD, self.IP_1) self.assertEqual(response.status_code, self.ATTEMPT_NOT_BLOCKED) # User 1 is blocked from IP 2 response = self._login(self.USER_1, self.WRONG_PASSWORD, ip_addr=self.IP_2) self.assertContains(response, self.LOCKED_MESSAGE, status_code=self.BLOCKED) # On IP 2 it is only 2. attempt, for user 2 it is also 2. attempt -> allow log in response = self._login(self.USER_2, self.VALID_PASSWORD, ip_addr=self.IP_2) self.assertEqual(response.status_code, self.ALLOWED) @override_settings(AXES_LOCKOUT_PARAMETERS=["username", "ip_address"]) def test_lockout_by_user_or_ip_allows_when_diff_user_diff_ip_using_cache(self): # User 1 is locked out from IP 1. self._lockout_user1_from_ip1() # User 2 can still login from IP 2. response = self._login(self.USER_2, self.VALID_PASSWORD, ip_addr=self.IP_2) self.assertEqual(response.status_code, self.ALLOWED) @override_settings(AXES_LOCKOUT_PARAMETERS=["username", "ip_address"]) def test_lockout_by_user_or_ip_with_empty_username_allows_other_users_using_cache( self, ): # User with empty username is locked out from IP 1. self._lockout_user_from_ip(username="", ip_addr=self.IP_1) # Still possible to access the login page response = self.client.get(reverse("admin:login"), REMOTE_ADDR=self.IP_1) self.assertContains(response, self.LOGIN_FORM_KEY, status_code=200, html=True) @override_settings( AXES_COOLOFF_TIME=timedelta(seconds=1), AXES_RESET_COOL_OFF_ON_FAILURE_DURING_LOCKOUT=False, AXES_FAILURE_LIMIT=2, ) def test_login_during_lockout_doesnt_reset_cool_off_time(self): # Lockout for _ in range(get_failure_limit(None, None)): self.login(self.USER_1) # Attempt during lockout sleep_time = get_cool_off().total_seconds() / 2 sleep(sleep_time) self.login(self.USER_1) sleep(sleep_time) # New attempt after initial lockout period: should work response = self.login(is_valid_username=True, is_valid_password=True) self.assertNotContains(response, self.LOCKED_MESSAGE, status_code=self.ALLOWED) @override_settings( AXES_COOLOFF_TIME=timedelta(seconds=1), AXES_RESET_COOL_OFF_ON_FAILURE_DURING_LOCKOUT=True, AXES_FAILURE_LIMIT=2, ) def test_login_during_lockout_does_reset_cool_off_time(self): # Lockout for _ in range(get_failure_limit(None, None)): self.login(self.USER_1) # Attempt during lockout sleep_time = get_cool_off().total_seconds() / 2 sleep(sleep_time) self.login(self.USER_1) sleep(sleep_time) # New attempt after initial lockout period: should not work response = self.login(is_valid_username=True, is_valid_password=True) self.assertContains(response, self.LOCKED_MESSAGE, status_code=self.BLOCKED) # Test the same logic with cache handler @override_settings(AXES_HANDLER="axes.handlers.cache.AxesCacheHandler") class CacheLoginTestCase(DatabaseLoginTestCase): def attempt_count(self): cache = get_cache() keys = cache._cache return len(keys) def reset(self, **kwargs): get_cache().delete(make_cache_key_list([kwargs])[0]) django-axes-7.0.1/tests/test_management.py000066400000000000000000000101131472335743500206170ustar00rootroot00000000000000from io import StringIO from unittest.mock import patch, Mock from django.core.management import call_command from django.utils import timezone from axes.models import AccessAttempt, AccessLog from tests.base import AxesTestCase class ResetAccessLogsManagementCommandTestCase(AxesTestCase): def setUp(self): self.msg_not_found = "No logs found.\n" self.msg_num_found = "{} logs removed.\n" days_3 = timezone.now() - timezone.timedelta(days=3) with patch("django.utils.timezone.now", Mock(return_value=days_3)): AccessLog.objects.create() days_13 = timezone.now() - timezone.timedelta(days=9) with patch("django.utils.timezone.now", Mock(return_value=days_13)): AccessLog.objects.create() days_30 = timezone.now() - timezone.timedelta(days=27) with patch("django.utils.timezone.now", Mock(return_value=days_30)): AccessLog.objects.create() def test_axes_delete_access_logs_default(self): out = StringIO() call_command("axes_reset_logs", stdout=out) self.assertEqual(self.msg_not_found, out.getvalue()) def test_axes_delete_access_logs_older_than_2_days(self): out = StringIO() call_command("axes_reset_logs", age=2, stdout=out) self.assertEqual(self.msg_num_found.format(3), out.getvalue()) def test_axes_delete_access_logs_older_than_4_days(self): out = StringIO() call_command("axes_reset_logs", age=4, stdout=out) self.assertEqual(self.msg_num_found.format(2), out.getvalue()) def test_axes_delete_access_logs_older_than_16_days(self): out = StringIO() call_command("axes_reset_logs", age=16, stdout=out) self.assertEqual(self.msg_num_found.format(1), out.getvalue()) class ManagementCommandTestCase(AxesTestCase): def setUp(self): AccessAttempt.objects.create( username="jane.doe", ip_address="10.0.0.1", failures_since_start="4" ) AccessAttempt.objects.create( username="john.doe", ip_address="10.0.0.2", failures_since_start="15" ) AccessAttempt.objects.create( username="richard.doe", ip_address="10.0.0.4", failures_since_start="12" ) def test_axes_list_attempts(self): out = StringIO() call_command("axes_list_attempts", stdout=out) expected = "10.0.0.1\tjane.doe\t4\n10.0.0.2\tjohn.doe\t15\n10.0.0.4\trichard.doe\t12\n" self.assertEqual(expected, out.getvalue()) def test_axes_reset(self): out = StringIO() call_command("axes_reset", stdout=out) expected = "3 attempts removed.\n" self.assertEqual(expected, out.getvalue()) def test_axes_reset_not_found(self): out = StringIO() call_command("axes_reset", stdout=out) out = StringIO() call_command("axes_reset", stdout=out) expected = "No attempts found.\n" self.assertEqual(expected, out.getvalue()) def test_axes_reset_ip(self): out = StringIO() call_command("axes_reset_ip", "10.0.0.1", stdout=out) expected = "1 attempts removed.\n" self.assertEqual(expected, out.getvalue()) def test_axes_reset_ip_username(self): out = StringIO() call_command("axes_reset_ip_username", "10.0.0.4", "richard.doe", stdout=out) expected = "1 attempts removed.\n" self.assertEqual(expected, out.getvalue()) def test_axes_reset_ip_not_found(self): out = StringIO() call_command("axes_reset_ip", "10.0.0.3", stdout=out) expected = "No attempts found.\n" self.assertEqual(expected, out.getvalue()) def test_axes_reset_username(self): out = StringIO() call_command("axes_reset_username", "john.doe", stdout=out) expected = "1 attempts removed.\n" self.assertEqual(expected, out.getvalue()) def test_axes_reset_username_not_found(self): out = StringIO() call_command("axes_reset_username", "ivan.renko", stdout=out) expected = "No attempts found.\n" self.assertEqual(expected, out.getvalue()) django-axes-7.0.1/tests/test_middleware.py000066400000000000000000000034701472335743500206300ustar00rootroot00000000000000from django.conf import settings from django.http import HttpResponse, HttpRequest from django.test import override_settings from axes.middleware import AxesMiddleware from tests.base import AxesTestCase def get_username(request, credentials: dict) -> str: return credentials.get(settings.AXES_USERNAME_FORM_FIELD) class MiddlewareTestCase(AxesTestCase): STATUS_SUCCESS = 200 STATUS_LOCKOUT = 429 def setUp(self): self.request = HttpRequest() def test_success_response(self): def get_response(request): request.axes_locked_out = False return HttpResponse() response = AxesMiddleware(get_response)(self.request) self.assertEqual(response.status_code, self.STATUS_SUCCESS) def test_lockout_response(self): def get_response(request): request.axes_locked_out = True return HttpResponse() response = AxesMiddleware(get_response)(self.request) self.assertEqual(response.status_code, self.STATUS_LOCKOUT) @override_settings(AXES_USERNAME_CALLABLE="tests.test_middleware.get_username") def test_lockout_response_with_axes_callable_username(self): def get_response(request): request.axes_locked_out = True request.axes_credentials = {settings.AXES_USERNAME_FORM_FIELD: 'username'} return HttpResponse() response = AxesMiddleware(get_response)(self.request) self.assertEqual(response.status_code, self.STATUS_LOCKOUT) @override_settings(AXES_ENABLED=False) def test_respects_enabled_switch(self): def get_response(request): request.axes_locked_out = True return HttpResponse() response = AxesMiddleware(get_response)(self.request) self.assertEqual(response.status_code, self.STATUS_SUCCESS) django-axes-7.0.1/tests/test_models.py000066400000000000000000000024511472335743500177740ustar00rootroot00000000000000from django.apps.registry import apps from django.db import connection from django.db.migrations.autodetector import MigrationAutodetector from django.db.migrations.executor import MigrationExecutor from django.db.migrations.state import ProjectState from axes.models import AccessAttempt, AccessLog, AccessFailureLog from tests.base import AxesTestCase class ModelsTestCase(AxesTestCase): def setUp(self): self.failures_since_start = 42 self.access_attempt = AccessAttempt( failures_since_start=self.failures_since_start ) self.access_log = AccessLog() self.access_failure_log = AccessFailureLog() def test_access_attempt_str(self): self.assertIn("Access", str(self.access_attempt)) def test_access_log_str(self): self.assertIn("Access", str(self.access_log)) def test_access_failure_log_str(self): self.assertIn("Failed", str(self.access_failure_log)) class MigrationsTestCase(AxesTestCase): def test_missing_migrations(self): executor = MigrationExecutor(connection) autodetector = MigrationAutodetector( executor.loader.project_state(), ProjectState.from_apps(apps) ) changes = autodetector.changes(graph=executor.loader.graph) self.assertEqual({}, changes) django-axes-7.0.1/tests/test_signals.py000066400000000000000000000007511472335743500201520ustar00rootroot00000000000000from unittest.mock import MagicMock from axes.signals import user_locked_out from tests.base import AxesTestCase class SignalTestCase(AxesTestCase): def test_send_lockout_signal(self): """ Test if the lockout signal is correctly emitted when user is locked out. """ handler = MagicMock() user_locked_out.connect(handler) self.assertEqual(0, handler.call_count) self.lockout() self.assertEqual(1, handler.call_count) django-axes-7.0.1/tests/urls.py000066400000000000000000000001601472335743500164320ustar00rootroot00000000000000from django.contrib import admin from django.urls import path urlpatterns = [path("admin/", admin.site.urls)] django-axes-7.0.1/tests/urls_empty.py000066400000000000000000000000271472335743500176520ustar00rootroot00000000000000urlpatterns: list = []