Self hosted FLOSS fitness/workout, nutrition and weight tracker
Cleanup and refactor the social auth login code
Roland Geidere48a6460dc19
diff --git a/settings/ci.py b/settings/ci.pyindex 319a976b3..04423b09c 100644--- a/settings/ci.py+++ b/settings/ci.py@@ -1,18 +1,16 @@-# This file is part of wger Workout Manager <https://github.com/wger-project>.-# Copyright (C) 2013 - 2026 wger Team+# This file is part of wger Workout Manager.#-# wger Workout Manager is free software: you can redistribute it and/or modify-# it under the terms of the GNU Affero General Public License as published by-# the Free Software Foundation, either version 3 of the License, or-# (at your option) any later version.+# wger Workout Manager is free software: you can redistribute it and/or modify+# it under the terms of the GNU Affero General Public License as published by+# the Free Software Foundation, either version 3 of the License, or+# (at your option) any later version.#-# wger Workout Manager is distributed in the hope that it will be useful,-# but WITHOUT ANY WARRANTY; without even the implied warranty of-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the-# GNU Affero General Public License for more details.+# wger Workout Manager is distributed in the hope that it will be useful,+# but WITHOUT ANY WARRANTY; without even the implied warranty of+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+# GNU General Public License for more details.#-# You should have received a copy of the GNU Affero General Public License-# along with this program. If not, see <http://www.gnu.org/licenses/>.+# You should have received a copy of the GNU Affero General Public License# ruff: noqa: F405, F403@@ -49,8 +47,6 @@ WGER_SETTINGS['ALLOW_GUEST_USERS'] = TrueWGER_SETTINGS['ALLOW_UPLOAD_VIDEOS'] = FalseWGER_SETTINGS['MIN_ACCOUNT_AGE_TO_TRUST'] = 21 # in daysWGER_SETTINGS['EXERCISE_CACHE_TTL'] = 3600 # in seconds-WGER_SETTINGS['USE_GOOGLE_AUTH'] = False-WGER_SETTINGS['USE_SOCIAL_AUTH'] = FalseDATABASES = {'default': {diff --git a/settings/local_dev.py b/settings/local_dev.pyindex e4f5d2c64..998a3d4ca 100644--- a/settings/local_dev.py+++ b/settings/local_dev.py@@ -38,8 +38,6 @@ WGER_SETTINGS['USE_CELERY'] = FalseWGER_SETTINGS['CACHE_API_EXERCISES_CELERY'] = TrueWGER_SETTINGS['CACHE_API_EXERCISES_CELERY_FORCE_UPDATE'] = TrueWGER_SETTINGS['ROUTINE_CACHE_TTL'] = 500-WGER_SETTINGS['USE_GOOGLE_AUTH'] = True-WGER_SETTINGS['USE_SOCIAL_AUTH'] = TrueDEFAULT_FROM_EMAIL = WGER_SETTINGS['EMAIL_FROM']diff --git a/settings/main.py b/settings/main.pyindex 0aef9e56d..4010299a6 100644--- a/settings/main.py+++ b/settings/main.py@@ -260,10 +260,15 @@ AXES_IPWARE_META_PRECEDENCE_ORDER = env.list()#-# Django-allauth-# Dj-rest-auth+# Django-allauth social providers#-WGER_SETTINGS['USE_SOCIAL_AUTH'] = env.bool('USE_SOCIAL_AUTH', False)+WGER_SOCIAL_PROVIDERS = env.list('WGER_SOCIAL_PROVIDERS', default=[])+if WGER_SOCIAL_PROVIDERS:+ INSTALLED_APPS += [+ 'allauth.socialaccount',+ *[f'allauth.socialaccount.providers.{p}' for p in WGER_SOCIAL_PROVIDERS],+ ]+## Django Rest Framework SimpleJWT#diff --git a/settings/settings_global.py b/settings/settings_global.pyindex 62828331c..5bdce9f1b 100644--- a/settings/settings_global.py+++ b/settings/settings_global.py@@ -293,6 +293,7 @@ SOCIALACCOUNT_LOGIN_ON_GET = True#LOGIN_URL = '/user/login'LOGIN_REDIRECT_URL = '/'+ACCOUNT_LOGOUT_REDIRECT_URL = LOGIN_URL## Internationalization@@ -504,11 +505,6 @@ SIMPLE_JWT = {'UPDATE_LAST_LOGIN': False,}-#-# Dj-rest-auth-#-REST_USE_JWT = True-## CORS headers: allow all hosts to access the API#@@ -563,37 +559,24 @@ WGER_SETTINGS = {'EXPORT_INGREDIENTS_BULK_CELERY': False,'CACHE_API_EXERCISES_CELERY': False,'CACHE_API_EXERCISES_CELERY_FORCE_UPDATE': False,++ # Socials'TWITTER': False,'MASTODON': 'https://fosstodon.org/@wger','USE_CELERY': False,'USE_RECAPTCHA': False,'WGER_INSTANCE': 'https://wger.de',+# Trophy system settings'TROPHIES_ENABLED': True,'TROPHIES_INACTIVE_USER_DAYS': 30, # Days of inactivity before skipping trophy evaluation- # Social authentication/Oauth- 'USE_GOOGLE_AUTH': True, # GOOGLE}-WGER_SETTINGS['USE_SOCIAL_AUTH'] = (- WGER_SETTINGS.get('USE_GOOGLE_AUTH', False)- or WGER_SETTINGS.get('USE_GITHUB_AUTH', False)- or WGER_SETTINGS.get('USE_FACEBOOK_AUTH', False)-)--#-# Django-allauth-# Dj-rest-auth#-if WGER_SETTINGS.get('USE_SOCIAL_AUTH', False):- _social_apps = [-- 'allauth.socialaccount',- 'allauth.socialaccount.providers.google',-- ]+# Social authentication / OAuth+# List of allauth provider IDs to load, e.g. ['google', 'github', 'gitlab'].+WGER_SOCIAL_PROVIDERS = []- INSTALLED_APPS += _social_apps## Auth Proxy Authenticationdiff --git a/wger/core/api/views.py b/wger/core/api/views.pyindex 504b19a67..0fc15a509 100644--- a/wger/core/api/views.py+++ b/wger/core/api/views.py@@ -21,7 +21,6 @@ import logging# Djangofrom django.conf import settingsfrom django.contrib.auth.models import User-from django.contrib.sites.models import Sitefrom django.http import (HttpResponseForbidden,JsonResponse,diff --git a/wger/core/management/commands/setup_social_oauth.py b/wger/core/management/commands/setup_social_oauth.pydeleted file mode 100644index fec6d377d..000000000--- a/wger/core/management/commands/setup_social_oauth.py+++ /dev/null@@ -1,140 +0,0 @@-# This file is part of wger Workout Manager <https://github.com/wger-project>.-# Copyright (C) 2013 - 2026 wger Team-#-# wger Workout Manager is free software: you can redistribute it and/or modify-# it under the terms of the GNU Affero General Public License as published by-# the Free Software Foundation, either version 3 of the License, or-# (at your option) any later version.-#-# wger Workout Manager is distributed in the hope that it will be useful,-# but WITHOUT ANY WARRANTY; without even the implied warranty of-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the-# GNU Affero General Public License for more details.-#-# You should have received a copy of the GNU Affero General Public License-# along with this program. If not, see <http://www.gnu.org/licenses/>.--# Standard Library-import os--# Django-from django.conf import settings-from django.contrib.sites.models import Site-from django.core.management.base import (- BaseCommand,- CommandError,-)---if settings.WGER_SETTINGS.get('USE_SOCIAL_AUTH', False):- # Third Party- from allauth.socialaccount.models import SocialApp---SUPPORTED_PROVIDERS = ('google', 'github', 'facebook')--ENV_KEY_MAP = {- 'google': ('GOOGLE_CLIENT_ID', 'GOOGLE_CLIENT_SECRET'),-}--PROVIDER_DISPLAY_NAMES = {- 'google': 'Google Auth',- 'github': 'GitHub Auth',- 'facebook': 'Facebook Auth',-}---class Command(BaseCommand):- """- Management command to create or update a SocialApp (allauth) for a Google OAuth provider.-- This command seeds the single database record that allauth requires to perform- Google OAuth2 authentication. Run it once after initial deployment, or whenever- your Google OAuth credentials change.-- NOTE: To perform full CRUD management of SocialApp records (listing all apps, deleting- a provider, or editing individual fields), use the Django admin interface. Enable the admin- in settings_global.py and add '/admin' to urls.py.-- Usage:- python3 manage.py setup_social_oauth \\- --provider "google" \\- --client_id "YOUR_GOOGLE_CLIENT_ID" \\- --client_secret "YOUR_GOOGLE_CLIENT_SECRET" \\- --domain localhost:8000-- Google Cloud Console setup:- 1. Go to APIs & Services → Credentials → Create OAuth 2.0 Client ID- 2. Application type: Web application- 3. Authorized redirect URI: http://YOUR_DOMAIN/accounts/google/login/callback/- 4. Copy the client ID and secret, then run this command.- """-- help = 'Creates or updates allauth SocialApp credentials for Google'-- def add_arguments(self, parser):- parser.add_argument(- '--provider',- type=str,- required=True,- choices=SUPPORTED_PROVIDERS,- help='OAuth provider name: google',- )- parser.add_argument('--client_id', type=str, help='Oauth App Client ID')- parser.add_argument('--client_secret', type=str, help='Oauth App Client Secret')- parser.add_argument(- '--domain',- type=str,- default='localhost:8000',- help='Site domain (default: localhost:8000)',- )-- def handle(self, *args, **options):- if not settings.WGER_SETTINGS.get('USE_SOCIAL_AUTH', False):- raise CommandError(- 'Google OAuth is not enabled. '- 'Set WGER_SETTINGS["USE_SOCIAL_AUTH"] = True '- 'in your settings file before running this command.'- )-- provider = options['provider']- env_id_key, env_secret_key = ENV_KEY_MAP[provider]-- client_id = options['client_id'] or os.environ.get(env_id_key)- client_secret = options['client_secret'] or os.environ.get(env_secret_key)-- if not client_id or not client_secret:- self.stderr.write(- f'Error: Missing credentials for {provider}. '- f'Pass --client_id / --client_secret or set '- f'{env_id_key} / {env_secret_key} env variables.'- )- return-- domain = options['domain']-- app, created = SocialApp.objects.get_or_create(- provider=provider,- defaults={- 'name': PROVIDER_DISPLAY_NAMES[provider],- 'client_id': client_id,- 'secret': client_secret,- },- )- if not created:- # Update existing record- app.client_id = client_id- app.secret = client_secret- app.save()-- # Link the Site to the Social App-- site, _ = Site.objects.get_or_create(id=1, defaults={'domain': domain, 'name': domain})- app.sites.add(site)-- status = 'Created' if created else 'Updated'- self.stdout.write(- self.style.SUCCESS(- f'{status} {PROVIDER_DISPLAY_NAMES[provider]} OAuth App for {site.domain}'- )- )diff --git a/wger/core/signals.py b/wger/core/signals.pyindex 22fc56cf7..1e2ff31d1 100644--- a/wger/core/signals.py+++ b/wger/core/signals.py@@ -19,6 +19,7 @@ import datetime# Djangofrom django.contrib.auth.models import User+from django.contrib.auth.signals import user_logged_outfrom django.db.models.signals import (post_save,pre_save,@@ -67,3 +68,20 @@ def set_user_age(sender, instance, **kwargs):post_save.connect(create_user_profile, sender=User)post_save.connect(create_user_cache, sender=User)+++@receiver(user_logged_out)+def delete_temporary_user_on_logout(sender, request, user, **kwargs):+ """+ Temporary (guest) users are deleted when they log out.+ """+ if user is None or not user.is_authenticated:+ return+ try:+ is_temporary = user.userprofile.is_temporary+ except UserProfile.DoesNotExist:+ # User was already deleted (e.g. via the account-deletion flow,+ # which deletes the user before django_logout runs).+ return+ if is_temporary:+ user.delete()diff --git a/wger/core/templates/navigation.html b/wger/core/templates/navigation.htmlindex 5a84d7c09..0c0fd30f2 100644--- a/wger/core/templates/navigation.html+++ b/wger/core/templates/navigation.html@@ -292,11 +292,13 @@{% if user.userprofile.is_temporary %}<li class="dropdown-divider"></li><li>- <a class="dropdown-item"- href="{% url 'core:user:logout' %}">- <span class="{% fa_class 'sign-out-alt' %}"></span>- {% translate "Logout" %}- </a>+ <form method="post" action="{% url 'account_logout' %}">+ {% csrf_token %}+ <button type="submit" class="dropdown-item">+ <span class="{% fa_class 'sign-out-alt' %}"></span>+ {% translate "Logout" %}+ </button>+ </form></li>{% endif %}</ul>@@ -320,11 +322,13 @@{% if not trainer_identity %}<li class="dropdown-divider"></li><li>- <a class="dropdown-item"- href="{% url 'core:user:logout' %}">- <span class="{% fa_class 'sign-out-alt' %}"></span>- {% translate "Logout" %}- </a>+ <form method="post" action="{% url 'account_logout' %}">+ {% csrf_token %}+ <button type="submit" class="dropdown-item">+ <span class="{% fa_class 'sign-out-alt' %}"></span>+ {% translate "Logout" %}+ </button>+ </form></li>{% endif %}diff --git a/wger/core/templates/user/social_login.html b/wger/core/templates/user/social_login.htmlindex 023209e57..233459a15 100644--- a/wger/core/templates/user/social_login.html+++ b/wger/core/templates/user/social_login.html@@ -1,14 +1,19 @@{% load i18n socialaccount %}+{% get_providers as socialaccount_providers %}+{% if socialaccount_providers %}<div class="row mt-3"><div class="col-md-12 text-center">- <hr>- <h4>{% translate "Or login with" %}</h4>+ <h4>— {% translate "or login with" %} —</h4>- {% if use_social_auth %}- <a href="{% provider_login_url 'google' %}" class="btn btn-outline-danger me-2 mb-2">- <i class="fab fa-google me-1"></i> {% translate "Google" %}- </a>- {% endif %}+ {% for provider in socialaccount_providers %}+ <form method="post" action="{% provider_login_url provider %}" class="d-inline">+ {% csrf_token %}+ <button type="submit" class="btn btn-outline-primary me-2 mb-2">+ {{ provider.name }}+ </button>+ </form>+ {% endfor %}</div>-</div>\ No newline at end of file+</div>+{% endif %}diff --git a/wger/core/tests/test_auth_social.py b/wger/core/tests/test_auth_social.pynew file mode 100644index 000000000..e59b15055--- /dev/null+++ b/wger/core/tests/test_auth_social.py@@ -0,0 +1,97 @@+# This file is part of wger Workout Manager.+#+# This program is free software: you can redistribute it and/or modify+# it under the terms of the GNU Affero General Public License as published by+# the Free Software Foundation, either version 3 of the License, or+# (at your option) any later version.+#+# This program is distributed in the hope that it will be useful,+# but WITHOUT ANY WARRANTY; without even the implied warranty of+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+# GNU Affero General Public License for more details.+#+# You should have received a copy of the GNU Affero General Public License+# along with this program. If not, see <http://www.gnu.org/licenses/>.++# Standard Library+from unittest import mock++# Django+from django.conf import settings+from django.test import (+ RequestFactory,+ SimpleTestCase,+ override_settings,+)+from django.urls import reverse++# wger+from wger.core.tests.base_testcase import WgerTestCase+from wger.core.views.user import WgerLoginView+++class _StubProvider:+ """+ Mocks an allauth ``Provider`` instance+ """++ id = 'wger'+ name = 'Wger Test Provider'+ uses_apps = False++ def get_login_url(self, request, **kwargs):+ return '/accounts/wger-social/login/'+++@override_settings(+ INSTALLED_APPS=[*settings.INSTALLED_APPS, 'allauth.socialaccount'],+ WGER_SOCIAL_PROVIDERS=['wger'],+)+class SocialAuthEnabledLoginPageTestCase(WgerTestCase):+ """When social auth is enabled, the login page renders the provider section."""++ @mock.patch(+ 'allauth.socialaccount.adapter.DefaultSocialAccountAdapter.list_providers',+ return_value=[_StubProvider()],+ )+ def test_login_page_shows_social_section(self, _):+ response = self.client.get(reverse('core:user:login'))+ self.assertEqual(response.status_code, 200)+ self.assertTrue(response.context['use_social_auth'])+ self.assertContains(response, 'or login with')+ self.assertContains(response, 'Wger Test Provider')+ # The button must POST (CSRF-safe), not GET.+ self.assertContains(+ response,+ '<form method="post" action="/accounts/wger-social/login/"',+ )++ @mock.patch(+ 'allauth.socialaccount.adapter.DefaultSocialAccountAdapter.list_providers',+ return_value=[],+ )+ def test_no_section_without_configured_providers(self, _):+ """If no SocialApp rows exist, ``get_providers`` is empty and the section is hidden."""+ response = self.client.get(reverse('core:user:login'))+ self.assertEqual(response.status_code, 200)+ self.assertNotContains(response, 'or login with')+++class WgerLoginViewContextTestCase(SimpleTestCase):+ """Unit tests for ``WgerLoginView.get_context_data``."""++ def _build_view(self):+ view = WgerLoginView()+ view.request = RequestFactory().get(reverse('core:user:login'))+ view.setup(view.request)+ return view++ @override_settings(WGER_SOCIAL_PROVIDERS=[])+ def test_use_social_auth_false_when_no_providers(self):+ ctx = self._build_view().get_context_data()+ self.assertFalse(ctx['use_social_auth'])++ @override_settings(WGER_SOCIAL_PROVIDERS=['google'])+ def test_use_social_auth_true_when_providers_configured(self):+ ctx = self._build_view().get_context_data()+ self.assertTrue(ctx['use_social_auth'])diff --git a/wger/core/tests/test_temporary_users.py b/wger/core/tests/test_temporary_users.pyindex 82d61ac4f..594c169e0 100644--- a/wger/core/tests/test_temporary_users.py+++ b/wger/core/tests/test_temporary_users.py@@ -195,3 +195,29 @@ class DemoUserTestCase(WgerTestCase):self.assertEqual(self.count_temp_users(), 18)call_command('delete-temp-users')self.assertEqual(self.count_temp_users(), 2)++ def test_temporary_user_deleted_on_logout(self):+ """+ Logging out a temporary user must delete the account+ """+ before = self.count_temp_users()+ temp_user = create_temporary_user(HttpRequest())+ self.assertEqual(self.count_temp_users(), before + 1)++ self.client.force_login(temp_user)+ self.client.post(reverse('account_logout'))++ self.assertFalse(User.objects.filter(pk=temp_user.pk).exists())+ self.assertEqual(self.count_temp_users(), before)++ def test_regular_user_kept_on_logout(self):+ """+ Logging out a regular (non-temporary) user must not delete the account.+ """+ regular = User.objects.get(username='admin')+ self.assertFalse(regular.userprofile.is_temporary)++ self.client.force_login(regular)+ self.client.post(reverse('account_logout'))++ self.assertTrue(User.objects.filter(pk=regular.pk).exists())diff --git a/wger/core/views/user.py b/wger/core/views/user.pyindex 40923d9a4..e8c715a0a 100644--- a/wger/core/views/user.py+++ b/wger/core/views/user.py@@ -660,3 +660,8 @@ class WgerLoginView(AllauthLoginView):request, *args, **kwargs)return super().dispatch(request, *args, **kwargs)++ def get_context_data(self, **kwargs):+ context = super().get_context_data(**kwargs)+ context['use_social_auth'] = bool(settings.WGER_SOCIAL_PROVIDERS)+ return contextdiff --git a/wger/i18n.tpl b/wger/i18n.tplindex 2ec985d70..371c6e2ed 100644--- a/wger/i18n.tpl+++ b/wger/i18n.tpl@@ -81,4 +81,3 @@{% translate "Work out on January 1st" %}{% translate "Return to training after being inactive for 30 days" %}{% translate "Achieve a new Personal Record on any exercise" %}-{% translate "Google" %}diff --git a/wger/urls.py b/wger/urls.pyindex b52b360c4..98bd80fe3 100644--- a/wger/urls.py+++ b/wger/urls.py@@ -1,18 +1,19 @@-# This file is part of wger Workout Manager <https://github.com/wger-project>.-# Copyright (C) 2013 - 2026 wger Team+# -*- coding: utf-8 -*-++# This file is part of wger Workout Manager.#-# wger Workout Manager is free software: you can redistribute it and/or modify-# it under the terms of the GNU Affero General Public License as published by-# the Free Software Foundation, either version 3 of the License, or-# (at your option) any later version.+# wger Workout Manager is free software: you can redistribute it and/or modify+# it under the terms of the GNU Affero General Public License as published by+# the Free Software Foundation, either version 3 of the License, or+# (at your option) any later version.#-# wger Workout Manager is distributed in the hope that it will be useful,-# but WITHOUT ANY WARRANTY; without even the implied warranty of-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the-# GNU Affero General Public License for more details.+# wger Workout Manager is distributed in the hope that it will be useful,+# but WITHOUT ANY WARRANTY; without even the implied warranty of+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+# GNU General Public License for more details.#-# You should have received a copy of the GNU Affero General Public License-# along with this program. If not, see <http://www.gnu.org/licenses/>.+# You should have received a copy of the GNU Affero General Public License+# along with Workout Manager. If not, see <http://www.gnu.org/licenses/>.# Djangofrom django.conf import settings@@ -374,14 +375,9 @@ urlpatterns += [),]-if settings.WGER_SETTINGS.get('USE_SOCIAL_AUTH', False):- urlpatterns += [- path('accounts/', include('allauth.urls')),- ]-else:- urlpatterns += [- path('accounts/', include('allauth.account.urls')),- ]+urlpatterns += [+ path('accounts/', include('allauth.urls')),+]## URL for user uploaded files, served like this during development onlydiff --git a/wger/utils/context_processor.py b/wger/utils/context_processor.pyindex 9a1a011cd..550fb5426 100644--- a/wger/utils/context_processor.py+++ b/wger/utils/context_processor.py@@ -1,18 +1,17 @@-# This file is part of wger Workout Manager <https://github.com/wger-project>.-# Copyright (C) 2013 - 2026 wger Team+# This file is part of wger Workout Manager.#-# wger Workout Manager is free software: you can redistribute it and/or modify-# it under the terms of the GNU Affero General Public License as published by-# the Free Software Foundation, either version 3 of the License, or-# (at your option) any later version.+# wger Workout Manager is free software: you can redistribute it and/or modify+# it under the terms of the GNU Affero General Public License as published by+# the Free Software Foundation, either version 3 of the License, or+# (at your option) any later version.#-# wger Workout Manager is distributed in the hope that it will be useful,-# but WITHOUT ANY WARRANTY; without even the implied warranty of-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the-# GNU Affero General Public License for more details.+# wger Workout Manager is distributed in the hope that it will be useful,+# but WITHOUT ANY WARRANTY; without even the implied warranty of+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+# GNU General Public License for more details.#-# You should have received a copy of the GNU Affero General Public License-# along with this program. If not, see <http://www.gnu.org/licenses/>.+# You should have received a copy of the GNU Affero General Public License+# along with Workout Manager. If not, see <http://www.gnu.org/licenses/>.# Djangofrom django.conf import settings@@ -35,7 +34,6 @@ def processor(request):context = {'mastodon': settings.WGER_SETTINGS.get('MASTODON', ''),'allow_registration': settings.WGER_SETTINGS.get('ALLOW_REGISTRATION', False),- 'use_social_auth': settings.WGER_SETTINGS.get('USE_SOCIAL_AUTH', False),# Languages'i18n_language': get_language_data(