-
Notifications
You must be signed in to change notification settings - Fork 8
Third-party authentication #1220
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
imperosol
wants to merge
14
commits into
taiste
Choose a base branch
from
discord-auth
base: taiste
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
f1e60f2
feat: api route to get api client infos
imperosol 058b928
move `ResultConverter` to core app
imperosol 50d5615
add `hmac_key` to `ApiClient`
imperosol 76ceccb
`hmac_hexdigest` util function
imperosol 6e9ade9
test populate_more command
imperosol e2f1aae
add CGU/EULA to populate command
imperosol d2ae90b
third-party authentication views
imperosol f781c00
write tests
imperosol 3fc95e8
translation: third-party authentication
imperosol 99ed3f4
doc: third-party auth
imperosol 18b2c93
tweak documentation
imperosol 7c66fff
apply review comments
imperosol 1640742
fix: don't send callback request if data has been modified
imperosol 9f26157
apply docs review comments
imperosol File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,16 @@ | ||
| from ninja_extra import ControllerBase, api_controller, route | ||
|
|
||
| from api.auth import ApiKeyAuth | ||
| from api.schemas import ApiClientSchema | ||
|
|
||
|
|
||
| @api_controller("/client") | ||
| class ApiClientController(ControllerBase): | ||
| @route.get( | ||
| "/me", | ||
| auth=[ApiKeyAuth()], | ||
| response=ApiClientSchema, | ||
| url_name="api-client-infos", | ||
| ) | ||
| def get_client_info(self): | ||
| return self.context.request.auth |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,35 @@ | ||
| from django import forms | ||
| from django.forms import HiddenInput | ||
| from django.utils.translation import gettext_lazy as _ | ||
|
|
||
|
|
||
| class ThirdPartyAuthForm(forms.Form): | ||
| """Form to complete to authenticate on the sith from a third-party app. | ||
|
|
||
| For the form to be valid, the user approve the EULA (french: CGU) | ||
| and give its username from the third-party app. | ||
| """ | ||
|
|
||
| cgu_accepted = forms.BooleanField( | ||
| required=True, | ||
| label=_("I have read and I accept the terms and conditions of use"), | ||
| error_messages={ | ||
| "required": _("You must approve the terms and conditions of use.") | ||
| }, | ||
| ) | ||
| is_username_valid = forms.BooleanField( | ||
| required=True, | ||
| error_messages={"required": _("You must confirm that this is your username.")}, | ||
| ) | ||
| client_id = forms.IntegerField(widget=HiddenInput()) | ||
| third_party_app = forms.CharField(widget=HiddenInput()) | ||
| privacy_link = forms.URLField(widget=HiddenInput()) | ||
| username = forms.CharField(widget=HiddenInput()) | ||
| callback_url = forms.URLField(widget=HiddenInput()) | ||
| signature = forms.CharField(widget=HiddenInput()) | ||
|
|
||
| def __init__(self, *args, label_suffix: str = "", initial, **kwargs): | ||
| super().__init__(*args, label_suffix=label_suffix, initial=initial, **kwargs) | ||
| self.fields["is_username_valid"].label = _( | ||
| "I confirm that %(username)s is my username on %(app)s" | ||
| ) % {"username": initial.get("username"), "app": initial.get("third_party_app")} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,19 @@ | ||
| # Generated by Django 5.2.3 on 2025-10-26 10:15 | ||
|
|
||
| from django.db import migrations, models | ||
|
|
||
| import api.models | ||
|
|
||
|
|
||
| class Migration(migrations.Migration): | ||
| dependencies = [("api", "0001_initial")] | ||
|
|
||
| operations = [ | ||
| migrations.AddField( | ||
| model_name="apiclient", | ||
| name="hmac_key", | ||
| field=models.CharField( | ||
| default=api.models.get_hmac_key, max_length=128, verbose_name="HMAC Key" | ||
| ), | ||
| ), | ||
| ] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,23 @@ | ||
| from ninja import ModelSchema, Schema | ||
| from pydantic import Field, HttpUrl | ||
|
|
||
| from api.models import ApiClient | ||
| from core.schemas import SimpleUserSchema | ||
|
|
||
|
|
||
| class ApiClientSchema(ModelSchema): | ||
| class Meta: | ||
| model = ApiClient | ||
| fields = ["id", "name"] | ||
|
|
||
| owner: SimpleUserSchema | ||
| permissions: list[str] = Field(alias="all_permissions") | ||
|
|
||
|
|
||
| class ThirdPartyAuthParamsSchema(Schema): | ||
| client_id: int | ||
| third_party_app: str | ||
| privacy_link: HttpUrl | ||
| username: str | ||
| callback_url: HttpUrl | ||
| signature: str |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,32 @@ | ||
| {% extends "core/base.jinja" %} | ||
|
|
||
| {% block content %} | ||
| <form method="post"> | ||
| {% csrf_token %} | ||
| <h3>{% trans %}Confidentiality{% endtrans %}</h3> | ||
| <p> | ||
| {% trans trimmed app=third_party_app %} | ||
| By ticking this box and clicking on the send button, you | ||
| acknowledge and agree to provide {{ app }} with your | ||
| first name, last name, nickname and any other information | ||
| that was the third party app was explicitly authorized to fetch | ||
| and that it must have acknowledged to you, in a complete and accurate manner. | ||
| {% endtrans %} | ||
| </p> | ||
| <p class="margin-bottom"> | ||
| {% trans trimmed app=third_party_app, privacy_link=third_party_cgu, sith_cgu_link=sith_cgu %} | ||
| The privacy policies of <a href="{{ privacy_link }}">{{ app }}</a> | ||
| and of <a href="{{ sith_cgu_link }}">the Students' Association</a> | ||
| applies as soon as the form is submitted. | ||
| {% endtrans %} | ||
| </p> | ||
| <div class="row">{{ form.cgu_accepted }} {{ form.cgu_accepted.label_tag() }}</div> | ||
| <br> | ||
| <h3 class="margin-bottom">{% trans %}Confirmation of identity{% endtrans %}</h3> | ||
| <div class="row margin-bottom"> | ||
| {{ form.is_username_valid }} {{ form.is_username_valid.label_tag() }} | ||
| </div> | ||
| {% for field in form.hidden_fields() %}{{ field }}{% endfor %} | ||
| <input type="submit" class="btn btn-blue"> | ||
| </form> | ||
| {% endblock %} | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,24 @@ | ||
| import pytest | ||
| from django.contrib.admin import AdminSite | ||
| from django.http import HttpRequest | ||
| from model_bakery import baker | ||
| from pytest_django.asserts import assertNumQueries | ||
|
|
||
| from api.admin import ApiClientAdmin | ||
| from api.models import ApiClient | ||
|
|
||
|
|
||
| @pytest.mark.django_db | ||
| def test_reset_hmac_action(): | ||
| client_admin = ApiClientAdmin(ApiClient, AdminSite()) | ||
| api_clients = baker.make(ApiClient, _quantity=4, _bulk_create=True) | ||
| old_hmac_keys = [c.hmac_key for c in api_clients] | ||
| with assertNumQueries(2): | ||
| qs = ApiClient.objects.filter(id__in=[c.id for c in api_clients[2:4]]) | ||
| client_admin.reset_hmac_key(HttpRequest(), qs) | ||
| for c in api_clients: | ||
| c.refresh_from_db() | ||
| assert api_clients[0].hmac_key == old_hmac_keys[0] | ||
| assert api_clients[1].hmac_key == old_hmac_keys[1] | ||
| assert api_clients[2].hmac_key != old_hmac_keys[2] | ||
| assert api_clients[3].hmac_key != old_hmac_keys[3] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,18 @@ | ||
| import pytest | ||
| from django.test import Client | ||
| from django.urls import reverse | ||
| from model_bakery import baker | ||
|
|
||
| from api.hashers import generate_key | ||
| from api.models import ApiClient, ApiKey | ||
| from api.schemas import ApiClientSchema | ||
|
|
||
|
|
||
| @pytest.mark.django_db | ||
| def test_api_client_controller(client: Client): | ||
| key, hashed = generate_key() | ||
| api_client = baker.make(ApiClient) | ||
| baker.make(ApiKey, client=api_client, hashed_key=hashed) | ||
| res = client.get(reverse("api:api-client-infos"), headers={"X-APIKey": key}) | ||
| assert res.status_code == 200 | ||
| assert res.json() == ApiClientSchema.from_orm(api_client).model_dump() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,59 @@ | ||
| import pytest | ||
| from django.contrib.auth.models import Permission | ||
| from django.test import TestCase | ||
| from model_bakery import baker | ||
|
|
||
| from api.models import ApiClient | ||
| from core.models import Group | ||
|
|
||
|
|
||
| class TestClientPermissions(TestCase): | ||
| @classmethod | ||
| def setUpTestData(cls): | ||
| cls.api_client = baker.make(ApiClient) | ||
| cls.perms = baker.make(Permission, _quantity=10, _bulk_create=True) | ||
| cls.api_client.groups.set( | ||
| [ | ||
| baker.make(Group, permissions=cls.perms[0:3]), | ||
| baker.make(Group, permissions=cls.perms[3:5]), | ||
| ] | ||
| ) | ||
| cls.api_client.client_permissions.set( | ||
| [cls.perms[3], cls.perms[5], cls.perms[6], cls.perms[7]] | ||
| ) | ||
|
|
||
| def test_all_permissions(self): | ||
| assert self.api_client.all_permissions == { | ||
| f"{p.content_type.app_label}.{p.codename}" for p in self.perms[0:8] | ||
| } | ||
|
|
||
| def test_has_perm(self): | ||
| assert self.api_client.has_perm( | ||
| f"{self.perms[1].content_type.app_label}.{self.perms[1].codename}" | ||
| ) | ||
| assert not self.api_client.has_perm( | ||
| f"{self.perms[9].content_type.app_label}.{self.perms[9].codename}" | ||
| ) | ||
|
|
||
| def test_has_perms(self): | ||
| assert self.api_client.has_perms( | ||
| [ | ||
| f"{self.perms[1].content_type.app_label}.{self.perms[1].codename}", | ||
| f"{self.perms[2].content_type.app_label}.{self.perms[2].codename}", | ||
| ] | ||
| ) | ||
| assert not self.api_client.has_perms( | ||
| [ | ||
| f"{self.perms[1].content_type.app_label}.{self.perms[1].codename}", | ||
| f"{self.perms[9].content_type.app_label}.{self.perms[9].codename}", | ||
| ], | ||
| ) | ||
|
|
||
|
|
||
| @pytest.mark.django_db | ||
| def test_reset_hmac_key(): | ||
| client = baker.make(ApiClient) | ||
| original_key = client.hmac_key | ||
| client.reset_hmac(commit=True) | ||
| assert len(client.hmac_key) == len(original_key) | ||
| assert client.hmac_key != original_key |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.