django-oauthost 1.1.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,86 @@
1
+ Metadata-Version: 2.5
2
+ Name: django-oauthost
3
+ Version: 1.1.2
4
+ Summary: Reusable application for Django to protect your apps with OAuth 2.0.
5
+ Project-URL: Homepage, https://github.com/idlesign/django-oauthost
6
+ Project-URL: Documentation, https://django-oauthost.readthedocs.io/
7
+ Author-email: Igor Starikov <idlesign@yandex.ru>
8
+ License-Expression: BSD-3-Clause
9
+ License-File: LICENSE
10
+ Keywords: Django,oauth2
11
+ Classifier: Development Status :: 5 - Production/Stable
12
+ Classifier: Environment :: Web Environment
13
+ Classifier: Framework :: Django
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: License :: OSI Approved :: BSD License
16
+ Classifier: Operating System :: OS Independent
17
+ Classifier: Programming Language :: Python
18
+ Classifier: Programming Language :: Python :: 3
19
+ Classifier: Programming Language :: Python :: 3.10
20
+ Classifier: Programming Language :: Python :: 3.11
21
+ Classifier: Programming Language :: Python :: 3.12
22
+ Classifier: Programming Language :: Python :: 3.13
23
+ Classifier: Programming Language :: Python :: 3.14
24
+ Requires-Python: >=3.10
25
+ Description-Content-Type: text/markdown
26
+
27
+ # django-oauthost
28
+
29
+ <https://github.com/idlesign/django-oauthost>
30
+
31
+ [![release](https://img.shields.io/pypi/v/django-oauthost.svg)](https://pypi.python.org/pypi/django-oauthost)
32
+ [![lic](https://img.shields.io/pypi/l/django-oauthost.svg)](https://pypi.python.org/pypi/django-oauthost)
33
+ [![coverage](https://img.shields.io/coveralls/idlesign/django-oauthost/master.svg)](https://coveralls.io/r/idlesign/django-oauthost)
34
+
35
+ ## What's that
36
+
37
+ *Reusable application for Django to protect your apps with OAuth 2.0.*
38
+
39
+ It allows to guard your application views with OAuth 2.0 in quite a trivial way.
40
+
41
+ 1. Register your client using Django Admin or API:
42
+
43
+ ```python
44
+ from oauthost.toolbox import register_client
45
+
46
+ ...
47
+
48
+ # Define some scopes to restrict our client to (if required).
49
+ my_scopes = ['polls:vote']
50
+
51
+ # `user` might be `request.user` if in a view.
52
+ register_client('My OAuth Client', 'my_client',
53
+ 'http://someurl.com/myclient/', user, scopes_list=my_scopes)
54
+
55
+ ...
56
+ ```
57
+
58
+ 2. Decorate your views with `oauth_required` (suppose in `polls.views`):
59
+
60
+ ```python
61
+ from oauthost.decorators import oauth_required
62
+
63
+ @oauth_required(scope_auto=True)
64
+ def vote(request, poll_id, variant_id):
65
+ ...
66
+ ```
67
+
68
+ 3. Attach `oauthost.urls` to project `urls` (in `urls.py`):
69
+
70
+ ```python
71
+ from oauthost.urls import urlpatterns as oauthost_urlpatterns
72
+
73
+ urlpatterns = ... # Your actual urlpatterns are ommited.
74
+
75
+ urlpatterns += oauthost_urlpatterns
76
+ ```
77
+
78
+ Now authorization endpoint is available at `{ BASE_URL }auth/` and token endpoint is available at `{ BASE_URL }token/`.
79
+
80
+ That's all for **oauthost**, connect using your client.
81
+
82
+ More information is available, read the docs!
83
+
84
+ ## Documentation
85
+
86
+ <https://django-oauthost.readthedocs.io/>
@@ -0,0 +1,33 @@
1
+ oauthost/__init__.py,sha256=XLG0_Em-6USYDjzZHKxIQaoeO4go5zuHmI2gQEMUxrs,72
2
+ oauthost/admin.py,sha256=ayme9NS6zRJ46jSqMCVSPLrP3-NkoCCOBM-jMyqZdqM,1602
3
+ oauthost/apps.py,sha256=qS5cGumW20moZkYCzCUrGXgUsg2hfNtwGeI2gBzHILA,268
4
+ oauthost/auth_handlers.py,sha256=35pCPHsFaMdTxG8__NTK_dM4zjLw-HffbJMAW5_TPGM,3902
5
+ oauthost/decorators.py,sha256=wzmNmKRxNcLGhcC2WyVoeoME1dkKJOsjuCVLTJH27tI,1176
6
+ oauthost/endpoints.py,sha256=ss4Fv3DT_XvYRjx9OaliREKhp7rvAG6HebnjSNa09P4,35963
7
+ oauthost/exceptions.py,sha256=EDCPM41mxO4Naswji5ZZeS06dUfv_Qz5zDhU3OG2s1s,311
8
+ oauthost/fields.py,sha256=4ovXDg95Ta3fvKLeyvN6W-dC0I2k1pZnFzWBswk-5m8,859
9
+ oauthost/models.py,sha256=hMD8g2j-04Ws7kMHMsLAtXXyRFBI0G5EY2EOrTUQ7bk,12919
10
+ oauthost/settings.py,sha256=CRfZMSmx2J_UFQIfiWvZ9pBaCAW3JVHK85fEmZyY2LA,779
11
+ oauthost/toolbox.py,sha256=IEpMMgaHaT3Ak-SA5GWzLh_pfUjE_yuzNFOXw-7KHts,4138
12
+ oauthost/urls.py,sha256=1JC-1ezBeYwmnXy8d-aLbKnUmCisRpIdIlGlfIe-5Fs,629
13
+ oauthost/utils.py,sha256=3a7ihtNGBrsp6dSS_T2Du-R3Pfpstwn_HrLNEkYM9C0,437
14
+ oauthost/views.py,sha256=pzgjEApPB9V0pW5ChZU4cLVvedUXo2Wu4lqWhNdF0B0,473
15
+ oauthost/locale/en/LC_MESSAGES/django.po,sha256=cbwQwPxC0RHoLsB5KMV7vFHFVBNgVVs_Lt1V-tfKnd8,6175
16
+ oauthost/locale/ru/LC_MESSAGES/django.mo,sha256=ipUlB4AwVPZl53_aKU1p4IZURxopYs0oAoZBFlDJRGQ,9416
17
+ oauthost/locale/ru/LC_MESSAGES/django.po,sha256=X-hhGazu76Bj7Vjwy0F8wW1j9-YTdIyZeCtAVOnJvnM,10999
18
+ oauthost/management/__init__.py,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1
19
+ oauthost/management/commands/__init__.py,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1
20
+ oauthost/management/commands/syncscopes.py,sha256=32ugglkIHRnPyhd4YL1x3Sw1sw24s83EIwWK2KNPmBs,2914
21
+ oauthost/migrations/0001_initial.py,sha256=SYIHPuxFihT_DoBXoeUbfbh97oIAgt4DrJT4d_srTXg,8427
22
+ oauthost/migrations/0002_auto_20150927_1933.py,sha256=WDQQx-qiBs-7fqQXAfouGM-UYrOSA8-_MNa5RgeM7Ms,1943
23
+ oauthost/migrations/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
24
+ oauthost/templates/oauthost/authorize.html,sha256=R6sRE_u3k7quarKckaXrJX_zHAGP8j154xl1AaRNUek,846
25
+ oauthost/templates/oauthost/authorize_error.html,sha256=iLQ_x3cYlp-IKsVQIY_KoaPrhPNAPowl1rv7OQi0t4I,131
26
+ oauthost/templates/oauthost/authorize_proceed.html,sha256=FDKtck_e3OihHe6_G-8i-BNq0SjOFokhTMkX5d1NQSY,354
27
+ oauthost/templates/oauthost/base.html,sha256=1UBm6NL1AyDa2X9rlasG8A53B8KFZxPhwm4zOa0kuoc,1555
28
+ oauthost/templates/oauthost/forbidden.html,sha256=V_WD95aYDMgkkdGw6Yun_Ep0WkKJrN9x9jMt-AdM56M,209
29
+ oauthost/templates/oauthost/restricted.html,sha256=UTrjoH3vYHoSFhC_4KgGZpwFnxXrzcIbWDzGdasldZE,249
30
+ django_oauthost-1.1.2.dist-info/METADATA,sha256=kImJfoP_ePwq3To2Iamw_z11UWZWuoDM9QYwsB8OQ5k,2792
31
+ django_oauthost-1.1.2.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
32
+ django_oauthost-1.1.2.dist-info/licenses/LICENSE,sha256=98h0OcFpqPUCrF0aUKvlcmvAz4eqVux9GTTfHmXq0m0,1551
33
+ django_oauthost-1.1.2.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,27 @@
1
+ Copyright (c) 2011-2026, django-oauthost project
2
+ All rights reserved.
3
+
4
+ Redistribution and use in source and binary forms, with or without modification,
5
+ are permitted provided that the following conditions are met:
6
+
7
+ 1. Redistributions of source code must retain the above copyright notice,
8
+ this list of conditions and the following disclaimer.
9
+
10
+ 2. Redistributions in binary form must reproduce the above copyright
11
+ notice, this list of conditions and the following disclaimer in the
12
+ documentation and/or other materials provided with the distribution.
13
+
14
+ 3. Neither the name of the django-oauthost nor the names of its
15
+ contributors may be used to endorse or promote products derived from
16
+ this software without specific prior written permission.
17
+
18
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
19
+ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
20
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
21
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
22
+ ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
23
+ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
24
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
25
+ ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
27
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
oauthost/__init__.py ADDED
@@ -0,0 +1,4 @@
1
+ VERSION = '1.1.2'
2
+
3
+
4
+ default_app_config = 'oauthost.apps.OauthostConfig'
oauthost/admin.py ADDED
@@ -0,0 +1,55 @@
1
+ from django.contrib import admin
2
+
3
+ from .models import Client, RedirectionEndpoint, AuthorizationCode, Scope, Token
4
+
5
+
6
+ class AuthorizationCodeInlineAdmin(admin.TabularInline):
7
+ model = AuthorizationCode
8
+ extra = 1
9
+
10
+
11
+ class RedirectionEndpointAdmin(admin.TabularInline):
12
+ model = RedirectionEndpoint
13
+ extra = 1
14
+
15
+
16
+ class TokenInlineAdmin(admin.TabularInline):
17
+ model = Token
18
+ extra = 1
19
+
20
+
21
+ class ClientAdmin(admin.ModelAdmin):
22
+ list_display = ('title',)
23
+ list_display_links = ('title',)
24
+ search_fields = ('title',)
25
+ inlines = (RedirectionEndpointAdmin, AuthorizationCodeInlineAdmin, TokenInlineAdmin)
26
+
27
+
28
+ class ScopeAdmin(admin.ModelAdmin):
29
+ list_display = ('title', 'identifier', 'status')
30
+ list_display_links = ('title',)
31
+ search_fields = ('title', 'identifier')
32
+ list_filter = ('status',)
33
+
34
+
35
+ class TokenAdmin(admin.ModelAdmin):
36
+ list_display = ('date_issued', 'user', 'access_token', 'access_token_type', 'refresh_token')
37
+ search_fields = ('access_token', 'refresh_token')
38
+ list_filter = ('access_token_type', 'client')
39
+ ordering = ('-date_issued',)
40
+ date_hierarchy = 'date_issued'
41
+
42
+
43
+ class AuthorizationCodeAdmin(admin.ModelAdmin):
44
+ list_display = ('date_issued', 'code', 'client', 'user', 'uri')
45
+ list_display_links = ('code',)
46
+ search_fields = ('code', 'uri')
47
+ list_filter = ('client',)
48
+ ordering = ('-date_issued',)
49
+ date_hierarchy = 'date_issued'
50
+
51
+
52
+ admin.site.register(Client, ClientAdmin)
53
+ admin.site.register(Scope, ScopeAdmin)
54
+ admin.site.register(Token, TokenAdmin)
55
+ admin.site.register(AuthorizationCode, AuthorizationCodeAdmin)
oauthost/apps.py ADDED
@@ -0,0 +1,10 @@
1
+ from django.apps import AppConfig
2
+ from django.utils.translation import gettext_lazy as _
3
+
4
+
5
+ class OauthostConfig(AppConfig):
6
+ """Oauthost configuration."""
7
+
8
+ name = 'oauthost'
9
+ verbose_name = _('OAuthost')
10
+ default_auto_field = 'django.db.models.AutoField'
@@ -0,0 +1,116 @@
1
+ from datetime import datetime
2
+
3
+ from django.contrib.auth import login
4
+ from django.core.exceptions import ObjectDoesNotExist
5
+ from django.template import loader, RequestContext
6
+ from django.http import HttpResponse, HttpRequest
7
+ from django.utils.translation import gettext_lazy as _
8
+
9
+
10
+ class BearerAuthHandler:
11
+ """Handles Bearer token authentication calls.
12
+
13
+ SPEC: http://tools.ietf.org/html/rfc6750
14
+
15
+ """
16
+
17
+ _token: str = None
18
+ _request: HttpRequest = None
19
+ _response: HttpResponse = None
20
+ _error: str = None
21
+ _scope: str = None
22
+
23
+ def __init__(self, request: HttpRequest, scope):
24
+ self._request = request
25
+ self._scope = scope
26
+
27
+ self.fetch_token()
28
+ self.validate_token()
29
+ self.prepare_response()
30
+
31
+ def fetch_token(self):
32
+ token = None
33
+
34
+ request = self._request
35
+
36
+ # Authorization Request Header Field
37
+ authorization_method = request.META.get('HTTP_AUTHORIZATION')
38
+ if authorization_method is not None:
39
+ auth_method_type, auth_method_value = authorization_method.split(' ', 1)
40
+ if auth_method_type == 'Bearer':
41
+ token = auth_method_value
42
+ else:
43
+ # Form-Encoded Body Parameter or URI Query Parameter
44
+ token = request.POST.get('access_token', request.GET.get('access_token'))
45
+
46
+ if token is None:
47
+ self._error = 'invalid_request'
48
+ else:
49
+ self._token = token
50
+
51
+ def validate_token(self) -> bool:
52
+
53
+ if self._token is None:
54
+ return False
55
+
56
+ from oauthost.models import Token
57
+ try:
58
+ token = Token.objects.get(access_token=self._token)
59
+ except ObjectDoesNotExist:
60
+ self._error = 'invalid_token'
61
+ return False
62
+
63
+ # If token found is granted to all the different token type.
64
+ if token.access_token_type != 'bearer':
65
+ self._error = 'invalid_token'
66
+ return False
67
+
68
+ # Token has expired.
69
+ if token.expires_at is not None and token.expires_at <= datetime.now():
70
+ self._error = 'invalid_token'
71
+ return False
72
+
73
+ # If target scope is defined, let's verify that the token has access to it.
74
+ if self._scope is not None:
75
+ if not token.scopes.filter(identifier=self._scope).count():
76
+ self._error = 'insufficient_scope'
77
+ return False
78
+
79
+ # Token is valid and now we'll log it's owner in.
80
+
81
+ # Manual .backend attribute is set as an alternative to `authenticate()`.
82
+ # For now this hardcoded backend will do.
83
+ token.user.backend = 'django.contrib.auth.backends.ModelBackend'
84
+ login(self._request, token.user)
85
+
86
+ return True
87
+
88
+ def prepare_response(self):
89
+
90
+ if self._error is not None:
91
+ from .settings import TEMPLATE_RESTRICTED
92
+
93
+ errors = {
94
+ 'invalid_request': (400, 'Request is malformed. Check request parameters validity.'),
95
+ 'invalid_token': (401, 'Given access token is invalid'),
96
+ 'insufficient_scope': (403, 'Access token grants no access to required scope.')
97
+ }
98
+
99
+ current_error = errors[self._error]
100
+ additional_params = {
101
+ 'error': self._error, 'error_description': current_error[1]
102
+ }
103
+ additional_params = ','.join([f'{key}="{val}"' for key, val in additional_params.items()])
104
+
105
+ context = RequestContext(self._request)
106
+
107
+ self._response = HttpResponse(
108
+ content=loader.render_to_string(
109
+ TEMPLATE_RESTRICTED, {'oauthost_title': _('Access Restricted')}, context
110
+ ),
111
+ status=current_error[0]
112
+ )
113
+ self._response['WWW-Authenticate'] = f'Bearer {additional_params}'
114
+
115
+ def response(self) -> HttpResponse:
116
+ return self._response
oauthost/decorators.py ADDED
@@ -0,0 +1,32 @@
1
+ from functools import wraps
2
+
3
+ from django.utils.decorators import available_attrs
4
+
5
+ from .toolbox import auth_handler_response
6
+
7
+
8
+ def oauth_required(scope: str = None, scope_auto: bool = False):
9
+ """Views decorator checking user oauth token.
10
+
11
+ :param scope: scope identifier string to check token has access to the scope.
12
+
13
+ :param scope_auto: if *True* scope identifier will be built automatically
14
+ using the following format: '<application_name>:<decorated_view_name>'.
15
+ E.g.: for application named *polls* and having *detail* view scope
16
+ would be *polls:detail*.
17
+
18
+ """
19
+ def decorated_view(view_function):
20
+ @wraps(view_function, assigned=available_attrs(view_function))
21
+ def wrapper(request, *args, **kwargs):
22
+ target_scope = scope
23
+
24
+ if scope_auto:
25
+ target_scope = '%(app_name)s:%(view_name)s' % {
26
+ 'app_name': view_function.__module__.split('.')[0],
27
+ 'view_name': view_function.__name__}
28
+
29
+ return auth_handler_response(request, scope=target_scope) or view_function(request, *args, **kwargs)
30
+ return wrapper
31
+
32
+ return decorated_view