Self hosted FLOSS fitness/workout, nutrition and weight tracker
feat(auth): add Google, GitHub and Facebook OAuth support
pankaj-basnet777c3b928df2
diff --git a/settings/ci.py b/settings/ci.pyindex 5c83210ed..8231437de 100644--- a/settings/ci.py+++ b/settings/ci.py@@ -50,6 +50,8 @@ WGER_SETTINGS['ALLOW_UPLOAD_VIDEOS'] = FalseWGER_SETTINGS['MIN_ACCOUNT_AGE_TO_TRUST'] = 21 # in daysWGER_SETTINGS['EXERCISE_CACHE_TTL'] = 3600 # in secondsWGER_SETTINGS['USE_SOCIAL_AUTH'] = False+WGER_SETTINGS['USE_GITHUB_AUTH'] = False+WGER_SETTINGS['USE_FACEBOOK_AUTH'] = FalseDATABASES = {'default': {diff --git a/settings/local_dev.py b/settings/local_dev.pyindex 998a3d4ca..d2845409c 100644--- a/settings/local_dev.py+++ b/settings/local_dev.py@@ -38,6 +38,9 @@ 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_SOCIAL_AUTH'] = True+WGER_SETTINGS['USE_GITHUB_AUTH'] = True+WGER_SETTINGS['USE_FACEBOOK_AUTH'] = TrueDEFAULT_FROM_EMAIL = WGER_SETTINGS['EMAIL_FROM']diff --git a/settings/main.py b/settings/main.pyindex 0007da87d..c9c791d86 100644--- a/settings/main.py+++ b/settings/main.py@@ -264,7 +264,8 @@ AXES_IPWARE_META_PRECEDENCE_ORDER = env.list(# Dj-rest-auth#WGER_SETTINGS['USE_SOCIAL_AUTH'] = env.bool('USE_SOCIAL_AUTH', False)-+WGER_SETTINGS['USE_GITHUB_AUTH'] = env.bool('USE_GITHUB_AUTH', False)+WGER_SETTINGS['USE_FACEBOOK_AUTH'] = env.bool('USE_FACEBOOK_AUTH', False)## Django Rest Framework SimpleJWT#diff --git a/settings/settings_global.py b/settings/settings_global.pyindex 62a91ed0e..259c5ea50 100644--- a/settings/settings_global.py+++ b/settings/settings_global.py@@ -282,7 +282,23 @@ SOCIALACCOUNT_PROVIDERS = {'access_type': 'online',},'OAUTH_PKCE_ENABLED': True,- }+ },+ 'github': {+ 'SCOPE': ['user:email'],+ 'APP': {+ 'client_id': '',+ 'secret': '',+ 'key': '',+ },+ },+ 'facebook': {+ 'METHOD': 'oauth2',+ 'SCOPE': ['email', 'public_profile'],+ 'FIELDS': ['id', 'email', 'name', 'first_name', 'last_name'],+ 'EXCHANGE_TOKEN': True,+ 'LOCALE_FUNC': lambda request: 'en_US',+ 'VERSION': 'v18.0',+ },}ACCOUNT_LOGOUT_ON_GET = True@@ -572,7 +588,9 @@ WGER_SETTINGS = {'TROPHIES_ENABLED': True,'TROPHIES_INACTIVE_USER_DAYS': 30, # Days of inactivity before skipping trophy evaluation# Social authentication/Oauth- 'USE_SOCIAL_AUTH': False,+ 'USE_SOCIAL_AUTH': True, # GOOGLE+ 'USE_GITHUB_AUTH': True,+ 'USE_FACEBOOK_AUTH': False,}#@@ -580,7 +598,7 @@ WGER_SETTINGS = {# Dj-rest-auth#if WGER_SETTINGS.get('USE_SOCIAL_AUTH', False):- INSTALLED_APPS += [+ _social_apps = ['allauth.socialaccount','allauth.socialaccount.providers.google',@@ -590,6 +608,14 @@ if WGER_SETTINGS.get('USE_SOCIAL_AUTH', False):]+ if WGER_SETTINGS.get('USE_GITHUB_AUTH', False):+ _social_apps.append('allauth.socialaccount.providers.github')++ if WGER_SETTINGS.get('USE_FACEBOOK_AUTH', False):+ _social_apps.append('allauth.socialaccount.providers.facebook')++ INSTALLED_APPS += _social_apps+## Auth Proxy Authentication#diff --git a/wger/core/api/views.py b/wger/core/api/views.pyindex f05d10c1e..116790fd3 100644--- a/wger/core/api/views.py+++ b/wger/core/api/views.py@@ -59,10 +59,18 @@ from rest_framework.response import Responseif settings.WGER_SETTINGS.get('USE_SOCIAL_AUTH'):+ # Third Partyfrom allauth.socialaccount.providers.google.views import GoogleOAuth2Adapterfrom allauth.socialaccount.providers.oauth2.client import OAuth2Clientfrom dj_rest_auth.registration.views import SocialLoginView+ if settings.WGER_SETTINGS.get('USE_GITHUB_AUTH'):+ # Third Party+ from allauth.socialaccount.providers.github.views import GitHubOAuth2Adapter++ if settings.WGER_SETTINGS.get('USE_FACEBOOK_AUTH'):+ from allauth.socialaccount.providers.facebook.views import FacebookOAuth2Adapter+# wger# The per-app powersync modules are imported for their side effect: each one# registers its handlers with wger.utils.powersync.REGISTRY at import time.@@ -379,11 +387,12 @@ class UserAPIRegistrationViewSet(viewsets.ViewSet):)-if settings.WGER_SETTINGS.get('USE_SOCIAL_AUTH'):+if settings.WGER_SETTINGS.get('USE_SOCIAL_AUTH', False):class GoogleLogin(SocialLoginView):"""REST endpoint to exchange a Google Access Token for a wger API JWT.+ Flutter sends the Google accessToken here."""adapter_class = GoogleOAuth2Adapter@@ -392,8 +401,36 @@ if settings.WGER_SETTINGS.get('USE_SOCIAL_AUTH'):@propertydef callback_url():base_url = Site.objects.get_current()- base_url_domain = base_url.domain- return f'http://${base_url_domain}/accounts/google/login/callback/'+ return f'http://${base_url.domain}/accounts/google/login/callback/'++ if settings.WGER_SETTINGS.get('USE_GITHUB_AUTH', False):+ """+ REST endpoint to exchange a GitHub OAuth2 Access Token for a wger API JWT.+ Flutter sends the GitHub accessToken here."""++ class GithubLogin(SocialLoginView):+ adapter_class = GitHubOAuth2Adapter+ client_class = OAuth2Client++ @property+ def callback_url(self):+ base_url = Site.objects.get_current()+ return f'http://{base_url.domain}/accounts/github/login/callback/'++ if settings.WGER_SETTINGS.get('USE_FACEBOOK_AUTH'):++ class FacebookLogin(SocialLoginView):+ """+ REST endpoint to exchange a Facebook Access Token for a wger API JWT.+ Flutter sends the Facebook accessToken here."""++ adaptor_class = FacebookOAuth2Adapter+ client_class = OAuth2Client++ @property+ def callback(self):+ base_url = Site.objects.get_current()+ return f'{base_url.domain}/accounts/facebook/login/callback'class LanguageViewSet(viewsets.ReadOnlyModelViewSet):diff --git a/wger/core/management/commands/setup_google_oauth.py b/wger/core/management/commands/setup_google_oauth.pydeleted file mode 100644index d26777182..000000000--- a/wger/core/management/commands/setup_google_oauth.py+++ /dev/null@@ -1,74 +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,-)--# Third Party-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):- if not settings.WGER_SETTINGS.get('USE_SOCIAL_AUTH'):- raise CommandError(- 'Google OAuth is not enabled. '- 'Set WGER_SETTINGS["USE_SOCIAL_AUTH"] = True '- 'in your settings file before running this command.'- )-- site, created = Site.objects.get_or_create(- id=1, defaults={'domain': 'localhost:8000', 'name': 'localhost'}- )-- # 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-- 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}')- )diff --git a/wger/core/management/commands/setup_social_oauth.py b/wger/core/management/commands/setup_social_oauth.pynew file mode 100644index 000000000..c2e7305e1--- /dev/null+++ b/wger/core/management/commands/setup_social_oauth.py@@ -0,0 +1,127 @@+# 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,+)++# Third Party+from allauth.socialaccount.models import SocialApp+++SUPPORTED_PROVIDERS = ('google', 'github', 'facebook')++ENV_KEY_MAP = {+ 'google': ('GOOGLE_CLIENT_ID', 'GOOGLE_CLIENT_SECRET'),+ 'github': ('GITHUB_CLIENT_ID', 'GITHUB_CLIENT_SECRET'),+ 'facebook': ('FACEBOOK_CLIENT_ID', 'FACEBOOK_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 given provider.++ Usage:+ python manage.py setup_social_oauth --provider google \+ --client_id YOUR_ID --client_secret YOUR_SECRET++ python manage.py setup_social_oauth --provider github \+ --client_id YOUR_ID --client_secret YOUR_SECRET++ python manage.py setup_social_oauth --provider facebook \+ --client_id YOUR_ID --client_secret YOUR_SECRET+ """++ help = 'Creates or updates allauth SocialApp credentials for Google, GitHub, or Facebook.'++ def add_arguments(self, parser):+ parser.add_argument(+ '--provider',+ type=str,+ required=True,+ choices=SUPPORTED_PROVIDERS,+ help='OAuth provider name: google | github | facebook',+ )+ 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']++ # Link the Site to the Social App++ site, _ = Site.objects.get_or_create(+ id=1,+ defaults={'domain': domain, 'name': domain},+ )++ app, created = SocialApp.objects.update_or_create(+ provider=provider,+ defaults={+ 'name': PROVIDER_DISPLAY_NAMES[provider],+ 'client_id': client_id,+ 'secret': client_secret,+ },+ )+ 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/templates/user/social_login.html b/wger/core/templates/user/social_login.htmlindex 12b5d563a..0411e9708 100644--- a/wger/core/templates/user/social_login.html+++ b/wger/core/templates/user/social_login.html@@ -1,11 +1,26 @@{% load i18n socialaccount %}-<div class="row">+<div class="row mt-3"><div class="col-md-12 text-center"><hr>- <h4>{% translate "Login with Google" %}</h4>- <a href="{% provider_login_url 'google' %}" class="btn btn-primary">- <i class="fab fa-google"></i> {% translate "Login" %}+ <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 %}++ {% if use_github_auth %}+ <a href="{% provider_login_url 'github' %}" class="btn btn-outline-dark me-2 mb-2">+ <i class="fab fa-github me-1"></i> {% translate "GitHub" %}+ </a>+ {% endif %}++ {% if use_facebook_auth %}+ <a href="{% provider_login_url 'facebook' %}" class="btn btn-outline-primary me-2 mb-2">+ <i class="fab fa-facebook me-1"></i> {% translate "Facebook" %}</a>+ {% endif %}</div></div>\ No newline at end of filediff --git a/wger/i18n.tpl b/wger/i18n.tplindex 371c6e2ed..07d4a6d77 100644--- a/wger/i18n.tpl+++ b/wger/i18n.tpl@@ -81,3 +81,6 @@{% 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" %}+{% translate "Github" %}+{% translate "Facebook" %}diff --git a/wger/urls.py b/wger/urls.pyindex 779817854..7b0d74bdd 100644--- a/wger/urls.py+++ b/wger/urls.py@@ -382,6 +382,24 @@ if settings.WGER_SETTINGS.get('USE_SOCIAL_AUTH', False):path('auth/google/', core_api_views.GoogleLogin.as_view(), name='google_rest_login'),]+ if settings.WGER_SETTINGS.get('USE_GITHUB_AUTH', False):+ urlpatterns += [+ path(+ 'auth/github/',+ core_api_views.GithubLogin.as_view(),+ name='github_rest_login',+ ),+ ]++ # Facebook REST endpoint — only added when Facebook auth is enabled+ if settings.WGER_SETTINGS.get('USE_FACEBOOK_AUTH', False):+ urlpatterns += [+ path(+ 'auth/facebook/',+ core_api_views.FacebookLogin.as_view(),+ name='facebook_rest_login',+ ),+ ]## 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..d24282d8b 100644--- a/wger/utils/context_processor.py+++ b/wger/utils/context_processor.py@@ -35,7 +35,10 @@ 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),+ # 'use_social_auth': settings.WGER_SETTINGS.get('USE_SOCIAL_AUTH', False),+ 'use_social_auth': True,+ 'use_github_auth': settings.WGER_SETTINGS.get('USE_GITHUB_AUTH', False),+ 'use_facebook_auth': settings.WGER_SETTINGS.get('USE_FACEBOOK_AUTH', False),# Languages'i18n_language': get_language_data(