diff options
Diffstat (limited to 'pydis_site/apps')
-rw-r--r-- | pydis_site/apps/home/__init__.py | 1 | ||||
-rw-r--r-- | pydis_site/apps/home/apps.py | 33 | ||||
-rw-r--r-- | pydis_site/apps/home/signals.py | 159 | ||||
-rw-r--r-- | pydis_site/apps/home/tests/test_signal_listener.py | 310 | ||||
-rw-r--r-- | pydis_site/apps/home/tests/test_views.py | 14 | ||||
-rw-r--r-- | pydis_site/apps/home/urls.py | 22 | ||||
-rw-r--r-- | pydis_site/apps/staff/admin.py | 6 | ||||
-rw-r--r-- | pydis_site/apps/staff/migrations/0001_initial.py | 25 | ||||
-rw-r--r-- | pydis_site/apps/staff/models/__init__.py | 3 | ||||
-rw-r--r-- | pydis_site/apps/staff/models/role_mapping.py | 24 |
10 files changed, 596 insertions, 1 deletions
diff --git a/pydis_site/apps/home/__init__.py b/pydis_site/apps/home/__init__.py index e69de29b..ecfab449 100644 --- a/pydis_site/apps/home/__init__.py +++ b/pydis_site/apps/home/__init__.py @@ -0,0 +1 @@ +default_app_config = "pydis_site.apps.home.apps.HomeConfig" diff --git a/pydis_site/apps/home/apps.py b/pydis_site/apps/home/apps.py index 9a3d213c..a7c47dc5 100644 --- a/pydis_site/apps/home/apps.py +++ b/pydis_site/apps/home/apps.py @@ -1,7 +1,38 @@ +from typing import Any, Dict + from django.apps import AppConfig class HomeConfig(AppConfig): """Django AppConfig for the home app.""" - name = 'home' + name = 'pydis_site.apps.home' + signal_listener = None + + def ready(self) -> None: + """Run when the app has been loaded and is ready to serve requests.""" + from pydis_site.apps.home.signals import SignalListener + + self.signal_listener = SignalListener() + self.patch_allauth() + + def patch_allauth(self) -> None: + """Monkey-patches Allauth classes so we never collect email addresses.""" + # Imported here because we can't import it before our apps are loaded up + from allauth.socialaccount.providers.base import Provider + + def extract_extra_data(_: Provider, data: Dict[str, Any]) -> Dict[str, Any]: + """ + Extracts extra data for a SocialAccount provided by Allauth. + + This is our version of this function that strips the email address from incoming extra + data. We do this so that we never have to store it. + + This is monkey-patched because most OAuth providers - or at least the ones we care + about - all use the function from the base Provider class. This means we don't have + to make a new Django app for each one we want to work with. + """ + data["email"] = "" + return data + + Provider.extract_extra_data = extract_extra_data diff --git a/pydis_site/apps/home/signals.py b/pydis_site/apps/home/signals.py new file mode 100644 index 00000000..a5577f41 --- /dev/null +++ b/pydis_site/apps/home/signals.py @@ -0,0 +1,159 @@ +from typing import List, Type + +from allauth.account.signals import user_logged_in +from allauth.socialaccount.models import SocialAccount, SocialLogin +from allauth.socialaccount.providers.base import Provider +from allauth.socialaccount.providers.discord.provider import DiscordProvider +from allauth.socialaccount.signals import ( + pre_social_login, social_account_added, social_account_removed, + social_account_updated) +from django.contrib.auth.models import Group, User as DjangoUser +from django.db.models.signals import post_save + +from pydis_site.apps.api.models import User as DiscordUser +from pydis_site.apps.staff.models import RoleMapping + + +class SignalListener: + """ + Listens to and processes events via the Django Signals system. + + Django Signals is basically an event dispatcher. It consists of Signals (which are the events) + and Receivers, which listen for and handle those events. Signals are triggered by Senders, + which are essentially just any class at all, and Receivers can filter the Signals they listen + for by choosing a Sender, if required. + + Signals themselves define a set of arguments that they will provide to Receivers when the + Signal is sent. They are always keyword arguments, and Django recommends that all Receiver + functions accept them as `**kwargs` (and will supposedly error if you don't do this), + supposedly because Signals can change in the future and your receivers should still work. + + Signals do provide a list of their arguments when they're initially constructed, but this + is purely for documentation purposes only and Django does not enforce it. + + The Django Signals docs are here: https://docs.djangoproject.com/en/2.2/topics/signals/ + """ + + def __init__(self): + post_save.connect(self.model_updated, sender=DiscordUser) + + pre_social_login.connect(self.social_account_updated) + social_account_added.connect(self.social_account_updated) + social_account_updated.connect(self.social_account_updated) + social_account_removed.connect(self.social_account_removed) + + user_logged_in.connect(self.user_logged_in) + + def user_logged_in(self, sender: Type[DjangoUser], **kwargs) -> None: + """Handles signals relating to Allauth logins.""" + user: DjangoUser = kwargs["user"] + + try: + account: SocialAccount = SocialAccount.objects.get( + user=user, provider=DiscordProvider.id + ) + except SocialAccount.DoesNotExist: + return # User's never linked a Discord account + + try: + discord_user: DiscordUser = DiscordUser.objects.get(id=int(account.uid)) + except DiscordUser.DoesNotExist: + return + + self._apply_groups(discord_user, account) + + def social_account_updated(self, sender: Type[SocialLogin], **kwargs) -> None: + """Handle signals relating to new/existing social accounts.""" + social_login: SocialLogin = kwargs["sociallogin"] + + account: SocialAccount = social_login.account + provider: Provider = account.get_provider() + + if not isinstance(provider, DiscordProvider): + return + + try: + user: DiscordUser = DiscordUser.objects.get(id=int(account.uid)) + except DiscordUser.DoesNotExist: + return + + self._apply_groups(user, account) + + def social_account_removed(self, sender: Type[SocialLogin], **kwargs) -> None: + """Handle signals relating to removal of social accounts.""" + account: SocialAccount = kwargs["socialaccount"] + provider: Provider = account.get_provider() + + if not isinstance(provider, DiscordProvider): + return + + try: + user: DiscordUser = DiscordUser.objects.get(id=int(account.uid)) + except DiscordUser.DoesNotExist: + return + + self._apply_groups(user, account, True) + + def model_updated(self, sender: Type[DiscordUser], **kwargs) -> None: + """Handle signals related to the updating of Discord User model entries.""" + instance: DiscordUser = kwargs["instance"] + raw: bool = kwargs["raw"] + + # `update_fields` could be used for checking changes, but it's None here due to how the + # model is saved without using that argument - so we can't use it. + + if raw: + # Fixtures are being loaded, so don't touch anything + return + + try: + account: SocialAccount = SocialAccount.objects.get( + uid=str(instance.id), provider=DiscordProvider.id + ) + except SocialAccount.DoesNotExist: + return # User has never logged in with Discord on the site + + self._apply_groups(instance, account) + + def _apply_groups( + self, user: DiscordUser, account: SocialAccount, deletion: bool = False + ) -> None: + mappings = RoleMapping.objects.all() + + try: + current_groups: List[Group] = list(account.user.groups.all()) + except SocialAccount.user.RelatedObjectDoesNotExist: + return # There's no user account yet, this will be handled by another receiver + + if not user.in_guild: + deletion = True + + if deletion: + # They've unlinked Discord or left the server, so we have to remove their groups + + if not current_groups: + return # They have no groups anyway, no point in processing + + account.user.groups.remove( + *(mapping.group for mapping in mappings) + ) + else: + new_groups = [] + + for role in user.roles.all(): + try: + new_groups.append(mappings.get(role=role).group) + except RoleMapping.DoesNotExist: + continue # No mapping exists + + remove_groups = [ + mapping.group for mapping in mappings if mapping.group not in new_groups + ] + + add_groups = [group for group in new_groups if group not in current_groups] + + if remove_groups: + account.user.groups.remove(*remove_groups) + + if add_groups: + account.user.groups.add(*add_groups) diff --git a/pydis_site/apps/home/tests/test_signal_listener.py b/pydis_site/apps/home/tests/test_signal_listener.py new file mode 100644 index 00000000..b7400558 --- /dev/null +++ b/pydis_site/apps/home/tests/test_signal_listener.py @@ -0,0 +1,310 @@ +from unittest import mock + +from allauth.account.signals import user_logged_in +from allauth.socialaccount.models import SocialAccount, SocialLogin +from allauth.socialaccount.providers.discord.provider import DiscordProvider +from allauth.socialaccount.providers.github.provider import GitHubProvider +from allauth.socialaccount.signals import ( + pre_social_login, social_account_added, social_account_removed, + social_account_updated) +from django.contrib.auth.models import Group, User as DjangoUser +from django.db.models.signals import post_save +from django.test import TestCase + +from pydis_site.apps.api.models import Role, User as DiscordUser +from pydis_site.apps.home.signals import SignalListener +from pydis_site.apps.staff.models import RoleMapping + + +class SignalListenerTests(TestCase): + @classmethod + def setUpTestData(cls): + """Executed when testing begins.""" + cls.admin_role = Role.objects.create( + id=0, + name="admin", + colour=0, + permissions=0, + position=0 + ) + + cls.admin_group = Group.objects.create(name="admin") + + cls.role_mapping = RoleMapping.objects.create( + role=cls.admin_role, + group=cls.admin_group + ) + + cls.unmapped_role = Role.objects.create( + id=1, + name="unmapped", + colour=0, + permissions=0, + position=1 + ) + + cls.discord_user = DiscordUser.objects.create( + id=0, + name="user", + discriminator=0, + avatar_hash=None + ) + + cls.discord_unmapped = DiscordUser.objects.create( + id=2, + name="unmapped", + discriminator=0, + avatar_hash=None + ) + + cls.discord_unmapped.roles.add(cls.unmapped_role) + cls.discord_unmapped.save() + + cls.discord_not_in_guild = DiscordUser.objects.create( + id=3, + name="not-in-guild", + discriminator=0, + avatar_hash=None, + in_guild=False + ) + + cls.discord_admin = DiscordUser.objects.create( + id=1, + name="admin", + discriminator=0, + avatar_hash=None + ) + + cls.discord_admin.roles.set([cls.admin_role]) + cls.discord_admin.save() + + cls.django_user_discordless = DjangoUser.objects.create(username="no-discord") + cls.django_user_never_joined = DjangoUser.objects.create(username="never-joined") + + cls.social_never_joined = SocialAccount.objects.create( + user=cls.django_user_never_joined, + provider=DiscordProvider.id, + uid=5 + ) + + cls.django_user = DjangoUser.objects.create(username="user") + + cls.social_user = SocialAccount.objects.create( + user=cls.django_user, + provider=DiscordProvider.id, + uid=cls.discord_user.id + ) + + cls.social_user_github = SocialAccount.objects.create( + user=cls.django_user, + provider=GitHubProvider.id, + uid=cls.discord_user.id + ) + + cls.social_unmapped = SocialAccount( + # We instantiate it and don't put it in the DB. This is (surprisingly) + # a realistic test case, so we need to check for it + + provider=DiscordProvider.id, + uid=5, + user_id=None # No relation exists at all + ) + + cls.django_admin = DjangoUser.objects.create( + username="admin", + is_staff=True, + is_superuser=True + ) + + cls.social_admin = SocialAccount.objects.create( + user=cls.django_admin, + provider=DiscordProvider.id, + uid=cls.discord_admin.id + ) + + def test_model_save(self): + """Test signal handling for when Discord user model objects are saved to DB.""" + mock_obj = mock.Mock() + + with mock.patch.object(SignalListener, "_apply_groups", mock_obj): + _ = SignalListener() + + post_save.send( + DiscordUser, + instance=self.discord_user, + raw=True, + created=None, # Not realistic, but we don't use it + using=None, # Again, we don't use it + update_fields=False # Always false during integration testing + ) + + mock_obj.assert_not_called() + + post_save.send( + DiscordUser, + instance=self.discord_user, + raw=False, + created=None, # Not realistic, but we don't use it + using=None, # Again, we don't use it + update_fields=False # Always false during integration testing + ) + + mock_obj.assert_called_with(self.discord_user, self.social_user) + + def test_pre_social_login(self): + """Test the pre-social-login Allauth signal handling.""" + mock_obj = mock.Mock() + + discord_login = SocialLogin(self.django_user, self.social_user) + github_login = SocialLogin(self.django_user, self.social_user_github) + unmapped_login = SocialLogin(self.django_user, self.social_unmapped) + + with mock.patch.object(SignalListener, "_apply_groups", mock_obj): + _ = SignalListener() + + # Don't attempt to apply groups if the user doesn't have a linked Discord account + pre_social_login.send(SocialLogin, sociallogin=github_login) + mock_obj.assert_not_called() + + # Don't attempt to apply groups if the user hasn't joined the Discord server + pre_social_login.send(SocialLogin, sociallogin=unmapped_login) + mock_obj.assert_not_called() + + # Attempt to apply groups if everything checks out + pre_social_login.send(SocialLogin, sociallogin=discord_login) + mock_obj.assert_called_with(self.discord_user, self.social_user) + + def test_social_added(self): + """Test the social-account-added Allauth signal handling.""" + mock_obj = mock.Mock() + + discord_login = SocialLogin(self.django_user, self.social_user) + github_login = SocialLogin(self.django_user, self.social_user_github) + unmapped_login = SocialLogin(self.django_user, self.social_unmapped) + + with mock.patch.object(SignalListener, "_apply_groups", mock_obj): + _ = SignalListener() + + # Don't attempt to apply groups if the user doesn't have a linked Discord account + social_account_added.send(SocialLogin, sociallogin=github_login) + mock_obj.assert_not_called() + + # Don't attempt to apply groups if the user hasn't joined the Discord server + social_account_added.send(SocialLogin, sociallogin=unmapped_login) + mock_obj.assert_not_called() + + # Attempt to apply groups if everything checks out + social_account_added.send(SocialLogin, sociallogin=discord_login) + mock_obj.assert_called_with(self.discord_user, self.social_user) + + def test_social_updated(self): + """Test the social-account-updated Allauth signal handling.""" + mock_obj = mock.Mock() + + discord_login = SocialLogin(self.django_user, self.social_user) + github_login = SocialLogin(self.django_user, self.social_user_github) + unmapped_login = SocialLogin(self.django_user, self.social_unmapped) + + with mock.patch.object(SignalListener, "_apply_groups", mock_obj): + _ = SignalListener() + + # Don't attempt to apply groups if the user doesn't have a linked Discord account + social_account_updated.send(SocialLogin, sociallogin=github_login) + mock_obj.assert_not_called() + + # Don't attempt to apply groups if the user hasn't joined the Discord server + social_account_updated.send(SocialLogin, sociallogin=unmapped_login) + mock_obj.assert_not_called() + + # Attempt to apply groups if everything checks out + social_account_updated.send(SocialLogin, sociallogin=discord_login) + mock_obj.assert_called_with(self.discord_user, self.social_user) + + def test_social_removed(self): + """Test the social-account-removed Allauth signal handling.""" + mock_obj = mock.Mock() + + with mock.patch.object(SignalListener, "_apply_groups", mock_obj): + _ = SignalListener() + + # Don't attempt to remove groups if the user doesn't have a linked Discord account + social_account_removed.send(SocialLogin, socialaccount=self.social_user_github) + mock_obj.assert_not_called() + + # Don't attempt to remove groups if the social account doesn't map to a Django user + social_account_removed.send(SocialLogin, socialaccount=self.social_unmapped) + mock_obj.assert_not_called() + + # Attempt to remove groups if everything checks out + social_account_removed.send(SocialLogin, socialaccount=self.social_user) + mock_obj.assert_called_with(self.discord_user, self.social_user, True) + + def test_logged_in(self): + """Test the user-logged-in Allauth signal handling.""" + mock_obj = mock.Mock() + + with mock.patch.object(SignalListener, "_apply_groups", mock_obj): + _ = SignalListener() + + # Don't attempt to apply groups if the user doesn't have a linked Discord account + user_logged_in.send(DjangoUser, user=self.django_user_discordless) + mock_obj.assert_not_called() + + # Don't attempt to apply groups if the user hasn't joined the Discord server + user_logged_in.send(DjangoUser, user=self.django_user_never_joined) + mock_obj.assert_not_called() + + # Attempt to apply groups if everything checks out + user_logged_in.send(DjangoUser, user=self.django_user) + mock_obj.assert_called_with(self.discord_user, self.social_user) + + def test_apply_groups_admin(self): + """Test application of groups by role, relating to an admin user.""" + handler = SignalListener() + + self.assertTrue(self.django_user_discordless.groups.all().count() == 0) + + # Apply groups based on admin role being present on Discord + handler._apply_groups(self.discord_admin, self.social_admin) + self.assertTrue(self.admin_group in self.django_admin.groups.all()) + + # Remove groups based on the user apparently leaving the server + handler._apply_groups(self.discord_admin, self.social_admin, True) + self.assertTrue(self.django_user_discordless.groups.all().count() == 0) + + # Apply the admin role again + handler._apply_groups(self.discord_admin, self.social_admin) + + # Remove all of the roles from the user + self.discord_admin.roles.clear() + + # Remove groups based on the user no longer having the admin role on Discord + handler._apply_groups(self.discord_admin, self.social_admin) + self.assertTrue(self.django_user_discordless.groups.all().count() == 0) + + self.discord_admin.roles.add(self.admin_role) + self.discord_admin.save() + + def test_apply_groups_other(self): + """Test application of groups by role, relating to non-standard cases.""" + handler = SignalListener() + + self.assertTrue(self.django_user_discordless.groups.all().count() == 0) + + # No groups should be applied when there's no user account yet + handler._apply_groups(self.discord_unmapped, self.social_unmapped) + self.assertTrue(self.django_user_discordless.groups.all().count() == 0) + + # No groups should be applied when there are only unmapped roles to match + handler._apply_groups(self.discord_unmapped, self.social_user) + self.assertTrue(self.django_user.groups.all().count() == 0) + + # No groups should be applied when the user isn't in the guild + handler._apply_groups(self.discord_not_in_guild, self.social_user) + self.assertTrue(self.django_user.groups.all().count() == 0) + + def test_role_mapping_str(self): + """Test that role mappings stringify correctly.""" + self.assertTrue( + str(self.role_mapping) == f"@{self.admin_role.name} -> {self.admin_group.name}" + ) diff --git a/pydis_site/apps/home/tests/test_views.py b/pydis_site/apps/home/tests/test_views.py index 73678b0a..aa434605 100644 --- a/pydis_site/apps/home/tests/test_views.py +++ b/pydis_site/apps/home/tests/test_views.py @@ -7,3 +7,17 @@ class TestIndexReturns200(TestCase): url = reverse('home') resp = self.client.get(url) self.assertEqual(resp.status_code, 200) + + +class TestLoginCancelledReturns302(TestCase): + def test_login_cancelled_returns_302(self): + url = reverse('socialaccount_login_cancelled') + resp = self.client.get(url) + self.assertEqual(resp.status_code, 302) + + +class TestLoginErrorReturns302(TestCase): + def test_login_error_returns_302(self): + url = reverse('socialaccount_login_error') + resp = self.client.get(url) + self.assertEqual(resp.status_code, 302) diff --git a/pydis_site/apps/home/urls.py b/pydis_site/apps/home/urls.py index e65abea4..8428327f 100644 --- a/pydis_site/apps/home/urls.py +++ b/pydis_site/apps/home/urls.py @@ -1,14 +1,36 @@ +from allauth.account.views import LogoutView +from allauth.socialaccount.views import ConnectionsView from django.conf import settings from django.conf.urls.static import static from django.contrib import admin +from django.contrib.messages import ERROR from django.urls import include, path +from pydis_site.utils.views import MessageRedirectView from .views import HomeView app_name = 'home' urlpatterns = [ path('', HomeView.as_view(), name='home'), path('pages/', include('wiki.urls')), + + path('accounts/', include('allauth.socialaccount.providers.discord.urls')), + + path( + 'accounts/login/cancelled', MessageRedirectView.as_view( + pattern_name="home", message="Login cancelled." + ), name='socialaccount_login_cancelled' + ), + path( + 'accounts/login/error', MessageRedirectView.as_view( + pattern_name="home", message="Login failed due to an error, please try again.", + message_level=ERROR + ), name='socialaccount_login_error' + ), + + path('connections', ConnectionsView.as_view()), + path('logout', LogoutView.as_view(), name="logout"), + path('admin/', admin.site.urls), path('notifications/', include('django_nyt.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) diff --git a/pydis_site/apps/staff/admin.py b/pydis_site/apps/staff/admin.py new file mode 100644 index 00000000..94cd83c5 --- /dev/null +++ b/pydis_site/apps/staff/admin.py @@ -0,0 +1,6 @@ +from django.contrib import admin + +from .models import RoleMapping + + +admin.site.register(RoleMapping) diff --git a/pydis_site/apps/staff/migrations/0001_initial.py b/pydis_site/apps/staff/migrations/0001_initial.py new file mode 100644 index 00000000..7748e553 --- /dev/null +++ b/pydis_site/apps/staff/migrations/0001_initial.py @@ -0,0 +1,25 @@ +# Generated by Django 2.2.6 on 2019-10-03 18:24 + +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ('auth', '0011_update_proxy_permissions'), + ('api', '0043_infraction_hidden_warnings_to_notes'), + ] + + operations = [ + migrations.CreateModel( + name='RoleMapping', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('group', models.OneToOneField(help_text='The Django permissions group to use for this mapping.', on_delete=django.db.models.deletion.CASCADE, to='auth.Group')), + ('role', models.OneToOneField(help_text='The Discord role to use for this mapping.', on_delete=django.db.models.deletion.CASCADE, to='api.Role')), + ], + ), + ] diff --git a/pydis_site/apps/staff/models/__init__.py b/pydis_site/apps/staff/models/__init__.py index e69de29b..b49b6fd0 100644 --- a/pydis_site/apps/staff/models/__init__.py +++ b/pydis_site/apps/staff/models/__init__.py @@ -0,0 +1,3 @@ +from .role_mapping import RoleMapping + +__all__ = ["RoleMapping"] diff --git a/pydis_site/apps/staff/models/role_mapping.py b/pydis_site/apps/staff/models/role_mapping.py new file mode 100644 index 00000000..5c728283 --- /dev/null +++ b/pydis_site/apps/staff/models/role_mapping.py @@ -0,0 +1,24 @@ +from django.contrib.auth.models import Group +from django.db import models + +from pydis_site.apps.api.models import Role + + +class RoleMapping(models.Model): + """A mapping between a Discord role and Django permissions group.""" + + role = models.OneToOneField( + Role, + on_delete=models.CASCADE, + help_text="The Discord role to use for this mapping." + ) + + group = models.OneToOneField( + Group, + on_delete=models.CASCADE, + help_text="The Django permissions group to use for this mapping." + ) + + def __str__(self): + """Returns the mapping, for display purposes.""" + return f"@{self.role.name} -> {self.group.name}" |