././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1643879366.0197256 django-titofisto-0.2.2/CHANGELOG.md0000644000000000000000000000275600000000000013511 0ustar00# Changelog All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [0.2.2] - 2022-02-03 ### Fixed - Non-existing files in the public namespace erroneously raised interal server errors. ## [0.2.1] – 2021-12-07 ### Changed - Allow Django 4.0 ## [0.2.0] - 2021-10-24 ### Changed - Provide mechanism to make files in a public namespace accessible without a token. ## [0.1.2.post1] - 2021-05-17 ### Changed - Amend mistakes in changelog ## [0.1.2] - 2021-05-17 ### Changed - Combine timestamp into token parameter - (Dev) Move settings handling into separate module ## [0.1.1] - 2021-05-16 ### Fixed - Fall back to current time if file does not exist to get mtime ## [0.1.0] - 2021-05-16 ### Added - Initial release, as described in readme [Unreleased]: https://edugit.org/AlekSIS/libs/django-titofisto/-/tree/master [0.1.0]: https://edugit.org/AlekSIS/libs/django-titofisto/-/tags/0.1.0 [0.1.1]: https://edugit.org/AlekSIS/libs/django-titofisto/-/tags/0.1.1 [0.1.2]: https://edugit.org/AlekSIS/libs/django-titofisto/-/tags/0.1.2 [0.1.2.post1]: https://edugit.org/AlekSIS/libs/django-titofisto/-/tags/0.1.2.post1 [0.2.0]: https://edugit.org/AlekSIS/libs/django-titofisto/-/tags/0.2.0 [0.2.1]: https://edugit.org/AlekSIS/libs/django-titofisto/-/tags/0.2.1 [0.2.2]: https://edugit.org/AlekSIS/libs/django-titofisto/-/tags/0.2.2 ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1638871852.5925097 django-titofisto-0.2.2/LICENSE0000644000000000000000000002615500000000000012704 0ustar00 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright 2021 Dominik George Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1638871852.5925097 django-titofisto-0.2.2/README.rst0000644000000000000000000000567300000000000013370 0ustar00Django Time-Token File Storage ============================== This is a simple extension to Django's `FileSystemStorage` that adds a URL parameter carrying a shared token, which is only valid for a defined period of time. Functionality ------------- This is a drop-in replacement for the Django `FileSystemStorage`, usable if media files are served by Django itself. It does currently not work if media files are served from an independent web server. The storage and its accompanying view do the following: * When a URL to a storage file is generated, a HMAC-based token is generated * The token and the timestamp when it was generated are appended as request parameters to the URL * Upon retrieval of the file through the accompanying view, the requested file name and the passed timestamp are used to recalculate the HMAC-based token * Only if the tokens match, and a configured timeout has not passed, is the file served The HMAC-based token ensures that the token is invalidated when: * The filename changes * The timestamp changes * The mtime of the file changes * The `SECRET_KEY` changes The HMAC is salted with the `SECRET_KEY`. Installation ------------ To add `django-titofisto`_ to a project, first add it as dependency to your project, e.g. using `poetry`_:: $ poetry add django-titofisto `django-titofisto` will use the base `FileSystemStorage` for almost everything, including determining the `MEDIA_ROOT`. It merely adds a token as URL parameter to whatever the base `FileSystemStorage.url()` method returns. Add the following to your settings:: DEFAULT_FILE_STORAGE = "titofisto.TitofistoStorage" TITOFISTO_TIMEOUT = 3600 # optional, this is the default TITOFISTO_PARAM = "titofisto_token" # optional, this is the default Add the following to your URL config:: from django.conf import settings from django.urls import include, path urlpatterns += [ path(settings.MEDIA_URL.removeprefix("/"), include("titofisto.urls")), ] Django will start serving media files under the configured `MEDIA_URL`. Provide public media files ~~~~~~~~~~~~~~~~~~~~~~~~~~ Sometimes, there might be media files, for example favicons, you want to be accessible without any authentication. Per default, `django-titofisto` will serve all files stored in the directory `public` without a token. You can disable or configure this behavior using these settings: TITOFISTO_USE_PUBLIC_NAMESPACE = True # optional, this is the default TITOFISTO_PUBLIC_NAMESPACE = "public/" # optional, this is the default Credits ------- `django-titofisto` was developed for the `AlekSIS`_ school information system by its team. Copyright © 2021 Dominik George Copyright © 2021 Jonathan Weth .. _django-titofisto: https://edugit.org/AlekSIS/libs/django-titofisto .. _poetry: https://python-poetry.org/ .. _Django's cache framework: https://docs.djangoproject.com/en/3.2/topics/cache/ .. _AlekSIS: https://aleksis.org/ ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1643879377.2597015 django-titofisto-0.2.2/pyproject.toml0000644000000000000000000000146100000000000014604 0ustar00[tool.poetry] name = "django-titofisto" version = "0.2.2" description = "Django Time-Token File Storage" authors = ["Dominik George ", "Jonathan Weth "] license = "Apache-2.0" readme = "README.rst" repository = "https://edugit.org/AlekSIS/libs/django-titofisto" keywords = ["django", "storage", "media", "secure"] classifiers = [ "Development Status :: 4 - Beta", "Environment :: Web Environment", "Framework :: Django", "Intended Audience :: Developers", ] packages = [ { include = "titofisto" }, ] include = ["LICENSE", "CHANGELOG.md"] [tool.poetry.dependencies] python = "^3.9" Django = ">2.2,<5.0" [tool.poetry.dev-dependencies] freezegun = "^1.1.0" [build-system] requires = ["poetry-core>=1.0.0"] build-backend = "poetry.core.masonry.api" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1638871852.5925097 django-titofisto-0.2.2/titofisto/__init__.py0000644000000000000000000000004600000000000016023 0ustar00from .storage import TitofistoStorage ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1638871852.5925097 django-titofisto-0.2.2/titofisto/settings.py0000644000000000000000000000047300000000000016130 0ustar00from django.conf import settings PARAM = getattr(settings, "TITOFISTO_PARAM", "titofisto_token") TIMEOUT = getattr(settings, "TITOFISTO_TIMEOUT", 60 * 60) USE_PUBLIC_NAMESPACE = getattr(settings, "TITOFISTO_USE_PUBLIC_NAMESPACE", True) PUBLIC_NAMESPACE = getattr(settings, "TITOFISTO_PUBLIC_NAMESPACE", "public/") ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1638871852.5925097 django-titofisto-0.2.2/titofisto/storage.py0000644000000000000000000000301000000000000015722 0ustar00import hmac from datetime import datetime from typing import Optional from django.conf import settings from django.core.files.storage import FileSystemStorage from .settings import PARAM, USE_PUBLIC_NAMESPACE, PUBLIC_NAMESPACE class TitofistoStorage(FileSystemStorage): """Time-token secured variant of the base filesystem storage.""" def url(self, name: str) -> str: """Compute URL for requested storage file.""" # Get regular URL from base FileSystemStorage raw_url = super().url(name) if USE_PUBLIC_NAMESPACE: # Public files are accessible without a token if name.startswith(PUBLIC_NAMESPACE): return raw_url # Get token and timestamp token = self.get_token(name) # Generate full, token-secured URL full_url = f"{raw_url}?{PARAM}={token}" return full_url def get_token(self, name: str, ts: Optional[int] = None) -> str: """Get a token for a filename.""" # Determine parts of the HMAC from the file if self.exists(name): mtime = self.get_modified_time(name).isoformat() else: mtime = datetime.now().isoformat() if ts is None: ts = int(datetime.now().strftime("%s")) full_msg = f"{name}//{mtime}@{ts}" # Calculate a HMAC with the parts token = hmac.new( bytes(settings.SECRET_KEY, "utf-8"), msg=bytes(full_msg, "utf-8"), digestmod="sha256" ).hexdigest() + hex(ts)[2:] return token ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1638871852.5925097 django-titofisto-0.2.2/titofisto/test_settings.py0000644000000000000000000000127500000000000017170 0ustar00from tempfile import mkdtemp # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = "yiv&ahwdi^^_(m63-%uok#9k6vp#6*p=@d+a=hk4vj62=me5&2" # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ["*"] # Application definition INSTALLED_APPS = [] MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", ] ROOT_URLCONF = "titofisto.test_urls" WSGI_APPLICATION = "titofisto_example.wsgi.application" USE_TZ = True MEDIA_ROOT = mkdtemp() MEDIA_URL = "/media/" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1638871852.5925097 django-titofisto-0.2.2/titofisto/test_urls.py0000644000000000000000000000024500000000000016311 0ustar00from django.conf import settings from django.urls import include, path urlpatterns = [ path(settings.MEDIA_URL.removeprefix("/"), include("titofisto.urls")), ] ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1643879317.3598301 django-titofisto-0.2.2/titofisto/tests.py0000644000000000000000000001404300000000000015430 0ustar00from datetime import datetime, timedelta from io import BytesIO from pathlib import Path from unittest import TestCase from freezegun import freeze_time from django.conf import settings from django.test import Client from .storage import TitofistoStorage class TitofistoTestCase(TestCase): def setUp(self): self.storage = TitofistoStorage() self.test_file_1 = b"The quick brown fox jumps over the lazy dog" self.test_file_1_name = "quickfox.dat" self.storage.save(self.test_file_1_name, BytesIO(self.test_file_1)) self.test_file_2 = b"Franz jagt im komplett verwahrlosten Taxi quer durch Bayern" self.test_file_2_name = "franztaxi.dat" self.storage.save(self.test_file_2_name, BytesIO(self.test_file_2)) self.test_file_3 = b"Franz jagt im komplett verwahrlosten Taxi quer durch Bayern" self.test_file_3_name = "public/franztaxi.dat" self.storage.save(self.test_file_3_name, BytesIO(self.test_file_3)) self.param = "titofisto_token" self.timeout = 60 * 60 self.client = Client() def tearDown(self): self.storage.delete(self.test_file_1_name) self.storage.delete(self.test_file_2_name) def test_token_deterministic(self): """The generated token is deterministic for a single, unchanged file""" ts = int(datetime.now().strftime("%s")) token_1 = self.storage.get_token(self.test_file_1_name, ts) token_2 = self.storage.get_token(self.test_file_1_name, ts) self.assertEqual(token_1, token_2) def test_token_file_dependent(self): """The generated token is different for different files""" ts = int(datetime.now().strftime("%s")) token_1 = self.storage.get_token(self.test_file_1_name, ts) token_2 = self.storage.get_token(self.test_file_2_name, ts) self.assertNotEqual(token_1, token_2) def test_token_ts_dependent(self): """The generated token is different for different timestamps""" ts_1 = int(datetime.now().strftime("%s")) ts_2 = ts_1 + 5 token_1 = self.storage.get_token(self.test_file_1_name, ts_1) token_2 = self.storage.get_token(self.test_file_2_name, ts_2) self.assertNotEqual(token_1, token_2) def test_get_valid_token(self): """A file can be retrieved with a valid token""" token = self.storage.get_token(self.test_file_1_name) url = ( f"{settings.MEDIA_URL}{self.test_file_1_name}?" f"{self.param}={token}" ) res = self.client.get(url) self.assertEqual(res.status_code, 200) self.assertEqual(list(res.streaming_content)[0], self.test_file_1) def test_get_invalid_token(self): """A file can not be retrieved with an invalid token""" token = self.storage.get_token(self.test_file_1_name) url = ( f"{settings.MEDIA_URL}{self.test_file_1_name}?" f"{self.param}=a{token}" ) res = self.client.get(url) self.assertEqual(res.status_code, 404) def test_get_invalid_ts(self): """A file can not be retrieved with an invalid timestamp""" token = self.storage.get_token(self.test_file_1_name) url = ( f"{settings.MEDIA_URL}{self.test_file_1_name}?" f"{self.param}={token}a" ) res = self.client.get(url) self.assertEqual(res.status_code, 404) def test_get_close_to_timeout(self): """A file can still be retrieved close to the timeout""" now = datetime.now() token = self.storage.get_token(self.test_file_1_name, int(now.strftime("%s"))) url = ( f"{settings.MEDIA_URL}{self.test_file_1_name}?" f"{self.param}={token}" ) with freeze_time(now + timedelta(seconds=self.timeout - 1)): res = self.client.get(url) self.assertEqual(res.status_code, 200) self.assertEqual(list(res.streaming_content)[0], self.test_file_1) def test_get_after_timeout(self): """A file can not be retrieved after the timeout""" now = datetime.now() token = self.storage.get_token(self.test_file_1_name, int(now.strftime("%s"))) url = ( f"{settings.MEDIA_URL}{self.test_file_1_name}?" f"{self.param}={token}" ) with freeze_time(now + timedelta(seconds=self.timeout + 1)): res = self.client.get(url) self.assertEqual(res.status_code, 404) def test_get_after_mtime_change(self): """A file can not be retrieved with the same token after its mtime changes""" now = datetime.now() token = self.storage.get_token(self.test_file_1_name, int(now.strftime("%s"))) url = ( f"{settings.MEDIA_URL}{self.test_file_1_name}?" f"{self.param}={token}" ) with freeze_time(now + timedelta(seconds=10)): Path(self.storage.path(self.test_file_1_name)).touch() res = self.client.get(url) self.assertEqual(res.status_code, 404) def test_url(self): """The URL for a file should contain a token.""" url1 = self.storage.url(self.test_file_1_name) url2 = self.storage.url(self.test_file_2_name) self.assertIn(self.param, url1) self.assertIn(self.param, url2) def test_public_files_url(self): """The URL for a file in the public namespace doesn't contain a token.""" url = self.storage.url(self.test_file_3_name) self.assertNotIn(self.param, url) def test_public_files_view(self): """A file in the public namespace can be acessed without a token.""" self.storage.url(self.test_file_3_name) url = ( f"{settings.MEDIA_URL}{self.test_file_3_name}" ) res = self.client.get(url) self.assertEqual(res.status_code, 200) def test_404_not_found(self): """A 404 is returned for non-existent files.""" url = (f"{settings.MEDIA_URL}public/some_not_existing_file.txt") res = self.client.get(url) self.assertEqual(res.status_code, 404) ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1638871852.5925097 django-titofisto-0.2.2/titofisto/urls.py0000644000000000000000000000021600000000000015250 0ustar00from django.urls import path from .views import TitofistoMediaView urlpatterns = [ path("", TitofistoMediaView.as_view()), ] ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1643879317.3598301 django-titofisto-0.2.2/titofisto/views.py0000644000000000000000000000312700000000000015424 0ustar00from datetime import datetime from django.conf import settings from django.http import FileResponse, Http404, HttpRequest from django.views import View from .settings import PARAM, TIMEOUT, USE_PUBLIC_NAMESPACE, PUBLIC_NAMESPACE from .storage import TitofistoStorage class TitofistoMediaView(View): def get(self, request: HttpRequest, name: str) -> FileResponse: # Get storage storage = TitofistoStorage() if USE_PUBLIC_NAMESPACE: # Public files are directly served without needing a token if name.startswith(PUBLIC_NAMESPACE): if storage.exists(name): return FileResponse(storage._open(name)) else: raise Http404() # Inspect URL parameter for completeness and extract timestamp token = request.GET.get(PARAM, None) if token is None: raise Http404() try: ts = int(token[64:], 16) except ValueError: raise Http404() # Compute expected token for filename try: expected_token = storage.get_token(name, ts) except FileNotFoundError: raise Http404() # Compare tokens and raise 404 if they do not match if expected_token != token: raise Http404() # Calculate time difference if timeout is set now = int(datetime.now().strftime("%s")) if TIMEOUT is not None and now - ts > TIMEOUT: raise Http404() # Finally, serve file from disk if all checks passed return FileResponse(storage._open(name)) ././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1643879426.196059 django-titofisto-0.2.2/setup.py0000644000000000000000000000726400000000000013411 0ustar00# -*- coding: utf-8 -*- from setuptools import setup packages = \ ['titofisto'] package_data = \ {'': ['*']} install_requires = \ ['Django>2.2,<5.0'] setup_kwargs = { 'name': 'django-titofisto', 'version': '0.2.2', 'description': 'Django Time-Token File Storage', 'long_description': 'Django Time-Token File Storage\n==============================\n\nThis is a simple extension to Django\'s `FileSystemStorage` that adds a URL\nparameter carrying a shared token, which is only valid for a defined period\nof time.\n\nFunctionality\n-------------\n\nThis is a drop-in replacement for the Django `FileSystemStorage`, usable if\nmedia files are served by Django itself. It does currently not work if media\nfiles are served from an independent web server.\n\nThe storage and its accompanying view do the following:\n\n* When a URL to a storage file is generated, a HMAC-based token is generated\n* The token and the timestamp when it was generated are appended as request\n parameters to the URL\n* Upon retrieval of the file through the accompanying view, the requested\n file name and the passed timestamp are used to recalculate the HMAC-based\n token\n* Only if the tokens match, and a configured timeout has not passed, is the\n file served\n\nThe HMAC-based token ensures that the token is invalidated when:\n\n* The filename changes\n* The timestamp changes\n* The mtime of the file changes\n* The `SECRET_KEY` changes\n\nThe HMAC is salted with the `SECRET_KEY`.\n\nInstallation\n------------\n\nTo add `django-titofisto`_ to a project, first add it as dependency to your\nproject, e.g. using `poetry`_::\n\n $ poetry add django-titofisto\n\n`django-titofisto` will use the base `FileSystemStorage` for almost everything,\nincluding determining the `MEDIA_ROOT`. It merely adds a token as URL parameter\nto whatever the base `FileSystemStorage.url()` method returns.\n\nAdd the following to your settings::\n\n DEFAULT_FILE_STORAGE = "titofisto.TitofistoStorage"\n TITOFISTO_TIMEOUT = 3600 # optional, this is the default\n TITOFISTO_PARAM = "titofisto_token" # optional, this is the default\n\nAdd the following to your URL config::\n\n from django.conf import settings\n from django.urls import include, path\n\n urlpatterns += [\n path(settings.MEDIA_URL.removeprefix("/"), include("titofisto.urls")),\n ]\n\nDjango will start serving media files under the configured `MEDIA_URL`.\n\nProvide public media files\n~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nSometimes, there might be media files, for example favicons,\nyou want to be accessible without any authentication. Per default,\n`django-titofisto` will serve all files stored in the directory `public` without a token.\nYou can disable or configure this behavior using these settings:\n\n TITOFISTO_USE_PUBLIC_NAMESPACE = True # optional, this is the default\n TITOFISTO_PUBLIC_NAMESPACE = "public/" # optional, this is the default\n\nCredits\n-------\n\n`django-titofisto` was developed for the `AlekSIS`_ school information system by\nits team.\n\n Copyright © 2021 Dominik George \n Copyright © 2021 Jonathan Weth \n\n.. _django-titofisto: https://edugit.org/AlekSIS/libs/django-titofisto\n.. _poetry: https://python-poetry.org/\n.. _Django\'s cache framework: https://docs.djangoproject.com/en/3.2/topics/cache/\n.. _AlekSIS: https://aleksis.org/\n', 'author': 'Dominik George', 'author_email': 'dominik.george@teckids.org', 'maintainer': None, 'maintainer_email': None, 'url': 'https://edugit.org/AlekSIS/libs/django-titofisto', 'packages': packages, 'package_data': package_data, 'install_requires': install_requires, 'python_requires': '>=3.9,<4.0', } setup(**setup_kwargs) ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1643879426.1963267 django-titofisto-0.2.2/PKG-INFO0000644000000000000000000000730700000000000012772 0ustar00Metadata-Version: 2.1 Name: django-titofisto Version: 0.2.2 Summary: Django Time-Token File Storage Home-page: https://edugit.org/AlekSIS/libs/django-titofisto License: Apache-2.0 Keywords: django,storage,media,secure Author: Dominik George Author-email: dominik.george@teckids.org Requires-Python: >=3.9,<4.0 Classifier: Development Status :: 4 - Beta Classifier: Environment :: Web Environment Classifier: Framework :: Django Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: Apache Software License Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.9 Requires-Dist: Django (>2.2,<5.0) Project-URL: Repository, https://edugit.org/AlekSIS/libs/django-titofisto Description-Content-Type: text/x-rst Django Time-Token File Storage ============================== This is a simple extension to Django's `FileSystemStorage` that adds a URL parameter carrying a shared token, which is only valid for a defined period of time. Functionality ------------- This is a drop-in replacement for the Django `FileSystemStorage`, usable if media files are served by Django itself. It does currently not work if media files are served from an independent web server. The storage and its accompanying view do the following: * When a URL to a storage file is generated, a HMAC-based token is generated * The token and the timestamp when it was generated are appended as request parameters to the URL * Upon retrieval of the file through the accompanying view, the requested file name and the passed timestamp are used to recalculate the HMAC-based token * Only if the tokens match, and a configured timeout has not passed, is the file served The HMAC-based token ensures that the token is invalidated when: * The filename changes * The timestamp changes * The mtime of the file changes * The `SECRET_KEY` changes The HMAC is salted with the `SECRET_KEY`. Installation ------------ To add `django-titofisto`_ to a project, first add it as dependency to your project, e.g. using `poetry`_:: $ poetry add django-titofisto `django-titofisto` will use the base `FileSystemStorage` for almost everything, including determining the `MEDIA_ROOT`. It merely adds a token as URL parameter to whatever the base `FileSystemStorage.url()` method returns. Add the following to your settings:: DEFAULT_FILE_STORAGE = "titofisto.TitofistoStorage" TITOFISTO_TIMEOUT = 3600 # optional, this is the default TITOFISTO_PARAM = "titofisto_token" # optional, this is the default Add the following to your URL config:: from django.conf import settings from django.urls import include, path urlpatterns += [ path(settings.MEDIA_URL.removeprefix("/"), include("titofisto.urls")), ] Django will start serving media files under the configured `MEDIA_URL`. Provide public media files ~~~~~~~~~~~~~~~~~~~~~~~~~~ Sometimes, there might be media files, for example favicons, you want to be accessible without any authentication. Per default, `django-titofisto` will serve all files stored in the directory `public` without a token. You can disable or configure this behavior using these settings: TITOFISTO_USE_PUBLIC_NAMESPACE = True # optional, this is the default TITOFISTO_PUBLIC_NAMESPACE = "public/" # optional, this is the default Credits ------- `django-titofisto` was developed for the `AlekSIS`_ school information system by its team. Copyright © 2021 Dominik George Copyright © 2021 Jonathan Weth .. _django-titofisto: https://edugit.org/AlekSIS/libs/django-titofisto .. _poetry: https://python-poetry.org/ .. _Django's cache framework: https://docs.djangoproject.com/en/3.2/topics/cache/ .. _AlekSIS: https://aleksis.org/