Skip to content

armgit / wger

Public Imported from GitHub
0

Self hosted FLOSS fitness/workout, nutrition and weight tracker

Allow users to disconnect oicd applications

Roland Geider1aa54c8e60ce
diff --git a/wger/core/templates/user/connected_applications.html b/wger/core/templates/user/connected_applications.html
new file mode 100644
index 000000000..1fe152b6b
--- /dev/null
+++ b/wger/core/templates/user/connected_applications.html
@@ -0,0 +1,91 @@
+{% extends "base.html" %}
+{% load i18n wger_extras %}
+
+{% block title %}{% translate "Connected applications" %}{% endblock %}
+
+
+{% block content %}
+ <p>
+ {% blocktranslate trimmed %}
+ These applications can use your account through the API. You gave them
+ permission when you logged in with your wger account.
+ {% endblocktranslate %}
+ </p>
+
+ {% if applications %}
+ {% for application in applications %}
+ <div class="card mb-3">
+ <div class="card-body">
+ <div class="d-flex justify-content-between align-items-start gap-3">
+ <div>
+ <h5 class="card-title mb-1">{{ application.name }}</h5>
+ {% if application.expires_at %}
+ <p class="card-text mb-2">
+ <small class="text-muted">
+ {% blocktranslate trimmed with date=application.expires_at|date:"SHORT_DATE_FORMAT" %}
+ Access runs out on {{ date }} if the application is not used again
+ {% endblocktranslate %}
+ </small>
+ </p>
+ {% endif %}
+ <ul class="list-unstyled mb-0">
+ {% for permission in application.permissions %}
+ <li>
+ <span class="{% fa_class 'check' %} me-1 text-muted"></span>
+ {{ permission }}
+ </li>
+ {% endfor %}
+ </ul>
+ </div>
+ <button
+ type="button"
+ class="btn btn-sm btn-outline-danger flex-shrink-0"
+ hx-post="{% url 'core:user:connected-applications' %}"
+ hx-vals='{"disconnect": "{{ application.client_id }}"}'
+ hx-headers='{"X-CSRFToken": "{{ csrf_token }}"}'
+ hx-target="body"
+ hx-push-url="true"
+ >
+ {% translate "Disconnect" %}
+ </button>
+ </div>
+ </div>
+ </div>
+ {% endfor %}
+
+ <p>
+ {% blocktranslate trimmed %}
+ Disconnecting takes the access away immediately. The application can
+ ask for it again, and you will be shown the same page you saw the
+ first time.
+ {% endblocktranslate %}
+ </p>
+ {% else %}
+ <div class="card bg-light mb-4">
+ <div class="card-body">
+ <em>{% translate "No application has access to your account." %}</em>
+ </div>
+ </div>
+ {% endif %}
+{% endblock %}
+
+
+{# #}
+{# Sidebar #}
+{# #}
+{% block sidebar %}
+
+ <h5 class="mt-4">{% translate "Your account" %}</h5>
+
+ <p>
+ {% blocktranslate trimmed %}
+ This list is about other applications using your wger account. To manage
+ the accounts you use to log in to wger, see connected accounts in your
+ settings.
+ {% endblocktranslate %}
+ </p>
+
+ <p>
+ <a href="{% url 'core:user:preferences' %}">{% translate 'Settings' %}</a>
+ </p>
+{% endblock %}
diff --git a/wger/core/templates/user/preferences.html b/wger/core/templates/user/preferences.html
index 3ba944de4..5ccef0380 100644
--- a/wger/core/templates/user/preferences.html
+++ b/wger/core/templates/user/preferences.html
@@ -65,6 +65,14 @@
<span class="{% fa_class 'globe' %} me-2 text-muted"></span>
{% translate "API key" %}
</a>
+ {% if oidc_provider_configured %}
+ <a href="{% url 'core:user:connected-applications' %}"
+ class="list-group-item list-group-item-action">
+ <span class="{% fa_class 'chevron-right' %} float-end text-muted"></span>
+ <span class="{% fa_class 'plug' %} me-2 text-muted"></span>
+ {% translate "Connected applications" %}
+ </a>
+ {% endif %}
</div>
</div>
diff --git a/wger/core/tests/test_oidc_provider.py b/wger/core/tests/test_oidc_provider.py
index 8c69eb79e..636b93d46 100644
--- a/wger/core/tests/test_oidc_provider.py
+++ b/wger/core/tests/test_oidc_provider.py
@@ -60,6 +60,7 @@ from cryptography.hazmat.primitives.asymmetric import rsa
# wger
from wger.core.tasks import flush_expired_oidc_tokens_task
from wger.core.tests.base_testcase import WgerTestCase
+from wger.core.views.oidc import connected_applications
from wger.utils.oidc_auth import (
SCOPE_READ,
SCOPE_WRITE,
@@ -106,9 +107,9 @@ class GenerateOidcKeyTestCase(SimpleTestCase):
self.assertEqual(key.key_size, 1024)
-class OidcProviderTestCase(WgerTestCase):
+class OidcTestCase(WgerTestCase):
"""
- End-to-end test for the OAuth2/OIDC provider (allauth.idp.oidc)
+ A configured provider and one client to run flows against
"""
@classmethod
@@ -129,6 +130,35 @@ class OidcProviderTestCase(WgerTestCase):
self.oidc_client.set_response_types([Client.ResponseType.CODE])
self.oidc_client.save()
+ def create_access_token(
+ self,
+ scopes: list[str],
+ token_type: str = Token.Type.ACCESS_TOKEN,
+ expires_in: timedelta = timedelta(hours=1),
+ username: str = 'test',
+ client: Client | None = None,
+ ) -> str:
+ """
+ Mints a token directly, without running the whole flow
+ """
+ value = secrets.token_urlsafe(32)
+ token = Token(
+ type=token_type,
+ user=User.objects.get(username=username),
+ client=client or self.oidc_client,
+ hash=get_adapter().hash_token(value),
+ expires_at=timezone.now() + expires_in,
+ )
+ token.set_scopes(scopes)
+ token.save()
+ return value
+
+
+class OidcProviderTestCase(OidcTestCase):
+ """
+ End-to-end test for the OAuth2/OIDC provider (allauth.idp.oidc)
+ """
+
def request_authorization(self, challenge: str, scope: str = f'openid profile {SCOPE_READ}'):
"""
Opens the consent screen, returns its response
@@ -502,27 +532,6 @@ class OidcProviderTestCase(WgerTestCase):
self.assertEqual(self.read_profile(access_token).status_code, 403)
- def create_access_token(
- self,
- scopes: list[str],
- token_type: str = Token.Type.ACCESS_TOKEN,
- expires_in: timedelta = timedelta(hours=1),
- ) -> str:
- """
- Mints a token directly, without running the whole flow
- """
- value = secrets.token_urlsafe(32)
- token = Token(
- type=token_type,
- user=User.objects.get(username='test'),
- client=self.oidc_client,
- hash=get_adapter().hash_token(value),
- expires_at=timezone.now() + expires_in,
- )
- token.set_scopes(scopes)
- token.save()
- return value
-
def read_profile(self, token: str):
return self.client.get(
reverse('userprofile'),
@@ -721,3 +730,203 @@ class OidcProviderTestCase(WgerTestCase):
self.assertEqual(response.status_code, 302)
self.assertTrue(response['location'].startswith(f'{settings.LOGIN_URL}?next='))
+
+
+class ConnectedApplicationsTestCase(OidcTestCase):
+ """
+ The page listing the applications a user has given access to, and the
+ button that takes it back
+ """
+
+ def setUp(self):
+ super().setUp()
+ self.url = reverse('core:user:connected-applications')
+ self.user_login('test')
+
+ def read_scopes(self, name: str) -> str:
+ """
+ The permission wording the consent screen shows for a scope
+ """
+ return str(get_adapter().scope_display[name])
+
+ def test_a_granted_application_is_listed(self):
+ self.create_access_token([SCOPE_READ])
+
+ response = self.client.get(self.url)
+
+ self.assertEqual(response.status_code, 200)
+ self.assertContains(response, 'Test client')
+
+ def test_permissions_are_worded_as_on_the_consent_screen(self):
+ """
+ The page someone checks later must not describe the access differently
+ from the page they agreed to
+ """
+ self.create_access_token([SCOPE_READ])
+
+ response = self.client.get(self.url)
+
+ self.assertContains(response, self.read_scopes(SCOPE_READ))
+ self.assertNotContains(response, self.read_scopes(SCOPE_WRITE))
+
+ def test_the_scopes_of_all_live_tokens_are_shown(self):
+ """
+ An access token can be minted for a subset of what was granted, so what
+ the application can do is the union over its tokens
+ """
+ self.create_access_token([SCOPE_READ])
+ self.create_access_token([SCOPE_READ, SCOPE_WRITE], token_type=Token.Type.REFRESH_TOKEN)
+
+ response = self.client.get(self.url)
+
+ self.assertContains(response, self.read_scopes(SCOPE_READ), count=1)
+ self.assertContains(response, self.read_scopes(SCOPE_WRITE), count=1)
+
+ def test_the_expiry_shown_is_that_of_the_longest_lived_token(self):
+ """
+ What the user wants to know is when the connection lapses if nobody
+ touches it, which is the refresh token, not the hourly access token
+ """
+ self.create_access_token([SCOPE_READ])
+ self.create_access_token(
+ [SCOPE_READ],
+ token_type=Token.Type.REFRESH_TOKEN,
+ expires_in=timedelta(days=120),
+ )
+
+ applications = connected_applications(User.objects.get(username='test'))
+
+ self.assertEqual(len(applications), 1)
+ self.assertGreater(applications[0].expires_at, timezone.now() + timedelta(days=119))
+
+ def test_applications_are_listed_by_name(self):
+ """
+ Not by when they were connected: rotation resets that, so the order
+ would reshuffle itself while the user is reading the page
+ """
+ later = Client(type=Client.Type.PUBLIC, name='Aardvark')
+ later.set_scopes([SCOPE_READ])
+ later.save()
+ self.create_access_token([SCOPE_READ])
+ self.create_access_token([SCOPE_READ], client=later)
+
+ applications = connected_applications(User.objects.get(username='test'))
+
+ self.assertEqual([a.name for a in applications], ['Aardvark', 'Test client'])
+
+ def test_one_entry_per_application_not_per_token(self):
+ self.create_access_token([SCOPE_READ])
+ self.create_access_token([SCOPE_READ])
+ self.create_access_token([SCOPE_READ], token_type=Token.Type.REFRESH_TOKEN)
+
+ response = self.client.get(self.url)
+
+ self.assertContains(response, 'Test client', count=1)
+
+ def test_expired_tokens_are_not_a_connection(self):
+ """
+ Housekeeping only runs daily, so the page has to filter them itself
+ """
+ self.create_access_token([SCOPE_READ], expires_in=-timedelta(seconds=1))
+
+ response = self.client.get(self.url)
+
+ self.assertNotContains(response, 'Test client')
+ self.assertContains(response, 'No application has access')
+
+ def test_an_authorization_code_is_not_a_connection(self):
+ """
+ A code is a step in the flow: it may never be redeemed, and until it is
+ the application has nothing
+ """
+ self.create_access_token([SCOPE_READ], token_type=Token.Type.AUTHORIZATION_CODE)
+
+ response = self.client.get(self.url)
+
+ self.assertNotContains(response, 'Test client')
+
+ def test_only_the_callers_own_connections_are_listed(self):
+ self.create_access_token([SCOPE_READ], username='admin')
+
+ response = self.client.get(self.url)
+
+ self.assertNotContains(response, 'Test client')
+
+ def test_disconnecting_deletes_every_token_of_that_application(self):
+ self.create_access_token([SCOPE_READ])
+ self.create_access_token([SCOPE_READ], token_type=Token.Type.REFRESH_TOKEN)
+ # A code that is still redeemable would hand back a fresh token right
+ # after the user thought they had ended the connection
+ self.create_access_token([SCOPE_READ], token_type=Token.Type.AUTHORIZATION_CODE)
+
+ response = self.client.post(self.url, {'disconnect': self.oidc_client.id}, follow=True)
+
+ self.assertContains(response, 'no longer has access')
+ self.assertFalse(Token.objects.filter(client=self.oidc_client).exists())
+
+ def test_disconnecting_leaves_the_other_applications_alone(self):
+ other = Client(type=Client.Type.PUBLIC, name='Other client')
+ other.set_scopes([SCOPE_READ])
+ other.save()
+ self.create_access_token([SCOPE_READ])
+ self.create_access_token([SCOPE_READ], client=other)
+
+ response = self.client.post(self.url, {'disconnect': self.oidc_client.id}, follow=True)
+
+ # Not assertNotContains: the success message names the application that
+ # was just disconnected, so the page mentions it either way
+ self.assertContains(response, 'Other client')
+ self.assertFalse(Token.objects.filter(client=self.oidc_client).exists())
+ self.assertTrue(Token.objects.filter(client=other).exists())
+
+ def test_disconnecting_cannot_reach_another_users_tokens(self):
+ """
+ The client is shared, the grants are not
+ """
+ self.create_access_token([SCOPE_READ], username='admin')
+
+ self.client.post(self.url, {'disconnect': self.oidc_client.id})
+
+ self.assertTrue(Token.objects.filter(user__username='admin').exists())
+
+ def test_disconnecting_something_that_is_not_connected_says_nothing(self):
+ """
+ No message either way: there is nothing to report, and confirming that
+ an unknown client id exists would be an answer in itself
+ """
+ response = self.client.post(self.url, {'disconnect': 'no-such-client'}, follow=True)
+
+ self.assertEqual(response.status_code, 200)
+ self.assertNotContains(response, 'no longer has access')
+
+ def test_nothing_connected(self):
+ response = self.client.get(self.url)
+
+ self.assertContains(response, 'No application has access')
+
+ @override_settings(IDP_OIDC_PRIVATE_KEY='')
+ def test_page_is_gone_while_the_provider_is_off(self):
+ """
+ Same answer as the authorization view: without a signing key nothing
+ can be connected, and the tokens that exist are already refused
+ """
+ self.assertEqual(self.client.get(self.url).status_code, 404)
+
+ def test_the_settings_page_links_here(self):
+ response = self.client.get(reverse('core:user:preferences'))
+
+ self.assertContains(response, self.url)
+
+ @override_settings(IDP_OIDC_PRIVATE_KEY='')
+ def test_the_settings_page_hides_the_link_while_the_provider_is_off(self):
+ response = self.client.get(reverse('core:user:preferences'))
+
+ self.assertNotContains(response, self.url)
+
+ def test_anonymous_users_are_sent_to_the_login(self):
+ self.user_logout()
+
+ response = self.client.get(self.url)
+
+ self.assertEqual(response.status_code, 302)
+ self.assertIn(settings.LOGIN_URL, response['location'])
diff --git a/wger/core/urls.py b/wger/core/urls.py
index d6ccbc250..dcf93008a 100644
--- a/wger/core/urls.py
+++ b/wger/core/urls.py
@@ -28,6 +28,7 @@ from wger.core.views import (
languages,
license,
misc,
+ oidc,
repetition_units,
user,
weight_units,
@@ -75,6 +76,11 @@ patterns_user = [
path('registration', user.WgerSignupView.as_view(), name='registration'),
path('preferences', user.preferences, name='preferences'),
path('api-key', user.api_key, name='api-key'),
+ path(
+ 'connected-applications',
+ oidc.overview,
+ name='connected-applications',
+ ),
path('app-auth/', user.app_auth_handoff, name='app-auth-handoff'),
path('demo-entries', misc.demo_entries, name='demo-entries'),
path('<int:pk>/activate', user.UserActivateView.as_view(), name='activate'),
diff --git a/wger/core/views/oidc.py b/wger/core/views/oidc.py
new file mode 100644
index 000000000..519cc2b02
--- /dev/null
+++ b/wger/core/views/oidc.py
@@ -0,0 +1,135 @@
+# -*- 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 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 Workout Manager. If not, see <http://www.gnu.org/licenses/>.
+
+# Standard Library
+import datetime
+from dataclasses import dataclass
+
+# Django
+from django.contrib import messages
+from django.contrib.auth.decorators import login_required
+from django.http import (
+ Http404,
+ HttpResponseRedirect,
+)
+from django.shortcuts import render
+from django.template.context_processors import csrf
+from django.urls import reverse
+from django.utils.translation import gettext as _
+
+# Third Party
+from allauth.idp.oidc.adapter import get_adapter
+from allauth.idp.oidc.models import Token
+
+# wger
+from wger.utils.oidc_auth import is_provider_configured
+
+
+# What counts as a live connection. An authorization code is a step in the flow,
+# not a grant.
+GRANT_TOKEN_TYPES = (Token.Type.ACCESS_TOKEN, Token.Type.REFRESH_TOKEN)
+
+
+@dataclass
+class ConnectedApplication:
+ """One application a user has granted access to, as the page shows it.
+
+ No "connected since": rotation deletes the old refresh token and writes a
+ new one, so ``created_at`` is the last refresh, not the consent.
+ """
+
+ client_id: str
+ name: str
+ permissions: list[str]
+ #: When the longest-lived token runs out, if nothing refreshes it.
+ expires_at: datetime.datetime | None
+
+
+def scope_labels(scopes: list[str]) -> list[str]:
+ """
+ The wording the consent screen used, so the two pages cannot drift apart
+ """
+ display = get_adapter().scope_display
+ return [str(display.get(scope, scope)) for scope in scopes]
+
+
+def connected_applications(user) -> list[ConnectedApplication]:
+ """
+ The applications ``user`` has granted access to, one entry per client
+
+ Expired tokens are left out: housekeeping only deletes them once a day.
+ """
+ tokens = (
+ Token.objects.valid()
+ .filter(user=user, type__in=GRANT_TOKEN_TYPES, client__isnull=False)
+ .select_related('client')
+ )
+
+ by_client: dict[str, list[Token]] = {}
+ for token in tokens:
+ by_client.setdefault(token.client_id, []).append(token)
+
+ applications = []
+ for client_tokens in by_client.values():
+ # An access token can be minted for a subset of what was granted, so
+ # what the application can do is the union over its tokens.
+ scopes: list[str] = []
+ for token in client_tokens:
+ scopes.extend(s for s in token.get_scopes() if s not in scopes)
+
+ expiries = [token.expires_at for token in client_tokens]
+ applications.append(
+ ConnectedApplication(
+ client_id=client_tokens[0].client_id,
+ name=client_tokens[0].client.name,
+ permissions=scope_labels(scopes),
+ # A token without an expiry outlives every other one.
+ expires_at=None if None in expiries else max(expiries),
+ )
+ )
+
+ return sorted(applications, key=lambda a: a.name.lower())
+
+
+@login_required
+def overview(request):
+ """
+ Applications the user has given access to their account, and a way to take
+ it back
+ """
+ if not is_provider_configured():
+ raise Http404('The OAuth2 provider is not configured')
+
+ context = {}
+ context.update(csrf(request))
+
+ client_id = request.POST.get('disconnect') if request.method == 'POST' else None
+ if client_id:
+ # Scoped to the user, so another user's client id matches nothing
+ tokens = Token.objects.filter(user=request.user, client_id=client_id)
+ token = tokens.select_related('client').first()
+ if token is not None:
+ name = token.client.name
+ # Every type, not just GRANT_TOKEN_TYPES: a pending authorization
+ # code would still be exchangeable for a fresh token.
+ tokens.delete()
+ messages.success(request, _('{name} no longer has access').format(name=name))
+ return HttpResponseRedirect(reverse('core:user:connected-applications'))
+
+ context['applications'] = connected_applications(request.user)
+
+ return render(request, 'user/connected_applications.html', context)
diff --git a/wger/core/views/user.py b/wger/core/views/user.py
index 9001f3141..c8eb466e7 100644
--- a/wger/core/views/user.py
+++ b/wger/core/views/user.py
@@ -119,6 +119,7 @@ from wger.utils.headless_long_lived import (
revoke_all_long_lived_sessions,
revoke_long_lived_session,
)
+from wger.utils.oidc_auth import is_provider_configured
logger = logging.getLogger(__name__)
@@ -324,6 +325,7 @@ def preferences(request):
context['email_verified'] = request.user.userprofile.is_verified
context['mfa_enabled'] = is_mfa_enabled(request.user)
context['has_usable_password'] = request.user.has_usable_password()
+ context['oidc_provider_configured'] = is_provider_configured()
return render(request, 'user/preferences.html', context)