From 3d6f794bcd010d34d5a812ae88372b8c0920770c Mon Sep 17 00:00:00 2001 From: Mark Rogaski Date: Sun, 14 Aug 2016 11:54:32 -0400 Subject: [PATCH 01/22] Updated README formatting. --- README.rst | 47 +++++++++++++++++++++++++++-------------------- test_settings.py | 3 ++- 2 files changed, 29 insertions(+), 21 deletions(-) diff --git a/README.rst b/README.rst index c2000b2..86837a2 100644 --- a/README.rst +++ b/README.rst @@ -57,47 +57,54 @@ Required Settings ^^^^^^^^^^^^^^^^^ DISCORD_CLIENT_ID - The client identifier issued by the Discord authorization server. This - identifier is used in the authorization request of the OAuth 2.0 - Authorization Code Grant workflow. +~~~~~~~~~~~~~~~~~ +The client identifier issued by the Discord authorization server. This +identifier is used in the authorization request of the OAuth 2.0 +Authorization Code Grant workflow. DISCORD_CLIENT_SECRET - A shared secret issued by the Discord authorization server. This - identifier is used in the access token request of the OAuth 2.0 - Authorization Code Grant workflow. +~~~~~~~~~~~~~~~~~~~~~ +A shared secret issued by the Discord authorization server. This +identifier is used in the access token request of the OAuth 2.0 +Authorization Code Grant workflow. Optional Settings ^^^^^^^^^^^^^^^^^ DISCORD_AUTHZ_PATH - The path of the authorization request service endpoint, which will be - appended to the DISCORD_BASE_URI setting. +~~~~~~~~~~~~~~~~~~ +The path of the authorization request service endpoint, which will be +appended to the DISCORD_BASE_URI setting. - Default: /oauth2/authorize +Default: /oauth2/authorize DISCORD_BASE_URI - The base URI for the Discord API. +~~~~~~~~~~~~~~~~ +The base URI for the Discord API. - Default: https://discordapp.com/api +Default: https://discordapp.com/api DISCORD_INVITE_URI - The URI that the user will be redirected to after one or more successful - auto-invites. +~~~~~~~~~~~~~~~~~~ +The URI that the user will be redirected to after one or more successful +auto-invites. - Default: https://discordapp.com/channels/@me +Default: https://discordapp.com/channels/@me DISCORD_RETURN_URI - The URI that the user will be redirected to if no auto-invites are - attempted or successful. +~~~~~~~~~~~~~~~~~~ +The URI that the user will be redirected to if no auto-invites are +attempted or successful. - Default: / +Default: / DISCORD_TOKEN_PATH - The path of the access token request service endpoint, which will be - appended to the DISCORD_BASE_URI setting. +~~~~~~~~~~~~~~~~~~ +The path of the access token request service endpoint, which will be +appended to the DISCORD_BASE_URI setting. - Default: /oauth2/token +Default: /oauth2/token License diff --git a/test_settings.py b/test_settings.py index 96835b9..aab248e 100644 --- a/test_settings.py +++ b/test_settings.py @@ -40,4 +40,5 @@ ) SECRET_KEY = 'vn5v8g+q3q*ll)a3kh10wlj#(tc=738cklg9(z3***kw%qhnv-' -ROOT_URLCONF='discord_bind.urls' + +ROOT_URLCONF = 'discord_bind.urls' From 074944cc64e28de8c44df22407039af21c65218e Mon Sep 17 00:00:00 2001 From: Mark Rogaski Date: Tue, 16 Aug 2016 00:43:57 -0400 Subject: [PATCH 02/22] Added tests for index view. --- discord_bind/tests/test_views.py | 107 +++++++++++++++++++++++++++++++ 1 file changed, 107 insertions(+) create mode 100644 discord_bind/tests/test_views.py diff --git a/discord_bind/tests/test_views.py b/discord_bind/tests/test_views.py new file mode 100644 index 0000000..dab8b03 --- /dev/null +++ b/discord_bind/tests/test_views.py @@ -0,0 +1,107 @@ +""" + +The MIT License (MIT) + +Copyright (c) 2016, Mark Rogaski + +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. + +""" +from __future__ import unicode_literals + +try: + from unittest.mock import patch, MagicMock +except ImportError: + from mock import patch, MagicMock +try: + from urllib.parse import urlparse +except ImportError: + from urlparse import urlparse + +from django.test import TestCase, RequestFactory, override_settings +from django.contrib.sessions.middleware import SessionMiddleware +from django.contrib.auth.models import User, AnonymousUser +from django.core.urlresolvers import reverse +from django.conf import settings + +from discord_bind.views import index, callback +from discord_bind import app_settings + + +class AuthorizationRequestTest(TestCase): + """ Test the authorization request view """ + def setUp(self): + self.factory = RequestFactory() + self.user = User.objects.create_user(username="Hoots", + email="test@example.com", + password="test") + + @override_settings(DISCORD_CLIENT_ID='212763200357720576') + def test_get_index(self): + """ Test the index URL """ + def user_request(user): + request = self.factory.get(reverse('discord_bind_index')) + request.user = user + middleware = SessionMiddleware() + middleware.process_request(request) + request.session.save() + return request + + # Anonymous users should bounce to the login page + request = user_request(AnonymousUser()) + response = index(request) + self.assertEqual(response.status_code, 302) + self.assertTrue('login' in response['location']) + + # Loggied in users bounce to the auth request page + request = user_request(self.user) + response = index(request) + self.assertEqual(response.status_code, 302) + url = urlparse(response['location']) + self.assertEqual('https://discordapp.com/api/oauth2/authorize', + url.scheme + '://' + url.netloc + url.path) + self.assertIn('response_type=code', url.query) + self.assertIn('client_id=212763200357720576', url.query) + self.assertIn('redirect_uri=http%3A%2F%2Ftestserver%2Fcb', url.query) + self.assertIn('scope=email+guilds.join', url.query) + self.assertIn('state=', url.query) + + # Limited scope + with self.settings(DISCORD_EMAIL_SCOPE='212763200357720576'): + request = user_request(self.user) + response = index(request) + url = urlparse(response['location']) + self.assertIn('scope=identity+guilds.join', url.query) + + # URI settings + with self.settings(DISCORD_BASE_URI='https://www.example.com/api'): + request = user_request(self.user) + response = index(request) + url = urlparse(response['location']) + self.assertEqual('', url.query) + self.assertEqual('https://www.example.com/api/oauth2/authorize', + url.scheme + '://' + url.netloc + url.path) + + with self.settings(DISCORD_AUTHZ_URI='/foo/bar'): + request = user_request(self.user) + response = index(request) + url = urlparse(response['location']) + self.assertEqual('', url.query) + self.assertEqual('https://discordapp.com/api/foo/bar', + url.scheme + '://' + url.netloc + url.path) From dbd5fe3bbffba87bc2d56b967dea00521e9645a2 Mon Sep 17 00:00:00 2001 From: Mark Rogaski Date: Tue, 16 Aug 2016 01:04:20 -0400 Subject: [PATCH 03/22] Added to index view tests. --- discord_bind/tests/test_views.py | 38 +++++++++++++++++++++++++++++--- 1 file changed, 35 insertions(+), 3 deletions(-) diff --git a/discord_bind/tests/test_views.py b/discord_bind/tests/test_views.py index dab8b03..c418d4b 100644 --- a/discord_bind/tests/test_views.py +++ b/discord_bind/tests/test_views.py @@ -55,8 +55,8 @@ def setUp(self): @override_settings(DISCORD_CLIENT_ID='212763200357720576') def test_get_index(self): """ Test the index URL """ - def user_request(user): - request = self.factory.get(reverse('discord_bind_index')) + def user_request(user, query=''): + request = self.factory.get(reverse('discord_bind_index') + query) request.user = user middleware = SessionMiddleware() middleware.process_request(request) @@ -80,7 +80,8 @@ def user_request(user): self.assertIn('client_id=212763200357720576', url.query) self.assertIn('redirect_uri=http%3A%2F%2Ftestserver%2Fcb', url.query) self.assertIn('scope=email+guilds.join', url.query) - self.assertIn('state=', url.query) + self.assertIn('state=%s' % request.session['discord_bind_oauth_state'], + url.query) # Limited scope with self.settings(DISCORD_EMAIL_SCOPE='212763200357720576'): @@ -105,3 +106,34 @@ def user_request(user): self.assertEqual('', url.query) self.assertEqual('https://discordapp.com/api/foo/bar', url.scheme + '://' + url.netloc + url.path) + + # invite uri tests + request = user_request(self.user) + response = index(request) + self.assertEqual(request.session['discord_bind_invite_uri'], + 'https://discordapp.com/channels/@me') + + request = user_request(self.user, 'invite_uri=/foo') + response = index(request) + self.assertEqual(request.session['discord_bind_invite_uri'], '/foo') + + with self.settings(DISCORD_INVITE_URI='https://www.example.com/'): + request = user_request(self.user) + response = index(request) + self.assertEqual(request.session['discord_bind_invite_uri'], + 'https://www.example.com/') + + # return uri tests + request = user_request(self.user) + response = index(request) + self.assertEqual(request.session['discord_bind_return_uri'], '/') + + request = user_request(self.user, 'invite_uri=/foo') + response = index(request) + self.assertEqual(request.session['discord_bind_return_uri'], '/foo') + + with self.settings(DISCORD_INVITE_URI='https://www.example.com/'): + request = user_request(self.user) + response = index(request) + self.assertEqual(request.session['discord_bind_return_uri'], + 'https://www.example.com/') From 97eee40bf5f1463666411c36c83b543567ae00ad Mon Sep 17 00:00:00 2001 From: Mark Rogaski Date: Tue, 16 Aug 2016 01:38:18 -0400 Subject: [PATCH 04/22] Removed unnecessary imports. --- discord_bind/tests/test_views.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/discord_bind/tests/test_views.py b/discord_bind/tests/test_views.py index c418d4b..bd9531d 100644 --- a/discord_bind/tests/test_views.py +++ b/discord_bind/tests/test_views.py @@ -38,10 +38,8 @@ from django.contrib.sessions.middleware import SessionMiddleware from django.contrib.auth.models import User, AnonymousUser from django.core.urlresolvers import reverse -from django.conf import settings from discord_bind.views import index, callback -from discord_bind import app_settings class AuthorizationRequestTest(TestCase): From e123f35c750fcea9312aaafbed1ec0c4c591ac2c Mon Sep 17 00:00:00 2001 From: Mark Rogaski Date: Wed, 17 Aug 2016 01:27:45 -0400 Subject: [PATCH 05/22] Replaced app_settings with django-appconf. --- discord_bind/__init__.py | 3 ++ discord_bind/admin.py | 4 -- discord_bind/apps.py | 2 + discord_bind/{app_settings.py => conf.py} | 56 +++++++++++++---------- discord_bind/models.py | 4 +- discord_bind/views.py | 25 +++++----- requirements.txt | 1 + setup.py | 3 +- 8 files changed, 54 insertions(+), 44 deletions(-) rename discord_bind/{app_settings.py => conf.py} (56%) diff --git a/discord_bind/__init__.py b/discord_bind/__init__.py index 68d20d6..2b18b78 100644 --- a/discord_bind/__init__.py +++ b/discord_bind/__init__.py @@ -23,4 +23,7 @@ SOFTWARE. """ +# following PEP 386 +__version__ = '0.1.4' + default_app_config = 'discord_bind.apps.DiscordBindConfig' diff --git a/discord_bind/admin.py b/discord_bind/admin.py index 380e9c6..c3411bc 100644 --- a/discord_bind/admin.py +++ b/discord_bind/admin.py @@ -23,13 +23,9 @@ SOFTWARE. """ -import requests - from django.contrib import admin from .models import DiscordUser, DiscordInvite -from discord_bind.app_settings import BASE_URI - @admin.register(DiscordUser) class DiscordUserAdmin(admin.ModelAdmin): diff --git a/discord_bind/apps.py b/discord_bind/apps.py index 1a3d5e9..5e3f4a4 100644 --- a/discord_bind/apps.py +++ b/discord_bind/apps.py @@ -27,4 +27,6 @@ class DiscordBindConfig(AppConfig): + """ Application config """ + from discord_bind.conf import DiscordBindConf name = 'discord_bind' diff --git a/discord_bind/app_settings.py b/discord_bind/conf.py similarity index 56% rename from discord_bind/app_settings.py rename to discord_bind/conf.py index 9fb4e43..cc5ecc2 100644 --- a/discord_bind/app_settings.py +++ b/discord_bind/conf.py @@ -26,26 +26,36 @@ from __future__ import unicode_literals from django.conf import settings - - -# API service endpoints -BASE_URI = getattr(settings, 'DISCORD_BASE_URI', - 'https://discordapp.com/api') -AUTHZ_URI = getattr(settings, 'DISCORD_AUTHZ_URI', - BASE_URI + '/oauth2/authorize') -TOKEN_URI = getattr(settings, 'DISCORD_TOKEN_URI', - BASE_URI + '/oauth2/token') - -# OAuth2 application credentials -CLIENT_ID = getattr(settings, 'DISCORD_CLIENT_ID', '') -CLIENT_SECRET = getattr(settings, 'DISCORD_CLIENT_SECRET', '') - -# OAuth2 scope -AUTHZ_SCOPE = ( - ['email', 'guilds.join'] if getattr(settings, 'DISCORD_EMAIL_SCOPE', True) - else ['identity', 'guilds.join']) - -# Return URI -INVITE_URI = getattr(settings, 'DISCORD_INVITE_URI', - 'https://discordapp.com/channels/@me') -RETURN_URI = getattr(settings, 'DISCORD_RETURN_URI', '/') +from appconf import AppConf + + +class DiscordBindConf(AppConf): + """ Application settings """ + # API service endpoints + BASE_URI = 'https://discordapp.com/api' + AUTHZ_PATH = '/oauth2/authorize' + TOKEN_PATH = '/oauth2/token' + + # OAuth2 application credentials + CLIENT_ID = None + CLIENT_SECRET = None + + # OAuth2 scope + EMAIL_SCOPE = True + AUTHZ_SCOPE = ['email', 'guilds.join'] + + # Return URI + INVITE_URI = 'https://discordapp.com/channels/@me' + RETURN_URI = '/' + + class Meta: + proxy = True + prefix = 'discord' + required = ['CLIENT_ID', 'CLIENT_SECRET'] + + def configure(self): + if self.configured_data['EMAIL_SCOPE']: + self.configured_data['AUTHZ_SCOPE'] = ['email', 'guilds.join'] + else: + self.configured_data['AUTHZ_SCOPE'] = ['identity', 'guilds.join'] + return self.configured_data diff --git a/discord_bind/models.py b/discord_bind/models.py index 30eae90..364f56c 100644 --- a/discord_bind/models.py +++ b/discord_bind/models.py @@ -29,7 +29,7 @@ from django.db import models from django.contrib.auth.models import User, Group from django.utils.encoding import python_2_unicode_compatible -from discord_bind.app_settings import BASE_URI +from discord_bind.conf import settings import logging logger = logging.getLogger(__name__) @@ -81,7 +81,7 @@ def __str__(self): def update_context(self): result = False - r = requests.get(BASE_URI + '/invites/' + self.code) + r = requests.get(settings.DISCORD_BASE_URI + '/invites/' + self.code) if r.status_code == requests.codes.ok: logger.info('fetched data for Discord invite %s' % self.code) invite = r.json() diff --git a/discord_bind/views.py b/discord_bind/views.py index b4e2b29..f85dfe7 100644 --- a/discord_bind/views.py +++ b/discord_bind/views.py @@ -25,10 +25,8 @@ """ from __future__ import unicode_literals - from datetime import datetime -from django.conf import settings from django.http import HttpResponseRedirect try: from django.urls import reverse @@ -43,9 +41,7 @@ from requests_oauthlib import OAuth2Session from discord_bind.models import DiscordUser, DiscordInvite -from discord_bind.app_settings import BASE_URI, AUTHZ_URI, TOKEN_URI -from discord_bind.app_settings import RETURN_URI, INVITE_URI -from discord_bind.app_settings import CLIENT_ID, CLIENT_SECRET, AUTHZ_SCOPE +from discord_bind.conf import settings import logging logger = logging.getLogger(__name__) @@ -54,9 +50,9 @@ def oauth_session(request, state=None, token=None): """ Constructs the OAuth2 session object. """ redirect_uri = request.build_absolute_uri(reverse('discord_bind_callback')) - return OAuth2Session(CLIENT_ID, + return OAuth2Session(settings.DISCORD_CLIENT_ID, redirect_uri=redirect_uri, - scope=AUTHZ_SCOPE, + scope=settings.DISCORD_AUTHZ_SCOPE, token=token, state=state) @@ -67,16 +63,17 @@ def index(request): if 'invite_uri' in request.GET: request.session['discord_bind_invite_uri'] = request.GET['invite_uri'] else: - request.session['discord_bind_invite_uri'] = INVITE_URI + request.session['discord_bind_invite_uri'] = settings.DISCORD_INVITE_URI if 'return_uri' in request.GET: request.session['discord_bind_return_uri'] = request.GET['return_uri'] else: - request.session['discord_bind_return_uri'] = RETURN_URI + request.session['discord_bind_return_uri'] = settings.DISCORD_RETURN_URI # Compute the authorization URI oauth = oauth_session(request) - url, state = oauth.authorization_url(AUTHZ_URI) + url, state = oauth.authorization_url(settings.DISCORD_BASE_URI + + settings.DISCORD_AUTHZ_PATH) request.session['discord_bind_oauth_state'] = state return HttpResponseRedirect(url) @@ -120,12 +117,12 @@ def bind_user(request, data): response = request.build_absolute_uri() state = request.session['discord_bind_oauth_state'] oauth = oauth_session(request, state=state) - token = oauth.fetch_token(TOKEN_URI, - client_secret=CLIENT_SECRET, + token = oauth.fetch_token(settings.DISCORD_BASE_URI + settings.DISCORD_TOKEN_PATH, + client_secret=settings.DISCORD_CLIENT_SECRET, authorization_response=response) # Get Discord user data - user = oauth.get(BASE_URI + '/users/@me').json() + user = oauth.get(settings.DISCORD_BASE_URI + '/users/@me').json() data = decompose_data(user, token) bind_user(request, data) @@ -135,7 +132,7 @@ def bind_user(request, data): Q(groups__in=groups) | Q(groups=None)) count = 0 for invite in invites: - r = oauth.post(BASE_URI + '/invites/' + invite.code) + r = oauth.post(settings.DISCORD_BASE_URI + '/invites/' + invite.code) if r.status_code == requests.codes.ok: count += 1 logger.info(('accepted Discord ' diff --git a/requirements.txt b/requirements.txt index 7be4927..5ae76e9 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,4 +1,5 @@ Django>=1.9 +django-appconf>=1.0.2 django-setuptest>=0.2.1 requests>=2.11.0 requests-oauthlib>=0.6.2 \ No newline at end of file diff --git a/setup.py b/setup.py index 98096b8..0ce60e8 100644 --- a/setup.py +++ b/setup.py @@ -66,7 +66,8 @@ ], install_requires=[ "Django >= 1.9", - "requests-oauthlib == 0.6.2", + "requests-oauthlib >= 0.6", + "django-appconf >= 1.0", ], tests_require=[ "django-setuptest >= 0.2.1", From b6b89e49bf2f969c8002b55c47e527b5cae6eb2d Mon Sep 17 00:00:00 2001 From: Mark Rogaski Date: Wed, 17 Aug 2016 01:39:46 -0400 Subject: [PATCH 06/22] Fixed conf loading order. --- discord_bind/apps.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/discord_bind/apps.py b/discord_bind/apps.py index 5e3f4a4..9409c42 100644 --- a/discord_bind/apps.py +++ b/discord_bind/apps.py @@ -24,9 +24,13 @@ """ from django.apps import AppConfig +from django.utils.translation import ugettext_lazy as _ class DiscordBindConfig(AppConfig): """ Application config """ - from discord_bind.conf import DiscordBindConf name = 'discord_bind' + verbose_name = _('Discord Binding') + + def ready(self): + from . import conf From 35372754eeee7aeeb5b9c512dd0c09c139a4de36 Mon Sep 17 00:00:00 2001 From: Mark Rogaski Date: Wed, 17 Aug 2016 02:16:02 -0400 Subject: [PATCH 07/22] Fixed most auth request tests. --- discord_bind/tests/test_views.py | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/discord_bind/tests/test_views.py b/discord_bind/tests/test_views.py index bd9531d..a16f6eb 100644 --- a/discord_bind/tests/test_views.py +++ b/discord_bind/tests/test_views.py @@ -40,6 +40,7 @@ from django.core.urlresolvers import reverse from discord_bind.views import index, callback +from discord_bind.conf import settings class AuthorizationRequestTest(TestCase): @@ -54,7 +55,10 @@ def setUp(self): def test_get_index(self): """ Test the index URL """ def user_request(user, query=''): - request = self.factory.get(reverse('discord_bind_index') + query) + url = reverse('discord_bind_index') + if query != '': + url = url + '?' + query + request = self.factory.get(url) request.user = user middleware = SessionMiddleware() middleware.process_request(request) @@ -82,7 +86,7 @@ def user_request(user, query=''): url.query) # Limited scope - with self.settings(DISCORD_EMAIL_SCOPE='212763200357720576'): + with self.settings(DISCORD_EMAIL_SCOPE=False): request = user_request(self.user) response = index(request) url = urlparse(response['location']) @@ -93,15 +97,13 @@ def user_request(user, query=''): request = user_request(self.user) response = index(request) url = urlparse(response['location']) - self.assertEqual('', url.query) self.assertEqual('https://www.example.com/api/oauth2/authorize', url.scheme + '://' + url.netloc + url.path) - with self.settings(DISCORD_AUTHZ_URI='/foo/bar'): + with self.settings(DISCORD_AUTHZ_PATH='/foo/bar'): request = user_request(self.user) response = index(request) url = urlparse(response['location']) - self.assertEqual('', url.query) self.assertEqual('https://discordapp.com/api/foo/bar', url.scheme + '://' + url.netloc + url.path) @@ -126,11 +128,11 @@ def user_request(user, query=''): response = index(request) self.assertEqual(request.session['discord_bind_return_uri'], '/') - request = user_request(self.user, 'invite_uri=/foo') + request = user_request(self.user, 'return_uri=/foo') response = index(request) self.assertEqual(request.session['discord_bind_return_uri'], '/foo') - with self.settings(DISCORD_INVITE_URI='https://www.example.com/'): + with self.settings(DISCORD_RETURN_URI='https://www.example.com/'): request = user_request(self.user) response = index(request) self.assertEqual(request.session['discord_bind_return_uri'], From da7cb2900a439fb5491fd6c81cbd4af1bd40ae7c Mon Sep 17 00:00:00 2001 From: Mark Rogaski Date: Wed, 17 Aug 2016 09:20:56 -0400 Subject: [PATCH 08/22] Removed AUTHZ_SCOPE setting. --- discord_bind/conf.py | 8 -------- discord_bind/views.py | 13 +++++++++---- 2 files changed, 9 insertions(+), 12 deletions(-) diff --git a/discord_bind/conf.py b/discord_bind/conf.py index cc5ecc2..aee5835 100644 --- a/discord_bind/conf.py +++ b/discord_bind/conf.py @@ -42,7 +42,6 @@ class DiscordBindConf(AppConf): # OAuth2 scope EMAIL_SCOPE = True - AUTHZ_SCOPE = ['email', 'guilds.join'] # Return URI INVITE_URI = 'https://discordapp.com/channels/@me' @@ -52,10 +51,3 @@ class Meta: proxy = True prefix = 'discord' required = ['CLIENT_ID', 'CLIENT_SECRET'] - - def configure(self): - if self.configured_data['EMAIL_SCOPE']: - self.configured_data['AUTHZ_SCOPE'] = ['email', 'guilds.join'] - else: - self.configured_data['AUTHZ_SCOPE'] = ['identity', 'guilds.join'] - return self.configured_data diff --git a/discord_bind/views.py b/discord_bind/views.py index f85dfe7..a780534 100644 --- a/discord_bind/views.py +++ b/discord_bind/views.py @@ -50,9 +50,11 @@ def oauth_session(request, state=None, token=None): """ Constructs the OAuth2 session object. """ redirect_uri = request.build_absolute_uri(reverse('discord_bind_callback')) + scope = (['email', 'guilds.join'] if settings.DISCORD_EMAIL_SCOPE + else ['identity', 'guilds.join']) return OAuth2Session(settings.DISCORD_CLIENT_ID, redirect_uri=redirect_uri, - scope=settings.DISCORD_AUTHZ_SCOPE, + scope=scope, token=token, state=state) @@ -63,12 +65,14 @@ def index(request): if 'invite_uri' in request.GET: request.session['discord_bind_invite_uri'] = request.GET['invite_uri'] else: - request.session['discord_bind_invite_uri'] = settings.DISCORD_INVITE_URI + request.session['discord_bind_invite_uri'] = ( + settings.DISCORD_INVITE_URI) if 'return_uri' in request.GET: request.session['discord_bind_return_uri'] = request.GET['return_uri'] else: - request.session['discord_bind_return_uri'] = settings.DISCORD_RETURN_URI + request.session['discord_bind_return_uri'] = ( + settings.DISCORD_RETURN_URI) # Compute the authorization URI oauth = oauth_session(request) @@ -117,7 +121,8 @@ def bind_user(request, data): response = request.build_absolute_uri() state = request.session['discord_bind_oauth_state'] oauth = oauth_session(request, state=state) - token = oauth.fetch_token(settings.DISCORD_BASE_URI + settings.DISCORD_TOKEN_PATH, + token = oauth.fetch_token(settings.DISCORD_BASE_URI + + settings.DISCORD_TOKEN_PATH, client_secret=settings.DISCORD_CLIENT_SECRET, authorization_response=response) From 0278c1b09c04632d476782e9b052a0ea1b73f580 Mon Sep 17 00:00:00 2001 From: Mark Rogaski Date: Thu, 18 Aug 2016 01:03:31 -0400 Subject: [PATCH 09/22] Added user bind test w/out invites. --- discord_bind/tests/test_models.py | 4 +- discord_bind/tests/test_views.py | 85 +++++++++++++++++++++++++++++-- 2 files changed, 82 insertions(+), 7 deletions(-) diff --git a/discord_bind/tests/test_models.py b/discord_bind/tests/test_models.py index 26a2c48..6c55615 100644 --- a/discord_bind/tests/test_models.py +++ b/discord_bind/tests/test_models.py @@ -38,7 +38,7 @@ class TestDiscordUser(TestCase): - + """ Test the Discord user model """ def setUp(self): self.user = User.objects.create(username='henry') @@ -54,7 +54,7 @@ def test_discord_user(self): class TestDiscordInvite(TestCase): - + """ Test the Discord invite model """ def setUp(self): self.red = Group.objects.create(name='Red Team') self.blue = Group.objects.create(name='Blue Team') diff --git a/discord_bind/tests/test_views.py b/discord_bind/tests/test_views.py index a16f6eb..0a1c697 100644 --- a/discord_bind/tests/test_views.py +++ b/discord_bind/tests/test_views.py @@ -26,13 +26,14 @@ from __future__ import unicode_literals try: - from unittest.mock import patch, MagicMock + from unittest.mock import patch, mock, MagicMock except ImportError: - from mock import patch, MagicMock + from mock import patch, mock, MagicMock try: from urllib.parse import urlparse except ImportError: from urlparse import urlparse +import os from django.test import TestCase, RequestFactory, override_settings from django.contrib.sessions.middleware import SessionMiddleware @@ -43,17 +44,21 @@ from discord_bind.conf import settings -class AuthorizationRequestTest(TestCase): +os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1' + +class TestAuthorizationRequest(TestCase): """ Test the authorization request view """ def setUp(self): self.factory = RequestFactory() self.user = User.objects.create_user(username="Hoots", - email="test@example.com", + email="hoots@example.com", password="test") + def tearDown(self): + self.user.delete() + @override_settings(DISCORD_CLIENT_ID='212763200357720576') def test_get_index(self): - """ Test the index URL """ def user_request(user, query=''): url = reverse('discord_bind_index') if query != '': @@ -137,3 +142,73 @@ def user_request(user, query=''): response = index(request) self.assertEqual(request.session['discord_bind_return_uri'], 'https://www.example.com/') + + +class TestAccessTokenRequest(TestCase): + """ Test the authorization request view """ + def setUp(self): + self.factory = RequestFactory() + self.user = User.objects.create_user(username="Ralff", + email="ralff@example.com", + password="test") + + def tearDown(self): + self.user.delete() + + @override_settings(DISCORD_CLIENT_ID='212763200357720576') + def test_get_callback(self): + + @mock.patch('discord_bind.views.OAuth2Session.get') + @mock.patch('discord_bind.views.OAuth2Session.fetch_token') + def get_callback(user, query, mock_fetch, mock_get): + # build request + url = reverse('discord_bind_callback') + if query != '': + url = url + '?' + query + request = self.factory.get(url) + + # add user and session + request.user = user + middleware = SessionMiddleware() + middleware.process_request(request) + request.session['discord_bind_oauth_state'] = 'xyz' + request.session['discord_bind_invite_uri'] = ( + settings.DISCORD_INVITE_URI) + request.session['discord_bind_return_uri'] = ( + settings.DISCORD_RETURN_URI) + request.session.save() + + # build mock harness + mock_fetch.return_value = { + "access_token": "tvYhMddlVlxNGPtsAN34w9P6pivuLG", + "token_type": "Bearer", + "expires_in": 604800, + "refresh_token": "pUbZsF6BBZ8cD1CZqwxW25hCPUkQF5", + "scope": "email" + } + user_data = { + "avatar": "000d1294c515f3331cf32b31bc132f92", + "discriminator": "4021", + "email": "stigg@example.com", + "id": "132196734423007232", + "mfa_enabled": True, + "username": "stigg", + "verified": True + } + mock_response = mock.Mock() + mock_response.json.return_value = user_data + mock_get.return_value = mock_response + + # fire + return callback(request) + + # Anonymous users should bounce to the login page + response = get_callback(AnonymousUser(), '') + self.assertEqual(response.status_code, 302) + self.assertTrue('login' in response['location']) + + # Discord user binding + response = get_callback(self.user, + 'code=SplxlOBeZQQYbYS6WxSbIA&state=xyz') + self.assertEqual(response.status_code, 302) + self.assertEqual(response['location'], settings.DISCORD_RETURN_URI) From 2e6a50df770e5afdc9ec868c43492db9fc252357 Mon Sep 17 00:00:00 2001 From: Mark Rogaski Date: Thu, 18 Aug 2016 01:04:29 -0400 Subject: [PATCH 10/22] Added RTD stubs. --- docs/Makefile | 225 ++++++++++++++++++++++++++++++++ docs/conf.py | 341 +++++++++++++++++++++++++++++++++++++++++++++++++ docs/index.rst | 21 +++ docs/make.bat | 281 ++++++++++++++++++++++++++++++++++++++++ 4 files changed, 868 insertions(+) create mode 100644 docs/Makefile create mode 100644 docs/conf.py create mode 100644 docs/index.rst create mode 100644 docs/make.bat diff --git a/docs/Makefile b/docs/Makefile new file mode 100644 index 0000000..d6b0300 --- /dev/null +++ b/docs/Makefile @@ -0,0 +1,225 @@ +# Makefile for Sphinx documentation +# + +# You can set these variables from the command line. +SPHINXOPTS = +SPHINXBUILD = sphinx-build +PAPER = +BUILDDIR = _build + +# 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 +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 " epub3 to make an epub3" + @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)" + @echo " dummy to check syntax errors of document sources" + +.PHONY: clean +clean: + rm -rf $(BUILDDIR)/* + +.PHONY: html +html: + $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html + @echo + @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." + +.PHONY: dirhtml +dirhtml: + $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml + @echo + @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." + +.PHONY: singlehtml +singlehtml: + $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml + @echo + @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." + +.PHONY: pickle +pickle: + $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle + @echo + @echo "Build finished; now you can process the pickle files." + +.PHONY: json +json: + $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json + @echo + @echo "Build finished; now you can process the JSON files." + +.PHONY: htmlhelp +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." + +.PHONY: qthelp +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/django-discord-bind.qhcp" + @echo "To view the help file:" + @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/django-discord-bind.qhc" + +.PHONY: applehelp +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." + +.PHONY: devhelp +devhelp: + $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp + @echo + @echo "Build finished." + @echo "To view the help file:" + @echo "# mkdir -p $$HOME/.local/share/devhelp/django-discord-bind" + @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/django-discord-bind" + @echo "# devhelp" + +.PHONY: epub +epub: + $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub + @echo + @echo "Build finished. The epub file is in $(BUILDDIR)/epub." + +.PHONY: epub3 +epub3: + $(SPHINXBUILD) -b epub3 $(ALLSPHINXOPTS) $(BUILDDIR)/epub3 + @echo + @echo "Build finished. The epub3 file is in $(BUILDDIR)/epub3." + +.PHONY: latex +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)." + +.PHONY: latexpdf +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." + +.PHONY: latexpdfja +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." + +.PHONY: text +text: + $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text + @echo + @echo "Build finished. The text files are in $(BUILDDIR)/text." + +.PHONY: man +man: + $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man + @echo + @echo "Build finished. The manual pages are in $(BUILDDIR)/man." + +.PHONY: texinfo +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)." + +.PHONY: info +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." + +.PHONY: gettext +gettext: + $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale + @echo + @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." + +.PHONY: changes +changes: + $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes + @echo + @echo "The overview file is in $(BUILDDIR)/changes." + +.PHONY: linkcheck +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." + +.PHONY: doctest +doctest: + $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest + @echo "Testing of doctests in the sources finished, look at the " \ + "results in $(BUILDDIR)/doctest/output.txt." + +.PHONY: coverage +coverage: + $(SPHINXBUILD) -b coverage $(ALLSPHINXOPTS) $(BUILDDIR)/coverage + @echo "Testing of coverage in the sources finished, look at the " \ + "results in $(BUILDDIR)/coverage/python.txt." + +.PHONY: xml +xml: + $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml + @echo + @echo "Build finished. The XML files are in $(BUILDDIR)/xml." + +.PHONY: pseudoxml +pseudoxml: + $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml + @echo + @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." + +.PHONY: dummy +dummy: + $(SPHINXBUILD) -b dummy $(ALLSPHINXOPTS) $(BUILDDIR)/dummy + @echo + @echo "Build finished. Dummy builder generates no files." diff --git a/docs/conf.py b/docs/conf.py new file mode 100644 index 0000000..c5647b0 --- /dev/null +++ b/docs/conf.py @@ -0,0 +1,341 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +# +# django-discord-bind documentation build configuration file, created by +# sphinx-quickstart on Wed Aug 17 18:11:27 2016. +# +# This file is execfile()d with the current directory set to its +# containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +# +# import os +# import sys +# sys.path.insert(0, os.path.abspath('.')) + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +# +# needs_sphinx = '1.0' + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [ + 'sphinx.ext.githubpages', +] + +# 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 encoding of source files. +# +# source_encoding = 'utf-8-sig' + +# The master toctree document. +master_doc = 'index' + +# General information about the project. +project = 'django-discord-bind' +copyright = '2016, Mark Rogaski' +author = 'Mark Rogaski' + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The short X.Y version. +version = '0.2' +# The full version, including alpha/beta/rc tags. +release = '0.2.0' + +# 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 + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +# +# today = '' +# +# Else, today_fmt is used as the format for a strftime call. +# +# today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +# This patterns also effect to html_static_path and html_extra_path +exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] + +# The reST default role (used for this markup: `text`) to use for all +# documents. +# +# default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +# +# add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +# +# add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +# +# show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = 'sphinx' + +# A list of ignored prefixes for module index sorting. +# modindex_common_prefix = [] + +# If true, keep warnings as "system message" paragraphs in the built documents. +# keep_warnings = False + +# 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 = 'alabaster' + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +# +# html_theme_options = {} + +# Add any paths that contain custom themes here, relative to this directory. +# html_theme_path = [] + +# The name for this set of Sphinx documents. +# " v documentation" by default. +# +# html_title = 'django-discord-bind v0.2.0' + +# A shorter title for the navigation bar. Default is the same as html_title. +# +# html_short_title = None + +# The name of an image file (relative to this directory) to place at the top +# of the sidebar. +# +# html_logo = None + +# The name of an image file (relative to this directory) to use as a favicon of +# the docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 +# pixels large. +# +# html_favicon = None + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ['_static'] + +# Add any extra paths that contain custom files (such as robots.txt or +# .htaccess) here, relative to this directory. These files are copied +# directly to the root of the documentation. +# +# html_extra_path = [] + +# If not None, a 'Last updated on:' timestamp is inserted at every page +# bottom, using the given strftime format. +# The empty string is equivalent to '%b %d, %Y'. +# +# html_last_updated_fmt = None + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +# +# html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +# +# html_sidebars = {} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +# +# html_additional_pages = {} + +# If false, no module index is generated. +# +# html_domain_indices = True + +# If false, no index is generated. +# +# html_use_index = True + +# If true, the index is split into individual pages for each letter. +# +# html_split_index = False + +# If true, links to the reST sources are added to the pages. +# +# html_show_sourcelink = True + +# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. +# +# html_show_sphinx = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. +# +# html_show_copyright = True + +# If true, an OpenSearch description file will be output, and all pages will +# contain a tag referring to it. The value of this option must be the +# base URL from which the finished HTML is served. +# +# html_use_opensearch = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +# html_file_suffix = None + +# Language to be used for generating the HTML full-text search index. +# Sphinx supports the following languages: +# 'da', 'de', 'en', 'es', 'fi', 'fr', 'h', 'it', 'ja' +# 'nl', 'no', 'pt', 'ro', 'r', 'sv', 'tr', 'zh' +# +# html_search_language = 'en' + +# A dictionary with options for the search language support, empty by default. +# 'ja' uses this config value. +# 'zh' user can custom change `jieba` dictionary path. +# +# html_search_options = {'type': 'default'} + +# The name of a javascript file (relative to the configuration directory) that +# implements a search results scorer. If empty, the default will be used. +# +# html_search_scorer = 'scorer.js' + +# Output file base name for HTML help builder. +htmlhelp_basename = 'django-discord-binddoc' + +# -- Options for LaTeX output --------------------------------------------- + +latex_elements = { + # The paper size ('letterpaper' or 'a4paper'). + # + # 'papersize': 'letterpaper', + + # The font size ('10pt', '11pt' or '12pt'). + # + # 'pointsize': '10pt', + + # Additional stuff for the LaTeX preamble. + # + # 'preamble': '', + + # Latex figure (float) alignment + # + # '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, 'django-discord-bind.tex', 'django-discord-bind Documentation', + 'Mark Rogaski', 'manual'), +] + +# The name of an image file (relative to this directory) to place at the top of +# the title page. +# +# latex_logo = None + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +# +# latex_use_parts = False + +# If true, show page references after internal links. +# +# latex_show_pagerefs = False + +# If true, show URL addresses after external links. +# +# latex_show_urls = False + +# Documents to append as an appendix to all manuals. +# +# latex_appendices = [] + +# It false, will not define \strong, \code, itleref, \crossref ... but only +# \sphinxstrong, ..., \sphinxtitleref, ... To help avoid clash with user added +# packages. +# +# latex_keep_old_macro_names = True + +# If false, no module index is generated. +# +# latex_domain_indices = True + + +# -- Options for manual page output --------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + (master_doc, 'django-discord-bind', 'django-discord-bind Documentation', + [author], 1) +] + +# If true, show URL addresses after external links. +# +# man_show_urls = False + + +# -- Options for Texinfo output ------------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + (master_doc, 'django-discord-bind', 'django-discord-bind Documentation', + author, 'django-discord-bind', 'One line description of project.', + 'Miscellaneous'), +] + +# Documents to append as an appendix to all manuals. +# +# texinfo_appendices = [] + +# If false, no module index is generated. +# +# texinfo_domain_indices = True + +# How to display URL addresses: 'footnote', 'no', or 'inline'. +# +# texinfo_show_urls = 'footnote' + +# If true, do not generate a @detailmenu in the "Top" node's menu. +# +# texinfo_no_detailmenu = False diff --git a/docs/index.rst b/docs/index.rst new file mode 100644 index 0000000..d720d9e --- /dev/null +++ b/docs/index.rst @@ -0,0 +1,21 @@ +.. include:: ../README.rst + + +Contents: +========= + +.. toctree:: + :maxdepth: 1 + + configuration + administration + changelog + + +Indices and tables +================== + +* :ref:`genindex` +* :ref:`modindex` +* :ref:`search` + diff --git a/docs/make.bat b/docs/make.bat new file mode 100644 index 0000000..9d68853 --- /dev/null +++ b/docs/make.bat @@ -0,0 +1,281 @@ +@ECHO OFF + +REM Command file for Sphinx documentation + +if "%SPHINXBUILD%" == "" ( + set SPHINXBUILD=sphinx-build +) +set BUILDDIR=_build +set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . +set I18NSPHINXOPTS=%SPHINXOPTS% . +if NOT "%PAPER%" == "" ( + set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% + set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% +) + +if "%1" == "" goto help + +if "%1" == "help" ( + :help + echo.Please use `make ^` where ^ is one of + echo. html to make standalone HTML files + echo. dirhtml to make HTML files named index.html in directories + echo. singlehtml to make a single large HTML file + echo. pickle to make pickle files + echo. json to make JSON files + echo. htmlhelp to make HTML files and a HTML help project + echo. qthelp to make HTML files and a qthelp project + echo. devhelp to make HTML files and a Devhelp project + echo. epub to make an epub + echo. epub3 to make an epub3 + echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter + echo. text to make text files + echo. man to make manual pages + echo. texinfo to make Texinfo files + echo. gettext to make PO message catalogs + echo. changes to make an overview over all changed/added/deprecated items + echo. xml to make Docutils-native XML files + echo. pseudoxml to make pseudoxml-XML files for display purposes + echo. linkcheck to check all external links for integrity + echo. doctest to run all doctests embedded in the documentation if enabled + echo. coverage to run coverage check of the documentation if enabled + echo. dummy to check syntax errors of document sources + goto end +) + +if "%1" == "clean" ( + for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i + del /q /s %BUILDDIR%\* + goto end +) + + +REM Check if sphinx-build is available and fallback to Python version if any +%SPHINXBUILD% 1>NUL 2>NUL +if errorlevel 9009 goto sphinx_python +goto sphinx_ok + +:sphinx_python + +set SPHINXBUILD=python -m sphinx.__init__ +%SPHINXBUILD% 2> nul +if errorlevel 9009 ( + echo. + echo.The 'sphinx-build' command was not found. Make sure you have Sphinx + echo.installed, then set the SPHINXBUILD environment variable to point + echo.to the full path of the 'sphinx-build' executable. Alternatively you + echo.may add the Sphinx directory to PATH. + echo. + echo.If you don't have Sphinx installed, grab it from + echo.http://sphinx-doc.org/ + exit /b 1 +) + +:sphinx_ok + + +if "%1" == "html" ( + %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The HTML pages are in %BUILDDIR%/html. + goto end +) + +if "%1" == "dirhtml" ( + %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. + goto end +) + +if "%1" == "singlehtml" ( + %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. + goto end +) + +if "%1" == "pickle" ( + %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; now you can process the pickle files. + goto end +) + +if "%1" == "json" ( + %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; now you can process the JSON files. + goto end +) + +if "%1" == "htmlhelp" ( + %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; now you can run HTML Help Workshop with the ^ +.hhp project file in %BUILDDIR%/htmlhelp. + goto end +) + +if "%1" == "qthelp" ( + %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; now you can run "qcollectiongenerator" with the ^ +.qhcp project file in %BUILDDIR%/qthelp, like this: + echo.^> qcollectiongenerator %BUILDDIR%\qthelp\django-discord-bind.qhcp + echo.To view the help file: + echo.^> assistant -collectionFile %BUILDDIR%\qthelp\django-discord-bind.ghc + goto end +) + +if "%1" == "devhelp" ( + %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. + goto end +) + +if "%1" == "epub" ( + %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The epub file is in %BUILDDIR%/epub. + goto end +) + +if "%1" == "epub3" ( + %SPHINXBUILD% -b epub3 %ALLSPHINXOPTS% %BUILDDIR%/epub3 + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The epub3 file is in %BUILDDIR%/epub3. + goto end +) + +if "%1" == "latex" ( + %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. + goto end +) + +if "%1" == "latexpdf" ( + %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex + cd %BUILDDIR%/latex + make all-pdf + cd %~dp0 + echo. + echo.Build finished; the PDF files are in %BUILDDIR%/latex. + goto end +) + +if "%1" == "latexpdfja" ( + %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex + cd %BUILDDIR%/latex + make all-pdf-ja + cd %~dp0 + echo. + echo.Build finished; the PDF files are in %BUILDDIR%/latex. + goto end +) + +if "%1" == "text" ( + %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The text files are in %BUILDDIR%/text. + goto end +) + +if "%1" == "man" ( + %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The manual pages are in %BUILDDIR%/man. + goto end +) + +if "%1" == "texinfo" ( + %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. + goto end +) + +if "%1" == "gettext" ( + %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The message catalogs are in %BUILDDIR%/locale. + goto end +) + +if "%1" == "changes" ( + %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes + if errorlevel 1 exit /b 1 + echo. + echo.The overview file is in %BUILDDIR%/changes. + goto end +) + +if "%1" == "linkcheck" ( + %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck + if errorlevel 1 exit /b 1 + echo. + echo.Link check complete; look for any errors in the above output ^ +or in %BUILDDIR%/linkcheck/output.txt. + goto end +) + +if "%1" == "doctest" ( + %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest + if errorlevel 1 exit /b 1 + echo. + echo.Testing of doctests in the sources finished, look at the ^ +results in %BUILDDIR%/doctest/output.txt. + goto end +) + +if "%1" == "coverage" ( + %SPHINXBUILD% -b coverage %ALLSPHINXOPTS% %BUILDDIR%/coverage + if errorlevel 1 exit /b 1 + echo. + echo.Testing of coverage in the sources finished, look at the ^ +results in %BUILDDIR%/coverage/python.txt. + goto end +) + +if "%1" == "xml" ( + %SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The XML files are in %BUILDDIR%/xml. + goto end +) + +if "%1" == "pseudoxml" ( + %SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml. + goto end +) + +if "%1" == "dummy" ( + %SPHINXBUILD% -b dummy %ALLSPHINXOPTS% %BUILDDIR%/dummy + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. Dummy builder generates no files. + goto end +) + +:end From bffad47f10858010fc2b876988ff2e3383ef9f55 Mon Sep 17 00:00:00 2001 From: Mark Rogaski Date: Thu, 18 Aug 2016 09:26:34 -0400 Subject: [PATCH 11/22] Split test_views.py. --- discord_bind/tests/test_callback_view.py | 116 ++++++++++++++++++ .../{test_views.py => test_index_view.py} | 79 +----------- 2 files changed, 119 insertions(+), 76 deletions(-) create mode 100644 discord_bind/tests/test_callback_view.py rename discord_bind/tests/{test_views.py => test_index_view.py} (65%) diff --git a/discord_bind/tests/test_callback_view.py b/discord_bind/tests/test_callback_view.py new file mode 100644 index 0000000..eea9e4d --- /dev/null +++ b/discord_bind/tests/test_callback_view.py @@ -0,0 +1,116 @@ +""" + +The MIT License (MIT) + +Copyright (c) 2016, Mark Rogaski + +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. + +""" +from __future__ import unicode_literals + +try: + from unittest.mock import patch, mock, MagicMock +except ImportError: + from mock import patch, mock, MagicMock +try: + from urllib.parse import urlparse +except ImportError: + from urlparse import urlparse +import os + +from django.test import TestCase, RequestFactory, override_settings +from django.contrib.sessions.middleware import SessionMiddleware +from django.contrib.auth.models import User, AnonymousUser +from django.core.urlresolvers import reverse + +from discord_bind.views import callback +from discord_bind.conf import settings + +os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1' + + +class TestAccessTokenRequest(TestCase): + """ Test the authorization request view """ + def setUp(self): + self.factory = RequestFactory() + self.user = User.objects.create_user(username="Ralff", + email="ralff@example.com", + password="test") + + def tearDown(self): + self.user.delete() + + @override_settings(DISCORD_CLIENT_ID='212763200357720576') + def test_get_callback(self): + + @mock.patch('discord_bind.views.OAuth2Session.get') + @mock.patch('discord_bind.views.OAuth2Session.fetch_token') + def get_callback(user, query, mock_fetch, mock_get): + # build request + url = reverse('discord_bind_callback') + if query != '': + url = url + '?' + query + request = self.factory.get(url) + + # add user and session + request.user = user + middleware = SessionMiddleware() + middleware.process_request(request) + request.session['discord_bind_oauth_state'] = 'xyz' + request.session['discord_bind_invite_uri'] = ( + settings.DISCORD_INVITE_URI) + request.session['discord_bind_return_uri'] = ( + settings.DISCORD_RETURN_URI) + request.session.save() + + # build mock harness + mock_fetch.return_value = { + "access_token": "tvYhMddlVlxNGPtsAN34w9P6pivuLG", + "token_type": "Bearer", + "expires_in": 604800, + "refresh_token": "pUbZsF6BBZ8cD1CZqwxW25hCPUkQF5", + "scope": "email" + } + user_data = { + "avatar": "000d1294c515f3331cf32b31bc132f92", + "discriminator": "4021", + "email": "stigg@example.com", + "id": "132196734423007232", + "mfa_enabled": True, + "username": "stigg", + "verified": True + } + mock_response = mock.Mock() + mock_response.json.return_value = user_data + mock_get.return_value = mock_response + + # fire + return callback(request) + + # Anonymous users should bounce to the login page + response = get_callback(AnonymousUser(), '') + self.assertEqual(response.status_code, 302) + self.assertTrue('login' in response['location']) + + # Discord user binding + response = get_callback(self.user, + 'code=SplxlOBeZQQYbYS6WxSbIA&state=xyz') + self.assertEqual(response.status_code, 302) + self.assertEqual(response['location'], settings.DISCORD_RETURN_URI) diff --git a/discord_bind/tests/test_views.py b/discord_bind/tests/test_index_view.py similarity index 65% rename from discord_bind/tests/test_views.py rename to discord_bind/tests/test_index_view.py index 0a1c697..8834000 100644 --- a/discord_bind/tests/test_views.py +++ b/discord_bind/tests/test_index_view.py @@ -26,9 +26,9 @@ from __future__ import unicode_literals try: - from unittest.mock import patch, mock, MagicMock + from unittest.mock import patch, MagicMock except ImportError: - from mock import patch, mock, MagicMock + from mock import patch, MagicMock try: from urllib.parse import urlparse except ImportError: @@ -40,12 +40,9 @@ from django.contrib.auth.models import User, AnonymousUser from django.core.urlresolvers import reverse -from discord_bind.views import index, callback -from discord_bind.conf import settings +from discord_bind.views import index -os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1' - class TestAuthorizationRequest(TestCase): """ Test the authorization request view """ def setUp(self): @@ -142,73 +139,3 @@ def user_request(user, query=''): response = index(request) self.assertEqual(request.session['discord_bind_return_uri'], 'https://www.example.com/') - - -class TestAccessTokenRequest(TestCase): - """ Test the authorization request view """ - def setUp(self): - self.factory = RequestFactory() - self.user = User.objects.create_user(username="Ralff", - email="ralff@example.com", - password="test") - - def tearDown(self): - self.user.delete() - - @override_settings(DISCORD_CLIENT_ID='212763200357720576') - def test_get_callback(self): - - @mock.patch('discord_bind.views.OAuth2Session.get') - @mock.patch('discord_bind.views.OAuth2Session.fetch_token') - def get_callback(user, query, mock_fetch, mock_get): - # build request - url = reverse('discord_bind_callback') - if query != '': - url = url + '?' + query - request = self.factory.get(url) - - # add user and session - request.user = user - middleware = SessionMiddleware() - middleware.process_request(request) - request.session['discord_bind_oauth_state'] = 'xyz' - request.session['discord_bind_invite_uri'] = ( - settings.DISCORD_INVITE_URI) - request.session['discord_bind_return_uri'] = ( - settings.DISCORD_RETURN_URI) - request.session.save() - - # build mock harness - mock_fetch.return_value = { - "access_token": "tvYhMddlVlxNGPtsAN34w9P6pivuLG", - "token_type": "Bearer", - "expires_in": 604800, - "refresh_token": "pUbZsF6BBZ8cD1CZqwxW25hCPUkQF5", - "scope": "email" - } - user_data = { - "avatar": "000d1294c515f3331cf32b31bc132f92", - "discriminator": "4021", - "email": "stigg@example.com", - "id": "132196734423007232", - "mfa_enabled": True, - "username": "stigg", - "verified": True - } - mock_response = mock.Mock() - mock_response.json.return_value = user_data - mock_get.return_value = mock_response - - # fire - return callback(request) - - # Anonymous users should bounce to the login page - response = get_callback(AnonymousUser(), '') - self.assertEqual(response.status_code, 302) - self.assertTrue('login' in response['location']) - - # Discord user binding - response = get_callback(self.user, - 'code=SplxlOBeZQQYbYS6WxSbIA&state=xyz') - self.assertEqual(response.status_code, 302) - self.assertEqual(response['location'], settings.DISCORD_RETURN_URI) From 06cb764a2983437b37f17c96b8404cd513b53c15 Mon Sep 17 00:00:00 2001 From: Mark Rogaski Date: Thu, 18 Aug 2016 23:49:31 -0400 Subject: [PATCH 12/22] Expanded callback tests. --- discord_bind/tests/test_callback_view.py | 49 +++++++++++++++++++++--- 1 file changed, 43 insertions(+), 6 deletions(-) diff --git a/discord_bind/tests/test_callback_view.py b/discord_bind/tests/test_callback_view.py index eea9e4d..16560f7 100644 --- a/discord_bind/tests/test_callback_view.py +++ b/discord_bind/tests/test_callback_view.py @@ -37,10 +37,11 @@ from django.test import TestCase, RequestFactory, override_settings from django.contrib.sessions.middleware import SessionMiddleware -from django.contrib.auth.models import User, AnonymousUser +from django.contrib.auth.models import User, AnonymousUser, Group from django.core.urlresolvers import reverse from discord_bind.views import callback +from discord_bind.models import DiscordInvite from discord_bind.conf import settings os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1' @@ -53,6 +54,10 @@ def setUp(self): self.user = User.objects.create_user(username="Ralff", email="ralff@example.com", password="test") + g = Group.objects.create(name='Discord Users') + g.user_set.add(self.user) + for code in ['code0', 'code1', 'code2', 'code3']: + DiscordInvite.objects.create(code=code, active=False) def tearDown(self): self.user.delete() @@ -68,7 +73,7 @@ def get_callback(user, query, mock_fetch, mock_get): if query != '': url = url + '?' + query request = self.factory.get(url) - + # add user and session request.user = user middleware = SessionMiddleware() @@ -79,7 +84,7 @@ def get_callback(user, query, mock_fetch, mock_get): request.session['discord_bind_return_uri'] = ( settings.DISCORD_RETURN_URI) request.session.save() - + # build mock harness mock_fetch.return_value = { "access_token": "tvYhMddlVlxNGPtsAN34w9P6pivuLG", @@ -100,8 +105,8 @@ def get_callback(user, query, mock_fetch, mock_get): mock_response = mock.Mock() mock_response.json.return_value = user_data mock_get.return_value = mock_response - - # fire + + # fire return callback(request) # Anonymous users should bounce to the login page @@ -110,7 +115,39 @@ def get_callback(user, query, mock_fetch, mock_get): self.assertTrue('login' in response['location']) # Discord user binding - response = get_callback(self.user, + response = get_callback(self.user, 'code=SplxlOBeZQQYbYS6WxSbIA&state=xyz') self.assertEqual(response.status_code, 302) self.assertEqual(response['location'], settings.DISCORD_RETURN_URI) + + # Missing code + response = get_callback(self.user, + 'state=xyz') + self.assertEqual(response.status_code, 302) + self.assertEqual(response['location'], settings.DISCORD_RETURN_URI) + + # CSRF + response = get_callback(self.user, + 'code=SplxlOBeZQQYbYS6WxSbIA&state=abc') + self.assertEqual(response.status_code, 403) + response = get_callback(self.user, + 'error=server_error&state=abc') + self.assertEqual(response.status_code, 403) + + # Missing state + response = get_callback(self.user, + 'code=SplxlOBeZQQYbYS6WxSbIA') + self.assertEqual(response.status_code, 403) + response = get_callback(self.user, + 'error=server_error') + self.assertEqual(response.status_code, 403) + + # Valid error responses + for error in ['invalid_request', 'unauthorized_client', + 'access_denied', 'unsupported_response_type', + 'invalid_scope', 'server_error', + 'temporarily_unavailable']: + response = get_callback(self.user, + 'error=%s&state=xyz' % error) + self.assertEqual(response.status_code, 302) + self.assertEqual(response['location'], settings.DISCORD_RETURN_URI) From bbbfee8565ea6ee89913027ce9d098a8ef798df9 Mon Sep 17 00:00:00 2001 From: Mark Rogaski Date: Fri, 19 Aug 2016 00:05:04 -0400 Subject: [PATCH 13/22] Added tests for redirect_uri manipulation. --- discord_bind/tests/test_index_view.py | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/discord_bind/tests/test_index_view.py b/discord_bind/tests/test_index_view.py index 8834000..468421a 100644 --- a/discord_bind/tests/test_index_view.py +++ b/discord_bind/tests/test_index_view.py @@ -109,6 +109,16 @@ def user_request(user, query=''): self.assertEqual('https://discordapp.com/api/foo/bar', url.scheme + '://' + url.netloc + url.path) + # redirect uri tests + request = user_request(self.user, 'redirect_uri=https://foo.bar/cb') + response = index(request) + self.assertIn('redirect_uri=https%3A%2F%2Ffoo.bar%2Fcb', url.query) + + with self.settings(DISCORD_REDIRECT_URI='https://foo.bar/cb'): + request = user_request(self.user) + response = index(request) + self.assertIn('redirect_uri=https%3A%2F%2Ffoo.bar%2Fcb', url.query) + # invite uri tests request = user_request(self.user) response = index(request) From ca8541b06d19ac7ec5568c837a7c90c706fe00c5 Mon Sep 17 00:00:00 2001 From: Mark Rogaski Date: Fri, 19 Aug 2016 00:12:04 -0400 Subject: [PATCH 14/22] Fixed index view tests. --- discord_bind/conf.py | 3 ++- discord_bind/tests/test_index_view.py | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/discord_bind/conf.py b/discord_bind/conf.py index aee5835..a4039b3 100644 --- a/discord_bind/conf.py +++ b/discord_bind/conf.py @@ -43,7 +43,8 @@ class DiscordBindConf(AppConf): # OAuth2 scope EMAIL_SCOPE = True - # Return URI + # URI settings + REDIRECT_URI = None INVITE_URI = 'https://discordapp.com/channels/@me' RETURN_URI = '/' diff --git a/discord_bind/tests/test_index_view.py b/discord_bind/tests/test_index_view.py index 468421a..f89b8d1 100644 --- a/discord_bind/tests/test_index_view.py +++ b/discord_bind/tests/test_index_view.py @@ -112,7 +112,8 @@ def user_request(user, query=''): # redirect uri tests request = user_request(self.user, 'redirect_uri=https://foo.bar/cb') response = index(request) - self.assertIn('redirect_uri=https%3A%2F%2Ffoo.bar%2Fcb', url.query) + # We don't support this case + self.assertNotIn('redirect_uri=https%3A%2F%2Ffoo.bar%2Fcb', url.query) with self.settings(DISCORD_REDIRECT_URI='https://foo.bar/cb'): request = user_request(self.user) From db07397c0c6a1e2dade63bd96ad90f2f9d64c17a Mon Sep 17 00:00:00 2001 From: Mark Rogaski Date: Fri, 19 Aug 2016 00:21:17 -0400 Subject: [PATCH 15/22] Added DISCORD_REDIRECT_URI setting. --- discord_bind/tests/test_index_view.py | 1 + discord_bind/views.py | 6 +++++- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/discord_bind/tests/test_index_view.py b/discord_bind/tests/test_index_view.py index f89b8d1..9c4f7ee 100644 --- a/discord_bind/tests/test_index_view.py +++ b/discord_bind/tests/test_index_view.py @@ -118,6 +118,7 @@ def user_request(user, query=''): with self.settings(DISCORD_REDIRECT_URI='https://foo.bar/cb'): request = user_request(self.user) response = index(request) + url = urlparse(response['location']) self.assertIn('redirect_uri=https%3A%2F%2Ffoo.bar%2Fcb', url.query) # invite uri tests diff --git a/discord_bind/views.py b/discord_bind/views.py index a780534..5381281 100644 --- a/discord_bind/views.py +++ b/discord_bind/views.py @@ -49,7 +49,11 @@ def oauth_session(request, state=None, token=None): """ Constructs the OAuth2 session object. """ - redirect_uri = request.build_absolute_uri(reverse('discord_bind_callback')) + if settings.DISCORD_REDIRECT_URI is not None: + redirect_uri = settings.DISCORD_REDIRECT_URI + else: + redirect_uri = request.build_absolute_uri( + reverse('discord_bind_callback')) scope = (['email', 'guilds.join'] if settings.DISCORD_EMAIL_SCOPE else ['identity', 'guilds.join']) return OAuth2Session(settings.DISCORD_CLIENT_ID, From b586a9c9c4cad3cf17f46b34e7faa5174ce04fa8 Mon Sep 17 00:00:00 2001 From: Mark Rogaski Date: Fri, 19 Aug 2016 00:28:03 -0400 Subject: [PATCH 16/22] Added anti-CSRF validation. --- discord_bind/views.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/discord_bind/views.py b/discord_bind/views.py index 5381281..2700cb8 100644 --- a/discord_bind/views.py +++ b/discord_bind/views.py @@ -27,7 +27,7 @@ from datetime import datetime -from django.http import HttpResponseRedirect +from django.http import HttpResponseRedirect, HttpResponseForbidden try: from django.urls import reverse except ImportError: @@ -124,6 +124,8 @@ def bind_user(request, data): response = request.build_absolute_uri() state = request.session['discord_bind_oauth_state'] + if 'state' not in request.GET or request.GET['state'] != state: + return HttpResponseForbidden() oauth = oauth_session(request, state=state) token = oauth.fetch_token(settings.DISCORD_BASE_URI + settings.DISCORD_TOKEN_PATH, From f7e56684450bf7293d670428b4c9c091ca116907 Mon Sep 17 00:00:00 2001 From: Mark Rogaski Date: Fri, 19 Aug 2016 00:35:36 -0400 Subject: [PATCH 17/22] Updated change log. --- CHANGELOG.md | 34 -------------------------- discord_bind/__init__.py | 2 +- docs/changelog.rst | 53 ++++++++++++++++++++++++++++++++++++++++ setup.py | 2 +- 4 files changed, 55 insertions(+), 36 deletions(-) delete mode 100644 CHANGELOG.md create mode 100644 docs/changelog.rst diff --git a/CHANGELOG.md b/CHANGELOG.md deleted file mode 100644 index 8242f14..0000000 --- a/CHANGELOG.md +++ /dev/null @@ -1,34 +0,0 @@ -# Change Log - -This project uses [Semantic Versioning](http://semver.org/). - -## [0.1.3] -- 2016-08-14 -### Fixed -- Corrected all PEP8 issues. - -### Updated -- Documented all settings options. - -## [0.1.2] -- 2016-08-13 - -### Fixed -- Cleaned up package configuration. - -### Changed -- Disabled TravisCI e-mail notifications. - -## [0.1.1] -- 2016-08-13 - -### Fixed -- Removed migration dependencies. -- Cleaned up TravisCI configuration. - - -## 0.1.0 -- 2016-08-13 - -Initial release. - - -[0.1.3]: https://github.com/mrogaski/django-discord-bind/compare/0.1.2...0.1.3 -[0.1.2]: https://github.com/mrogaski/django-discord-bind/compare/0.1.1...0.1.2 -[0.1.1]: https://github.com/mrogaski/django-discord-bind/compare/0.1.0...0.1.1 diff --git a/discord_bind/__init__.py b/discord_bind/__init__.py index 2b18b78..0734afc 100644 --- a/discord_bind/__init__.py +++ b/discord_bind/__init__.py @@ -24,6 +24,6 @@ """ # following PEP 386 -__version__ = '0.1.4' +__version__ = '0.2.0' default_app_config = 'discord_bind.apps.DiscordBindConfig' diff --git a/docs/changelog.rst b/docs/changelog.rst new file mode 100644 index 0000000..2fc59ee --- /dev/null +++ b/docs/changelog.rst @@ -0,0 +1,53 @@ +Change Log +========== + +This project uses `Semantic Versioning `__. + +0.2.0 -- unreleased +------------------- + +Added +~~~~~ + +- Added the DISCORD_REDIRECT_URI setting. +- Added state validation to prevent CSRF attacks. + +0.1.3 -- 2016-08-14 +------------------- + +Fixed +~~~~~ + +- Corrected all PEP8 issues. + +Updated +~~~~~~~ + +- Documented all settings options. + +0.1.2 -- 2016-08-13 +------------------- + +Fixed +~~~~~ + +- Cleaned up package configuration. + +Changed +~~~~~~~ + +- Disabled TravisCI e-mail notifications. + +0.1.1 -- 2016-08-13 +------------------- + +Fixed +~~~~~ + +- Removed migration dependencies. +- Cleaned up TravisCI configuration. + +0.1.0 -- 2016-08-13 +------------------- + +Initial release. diff --git a/setup.py b/setup.py index 0ce60e8..2dd2ae8 100644 --- a/setup.py +++ b/setup.py @@ -36,7 +36,7 @@ setup( name='django-discord-bind', - version='0.1.3', + version='0.2.0', packages=find_packages(), include_package_data=True, license='MIT License', # example license From 5d9f55abf79e24c190586975625aa6ae5506de63 Mon Sep 17 00:00:00 2001 From: Mark Rogaski Date: Fri, 19 Aug 2016 00:39:22 -0400 Subject: [PATCH 18/22] FIxed mock imports. --- discord_bind/tests/test_callback_view.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/discord_bind/tests/test_callback_view.py b/discord_bind/tests/test_callback_view.py index 16560f7..93da8aa 100644 --- a/discord_bind/tests/test_callback_view.py +++ b/discord_bind/tests/test_callback_view.py @@ -26,9 +26,9 @@ from __future__ import unicode_literals try: - from unittest.mock import patch, mock, MagicMock + from unittest.mock import patch, Mock, MagicMock except ImportError: - from mock import patch, mock, MagicMock + from mock import patch, Mock, MagicMock try: from urllib.parse import urlparse except ImportError: @@ -65,8 +65,8 @@ def tearDown(self): @override_settings(DISCORD_CLIENT_ID='212763200357720576') def test_get_callback(self): - @mock.patch('discord_bind.views.OAuth2Session.get') - @mock.patch('discord_bind.views.OAuth2Session.fetch_token') + @patch('discord_bind.views.OAuth2Session.get') + @patch('discord_bind.views.OAuth2Session.fetch_token') def get_callback(user, query, mock_fetch, mock_get): # build request url = reverse('discord_bind_callback') @@ -102,7 +102,7 @@ def get_callback(user, query, mock_fetch, mock_get): "username": "stigg", "verified": True } - mock_response = mock.Mock() + mock_response = Mock() mock_response.json.return_value = user_data mock_get.return_value = mock_response From ca44d5c5312694202f12e8e7898d83ce3e9cdad6 Mon Sep 17 00:00:00 2001 From: Mark Rogaski Date: Fri, 19 Aug 2016 00:52:01 -0400 Subject: [PATCH 19/22] Updating docs. --- docs/index.rst | 3 +-- docs/settings.rst | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 33 insertions(+), 2 deletions(-) create mode 100644 docs/settings.rst diff --git a/docs/index.rst b/docs/index.rst index d720d9e..44e2808 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -7,8 +7,7 @@ Contents: .. toctree:: :maxdepth: 1 - configuration - administration + settings changelog diff --git a/docs/settings.rst b/docs/settings.rst new file mode 100644 index 0000000..cd2ca01 --- /dev/null +++ b/docs/settings.rst @@ -0,0 +1,32 @@ +.. _settings: + +Settings +======== + +.. currentmodule:: django.conf.settings + +Django Discord Bind has a number of settings that control its behavior. + + +Required settings +----------------- + +.. attribute:: DISCORD_CLIENT_ID + + The client identifier issued by the Discord authorization server. This + identifier is used in the authorization request of the OAuth 2.0 + Authorization Code Grant workflow. + +.. attribute:: DISCORD_CLIENT_SECRET + + A shared secret issued by the Discord authorization server. This + identifier is used in the access token request of the OAuth 2.0 + Authorization Code Grant workflow. + +.. attribute:: DISCORD_AUTHZ_PATH + + :Default: ``/oauth2/authorize`` + + The path of the authorization request service endpoint, which will be + appended to the DISCORD_BASE_URI setting. + From 055054a60659aa0c34f601462e14df28ad4815c2 Mon Sep 17 00:00:00 2001 From: Mark Rogaski Date: Fri, 19 Aug 2016 01:05:17 -0400 Subject: [PATCH 20/22] Updated docs. --- docs/settings.rst | 27 +++++++++++++++------------ 1 file changed, 15 insertions(+), 12 deletions(-) diff --git a/docs/settings.rst b/docs/settings.rst index cd2ca01..01fdabb 100644 --- a/docs/settings.rst +++ b/docs/settings.rst @@ -11,22 +11,25 @@ Django Discord Bind has a number of settings that control its behavior. Required settings ----------------- -.. attribute:: DISCORD_CLIENT_ID +DISCORD_CLIENT_ID +~~~~~~~~~~~~~~~~~ - The client identifier issued by the Discord authorization server. This - identifier is used in the authorization request of the OAuth 2.0 - Authorization Code Grant workflow. +The client identifier issued by the Discord authorization server. This +identifier is used in the authorization request of the OAuth 2.0 +Authorization Code Grant workflow. -.. attribute:: DISCORD_CLIENT_SECRET +DISCORD_CLIENT_SECRET +~~~~~~~~~~~~~~~~~~~~~ - A shared secret issued by the Discord authorization server. This - identifier is used in the access token request of the OAuth 2.0 - Authorization Code Grant workflow. +A shared secret issued by the Discord authorization server. This +identifier is used in the access token request of the OAuth 2.0 +Authorization Code Grant workflow. -.. attribute:: DISCORD_AUTHZ_PATH +DISCORD_AUTHZ_PATH +~~~~~~~~~~~~~~~~~~ - :Default: ``/oauth2/authorize`` + Default: ``/oauth2/authorize`` - The path of the authorization request service endpoint, which will be - appended to the DISCORD_BASE_URI setting. +The path of the authorization request service endpoint, which will be +appended to the DISCORD_BASE_URI setting. From edb3fb57d53bd7b728a1f90efb688e3485791219 Mon Sep 17 00:00:00 2001 From: Mark Rogaski Date: Fri, 19 Aug 2016 01:15:21 -0400 Subject: [PATCH 21/22] Updated docs. --- README.rst | 57 ----------------------------------------------- docs/conf.py | 4 +--- docs/settings.rst | 48 ++++++++++++++++++++++++++++++++++++--- 3 files changed, 46 insertions(+), 63 deletions(-) diff --git a/README.rst b/README.rst index 86837a2..6c2a3fe 100644 --- a/README.rst +++ b/README.rst @@ -50,63 +50,6 @@ Include the URL configuration in your project **urls.py**: Run ``python manage.py migrate`` to create the discord_bind models. -Configuration -------------- - -Required Settings -^^^^^^^^^^^^^^^^^ - -DISCORD_CLIENT_ID -~~~~~~~~~~~~~~~~~ -The client identifier issued by the Discord authorization server. This -identifier is used in the authorization request of the OAuth 2.0 -Authorization Code Grant workflow. - -DISCORD_CLIENT_SECRET -~~~~~~~~~~~~~~~~~~~~~ -A shared secret issued by the Discord authorization server. This -identifier is used in the access token request of the OAuth 2.0 -Authorization Code Grant workflow. - - -Optional Settings -^^^^^^^^^^^^^^^^^ - -DISCORD_AUTHZ_PATH -~~~~~~~~~~~~~~~~~~ -The path of the authorization request service endpoint, which will be -appended to the DISCORD_BASE_URI setting. - -Default: /oauth2/authorize - -DISCORD_BASE_URI -~~~~~~~~~~~~~~~~ -The base URI for the Discord API. - -Default: https://discordapp.com/api - -DISCORD_INVITE_URI -~~~~~~~~~~~~~~~~~~ -The URI that the user will be redirected to after one or more successful -auto-invites. - -Default: https://discordapp.com/channels/@me - -DISCORD_RETURN_URI -~~~~~~~~~~~~~~~~~~ -The URI that the user will be redirected to if no auto-invites are -attempted or successful. - -Default: / - -DISCORD_TOKEN_PATH -~~~~~~~~~~~~~~~~~~ -The path of the access token request service endpoint, which will be -appended to the DISCORD_BASE_URI setting. - -Default: /oauth2/token - - License ------- diff --git a/docs/conf.py b/docs/conf.py index c5647b0..49cb5db 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -30,9 +30,7 @@ # 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.githubpages', -] +extensions = [] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] diff --git a/docs/settings.rst b/docs/settings.rst index 01fdabb..33437c6 100644 --- a/docs/settings.rst +++ b/docs/settings.rst @@ -8,7 +8,7 @@ Settings Django Discord Bind has a number of settings that control its behavior. -Required settings +Required Settings ----------------- DISCORD_CLIENT_ID @@ -17,14 +17,17 @@ DISCORD_CLIENT_ID The client identifier issued by the Discord authorization server. This identifier is used in the authorization request of the OAuth 2.0 Authorization Code Grant workflow. - + DISCORD_CLIENT_SECRET ~~~~~~~~~~~~~~~~~~~~~ A shared secret issued by the Discord authorization server. This identifier is used in the access token request of the OAuth 2.0 Authorization Code Grant workflow. - + +Optional Settings +----------------- + DISCORD_AUTHZ_PATH ~~~~~~~~~~~~~~~~~~ @@ -33,3 +36,42 @@ DISCORD_AUTHZ_PATH The path of the authorization request service endpoint, which will be appended to the DISCORD_BASE_URI setting. +DISCORD_BASE_URI +~~~~~~~~~~~~~~~~ + + Default: ``https://discordapp.com/api`` + +The base URI for the Discord API. + +DISCORD_INVITE_URI +~~~~~~~~~~~~~~~~~~ + + Default: ``https://discordapp.com/channels/@me`` + +The URI that the user will be redirected to after one or more successful +auto-invites. + +DISCORD_REDIRECT_URI +~~~~~~~~~~~~~~~~~~ + + Default: ``reverse('discord_bind_callback')`` + +The URI that will be passed to the Discord authorization endpoint as the +URI for the callback route. Normally this is determined by Django, but +it can be set manually if the application is behind a proxy. + +DISCORD_RETURN_URI +~~~~~~~~~~~~~~~~~~ + + Default: ``/`` + +The URI that the user will be redirected to if no auto-invites are +attempted or successful. + +DISCORD_TOKEN_PATH +~~~~~~~~~~~~~~~~~~ + + Default: ``/oauth2/token`` + +The path of the access token request service endpoint, which will be +appended to the DISCORD_BASE_URI setting. From d35a7fdd47f2bc4d892d8a2ec506289b51da8306 Mon Sep 17 00:00:00 2001 From: Mark Rogaski Date: Fri, 19 Aug 2016 02:03:27 -0400 Subject: [PATCH 22/22] Documentation updates. --- README.rst | 36 +++++------------------------------- docs/changelog.rst | 7 ++++++- docs/conf.py | 16 ++++++++++------ docs/index.rst | 7 +++---- docs/installation.rst | 28 ++++++++++++++++++++++++++++ 5 files changed, 52 insertions(+), 42 deletions(-) create mode 100644 docs/installation.rst diff --git a/README.rst b/README.rst index 6c2a3fe..4d67555 100644 --- a/README.rst +++ b/README.rst @@ -1,4 +1,3 @@ -=================== django-discord-bind =================== @@ -6,9 +5,13 @@ django-discord-bind .. image:: https://badge.fury.io/py/django-discord-bind.svg :target: https://badge.fury.io/py/django-discord-bind + :alt: Git Repository .. image:: https://travis-ci.org/mrogaski/django-discord-bind.svg?branch=master :target: https://travis-ci.org/mrogaski/django-discord-bind - + :alt: Build Status +.. image:: https://readthedocs.org/projects/django-discord-bind/badge/?version=latest + :target: http://django-discord-bind.readthedocs.io/en/latest/?badge=latest + :alt: Documentation Status This is a simple Django application that allows users to associate one or more Discord accounts to their Django accounts and automatically join a @@ -21,35 +24,6 @@ Requirements * Python 2.7, 3.4, 3.5 * Django 1.9, 1.10 - -Installation ------------- - -Install with pip:: - - pip install django-discord-bind - -Add `discord_bind` to your `INSTALLED_APPS` setting: - -.. code-block:: python - - INSTALLED_APPS = [ - ... - 'discord_bind', - ] - -Include the URL configuration in your project **urls.py**: - -.. code-block:: python - - urlpatterns = [ - ... - url(r'^discord/', include('discord_bind.urls')), - ] - -Run ``python manage.py migrate`` to create the discord_bind models. - - License ------- diff --git a/docs/changelog.rst b/docs/changelog.rst index 2fc59ee..fa20d79 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -3,7 +3,7 @@ Change Log This project uses `Semantic Versioning `__. -0.2.0 -- unreleased +0.2.0 -- 2016-08-19 ------------------- Added @@ -12,6 +12,11 @@ Added - Added the DISCORD_REDIRECT_URI setting. - Added state validation to prevent CSRF attacks. +Updated +~~~~~~~ + +- Added more documentation. + 0.1.3 -- 2016-08-14 ------------------- diff --git a/docs/conf.py b/docs/conf.py index 49cb5db..0c8edc6 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -2,7 +2,7 @@ # -*- coding: utf-8 -*- # # django-discord-bind documentation build configuration file, created by -# sphinx-quickstart on Wed Aug 17 18:11:27 2016. +# sphinx-quickstart on Fri Aug 19 01:33:24 2016. # # This file is execfile()d with the current directory set to its # containing dir. @@ -57,10 +57,14 @@ # |version| and |release|, also used in various other places throughout the # built documents. # -# The short X.Y version. -version = '0.2' -# The full version, including alpha/beta/rc tags. -release = '0.2.0' +try: + from discord_bind import __version__ + # The short X.Y version. + version = '.'.join(__version__.split('.')[:2]) + # The full version, including alpha/beta/rc tags. + release = __version__ +except ImportError: + version = release = 'dev' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. @@ -120,7 +124,7 @@ # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # -html_theme = 'alabaster' +html_theme = 'default' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the diff --git a/docs/index.rst b/docs/index.rst index 44e2808..14e3b36 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -1,12 +1,12 @@ .. include:: ../README.rst - -Contents: -========= +Contents +======== .. toctree:: :maxdepth: 1 + installation settings changelog @@ -17,4 +17,3 @@ Indices and tables * :ref:`genindex` * :ref:`modindex` * :ref:`search` - diff --git a/docs/installation.rst b/docs/installation.rst new file mode 100644 index 0000000..78c2e5a --- /dev/null +++ b/docs/installation.rst @@ -0,0 +1,28 @@ +.. _installation: + +Installation +------------ + +Install with pip:: + + pip install django-discord-bind + +Add `discord_bind` to your `INSTALLED_APPS` setting: + +.. code-block:: python + + INSTALLED_APPS = [ + ... + 'discord_bind', + ] + +Include the URL configuration in your project **urls.py**: + +.. code-block:: python + + urlpatterns = [ + ... + url(r'^discord/', include('discord_bind.urls')), + ] + +Run ``python manage.py migrate`` to create the discord_bind models.