Skip to content

armgit / wger

Public Imported from GitHub
0

Self hosted FLOSS fitness/workout, nutrition and weight tracker

Feat: Implement Google OAuth using django-allauth for user authentication

pankaj-basnet73fc3c6bc662
diff --git a/settings/settings_global.py b/settings/settings_global.py
index 3f49c51a5..1e207d7a6 100644
--- a/settings/settings_global.py
+++ b/settings/settings_global.py
@@ -125,6 +125,8 @@ INSTALLED_APPS = [
'allauth',
'allauth.account',
'allauth.mfa',
+ 'allauth.socialaccount',
+ 'allauth.socialaccount.providers.google',
]
MIDDLEWARE = [
@@ -263,6 +265,25 @@ MFA_TOTP_ISSUER = 'wger'
MFA_PASSKEY_LOGIN_ENABLED = True
MFA_PASSKEY_SIGNUP_ENABLED = False
+#
+# Social account providers
+#
+SOCIALACCOUNT_PROVIDERS = {
+ 'google': {
+ 'SCOPE': [
+ 'profile',
+ 'email',
+ ],
+ 'AUTH_PARAMS': {
+ 'access_type': 'online',
+ },
+ 'OAUTH_PKCE_ENABLED': True,
+ }
+}
+
+ACCOUNT_LOGOUT_ON_GET = True
+SOCIALACCOUNT_LOGIN_ON_GET = True
+
#
# Login
#
diff --git a/wger/core/management/commands/setup_google_oauth.py b/wger/core/management/commands/setup_google_oauth.py
new file mode 100644
index 000000000..bcafaa9a0
--- /dev/null
+++ b/wger/core/management/commands/setup_google_oauth.py
@@ -0,0 +1,43 @@
+import os
+from django.core.management.base import BaseCommand
+from django.contrib.sites.models import Site
+from allauth.socialaccount.models import SocialApp
+
+class Command(BaseCommand):
+ help = 'Automates the creation of Google OAuth SocialApp credentials'
+
+ def add_arguments(self, parser):
+ parser.add_argument('--client_id', type=str, help='Google Client ID')
+ parser.add_argument('--client_secret', type=str, help='Google Client Secret')
+
+ def handle(self, *args, **options):
+ # 1. Get or Create the Site (usually ID 1 for localhost)
+ site, created = Site.objects.get_or_create(
+ id=1,
+ defaults={'domain': 'localhost:8000', 'name': 'localhost'}
+ )
+
+ # 2. Get credentials from arguments or environment variables
+ client_id = options['client_id'] or os.environ.get('GOOGLE_CLIENT_ID')
+ client_secret = options['client_secret'] or os.environ.get('GOOGLE_CLIENT_SECRET')
+
+ if not client_id or not client_secret:
+ self.stderr.write("Error: Missing Client ID or Secret. Provide via args or Env Vars.")
+ return
+
+ # 3. Create or Update the Social App
+ app, created = SocialApp.objects.update_or_create(
+ provider='google',
+ defaults={
+ 'name': 'Google Auth',
+ 'client_id': client_id,
+ 'secret': client_secret,
+ }
+ )
+
+ # 4. Link the Site to the Social App
+ app.sites.add(site)
+
+ status = "Created" if created else "Updated"
+ self.stdout.write(self.style.SUCCESS(f'Successfully {status} Google OAuth App for {site.domain}'))
+
\ No newline at end of file
diff --git a/wger/core/tests/test_verification.py b/wger/core/tests/test_verification.py
index 1d7c13c0d..7e5a5bd57 100644
--- a/wger/core/tests/test_verification.py
+++ b/wger/core/tests/test_verification.py
@@ -37,6 +37,87 @@ from wger.core.tests.base_testcase import WgerTestCase
logger = logging.getLogger(__name__)
+@override_settings(EMAIL_BACKEND='django.core.mail.backends.locmem.EmailBackend')
+class EmailVerificationFromPreferencesTestCase(WgerTestCase):
+ """
+ Tests that clicking the verification link in the preferences sidebar
+ sends a verification email via allauth.
+ """
+
+ def test_confirm_email_sends_mail_for_unverified_user(self):
+ """
+ An unverified user clicking confirm-email receives a verification email
+ """
+
+ # User 1 (admin) has verified=False in the fixtures
+ self.user_login('admin')
+
+ mail.outbox = []
+ response = self.client.get(reverse('core:user:confirm-email'))
+
+ # Redirects to dashboard
+ self.assertEqual(response.status_code, 302)
+ self.assertIn(reverse('core:dashboard'), response.url)
+
+ # A verification email was sent
+ self.assertEqual(len(mail.outbox), 1)
+ self.assertIn('[email protected]', mail.outbox[0].to)
+
+ def test_confirm_email_link_verifies_email(self):
+ """
+ Following the confirmation link from the email marks the address as verified
+ """
+
+ # User 1 (admin) has verified=False in the fixtures
+ self.user_login('admin')
+
+ mail.outbox = []
+ self.client.get(reverse('core:user:confirm-email'))
+ self.assertEqual(len(mail.outbox), 1)
+
+ # Extract the confirmation key from the email body
+ email_body = mail.outbox[0].body
+ match = re.search(r'/accounts/confirm-email/([^/\s]+)/', email_body)
+ self.assertIsNotNone(match, 'Could not find confirmation link in email body')
+ key = match.group(1)
+
+ # Visit the confirmation URL (GET shows the page, POST confirms)
+ confirm_url = reverse('account_confirm_email', args=[key])
+ self.client.get(confirm_url)
+
+ # The email should now be verified
+ user = User.objects.get(username='admin')
+ email_obj = EmailAddress.objects.get_for_user(user, user.email)
+ self.assertTrue(email_obj.verified)
+
+ def test_confirm_email_no_mail_for_verified_user(self):
+ """
+ A verified user clicking confirm-email does not receive a new email
+ """
+
+ # User 4 (trainer1) has verified=True in the fixtures
+ self.user_login('trainer1')
+
+ mail.outbox = []
+ response = self.client.get(reverse('core:user:confirm-email'))
+
+ # Redirects to dashboard
+ self.assertEqual(response.status_code, 302)
+
+ # No email was sent
+ self.assertEqual(len(mail.outbox), 0)
+
+ def test_confirm_email_requires_login(self):
+ """
+ Anonymous users are redirected to the login page
+ """
+
+ self.user_logout()
+ response = self.client.get(reverse('core:user:confirm-email'))
+ self.assertEqual(response.status_code, 302)
+ self.assertIn('/login', response.url)
+
+
@override_settings(EMAIL_BACKEND='django.core.mail.backends.locmem.EmailBackend')
class EmailVerificationFromAPITestCase(WgerTestCase):
"""
@@ -79,7 +160,7 @@ class EmailVerificationFromAPITestCase(WgerTestCase):
# Extract the confirmation key from the email body
email_body = mail.outbox[0].body
- match = re.search(r'/account/confirm-email/([^/\s]+)/', email_body)
+ match = re.search(r'/accounts/confirm-email/([^/\s]+)/', email_body)
self.assertIsNotNone(match, 'Could not find confirmation link in email body')
key = match.group(1)
diff --git a/wger/urls.py b/wger/urls.py
index 0bedb3ae2..6ab8dc046 100644
--- a/wger/urls.py
+++ b/wger/urls.py
@@ -373,6 +373,7 @@ urlpatterns += [
SpectacularRedocView.as_view(url_name='schema'),
name='api-redoc',
),
+ path('accounts/', include('allauth.urls')),
]
#