Skip to content
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

fix: do never link users with organisation identities #1196

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion api/mysagw/oidc_auth/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from django.conf import settings
from django.db import IntegrityError, transaction
from django.db.models import Q
from rest_framework.exceptions import ValidationError

from mysagw.identity.models import Identity

Expand Down Expand Up @@ -87,8 +88,13 @@ def _update_or_create_identity(self):
settings.OIDC_MONITORING_CLIENT_USERNAME,
]:
return None
if Identity.objects.filter(
is_organisation=True, email__iexact=self.email
).exists():
msg = "Can't create Identity, because there is already an organisation with this email address."
raise ValidationError(msg)
try:
identity = Identity.objects.get(
identity = Identity.objects.filter(is_organisation=False).get(
Q(idp_id=self.id) | Q(email__iexact=self.email),
)
# we only want to save if necessary in order to prevent adding historical
Expand Down
41 changes: 41 additions & 0 deletions api/mysagw/oidc_auth/tests/test_authentication.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,12 @@

import pytest
from django.core.cache import cache
from django.urls import reverse
from mozilla_django_oidc.contrib.drf import OIDCAuthentication
from requests.exceptions import HTTPError
from rest_framework import exceptions, status
from rest_framework.exceptions import AuthenticationFailed
from rest_framework.test import APIClient
from simple_history.models import HistoricalRecords

from mysagw.identity.models import Identity
Expand Down Expand Up @@ -245,3 +247,42 @@ def test_authentication_idp_missing_claim(
request = rf.get("/openid", HTTP_AUTHORIZATION="Bearer Token")
with pytest.raises(AuthenticationFailed):
OIDCAuthentication().authenticate(request)


@pytest.mark.parametrize(
"identity__is_organisation,identity__organisation_name,identity__email",
[
(True, "org name", "[email protected]"),
],
)
def test_authentication_email_already_used(
db, rf, requests_mock, settings, get_claims, identity
):
idp_id = str(uuid4())
claims = get_claims(
id_claim=idp_id,
email_claim="[email protected]",
first_name_claim="Winston",
last_name_claim="Smith",
salutation_claim="neutral",
title_claim=None,
)
assert Identity.objects.count() == 1

requests_mock.get(settings.OIDC_OP_USER_ENDPOINT, text=json.dumps(claims))

url = reverse("me")

client = APIClient()
response = client.get(url, HTTP_AUTHORIZATION="Bearer Token")
assert response.status_code == status.HTTP_400_BAD_REQUEST
assert response.json() == {
"errors": [
{
"detail": "Can't create Identity, because there is already an organisation with this email address.",
"status": "400",
"source": {"pointer": "/data"},
"code": "invalid",
}
]
}
1 change: 1 addition & 0 deletions ember/app/router.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ const resetNamespace = true;
//eslint-disable-next-line array-callback-return
Router.map(function () {
this.route("login");
this.route("support");
this.route("notfound", { path: "/*path" });

this.route("protected", { path: "/" }, function () {
Expand Down
42 changes: 28 additions & 14 deletions ember/app/services/session.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import ENV from "mysagw/config/environment";

export default class CustomSession extends Session {
@service store;
@service router;

currentIdentity = trackedTask(this, this.fetchCurrentIdentity, () => [
this.isAuthenticated,
Expand All @@ -18,21 +19,34 @@ export default class CustomSession extends Session {

if (!this.isAuthenticated) return null;

const data = yield Promise.all([
this.store.query(
"membership",
{
include: "organisation",
},
{ adapterOptions: { customEndpoint: "my-memberships" } },
),
this.store.queryRecord("identity", {}),
]);
try {
const data = yield Promise.all([
this.store.query(
"membership",
{
include: "organisation",
},
{ adapterOptions: { customEndpoint: "my-memberships" } },
),
this.store.queryRecord("identity", {}),
]);

return {
memberships: data[0],
identity: data[1],
};
} catch (error) {
this.invalidate();

if (
error.errors[0].detail ===
"Can't create Identity, because there is already an organisation with this email address."
) {
return this.router.transitionTo("support");
}

return {
memberships: data[0],
identity: data[1],
};
return this.router.transitionTo("login");
}
}

get identity() {
Expand Down
3 changes: 3 additions & 0 deletions ember/app/ui/support/route.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import Route from "@ember/routing/route";

export default class SupportRoute extends Route {}
10 changes: 10 additions & 0 deletions ember/app/ui/support/template.hbs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<div class="uk-text-center">
<h1>{{t "support.title"}}</h1>
<h3>
{{t "support.subtitle"}}
<a href="mailto:[email protected]" target="_blank" rel="noopener noreferrer">
{{! template-lint-disable no-bare-strings }}
[email protected]
</a>
</h3>
</div>
3 changes: 3 additions & 0 deletions ember/translations/support/de.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
support:
title: "Ein Fehler ist aufgetreten."
subtitle: "Bitte wenden Sie sich an"
3 changes: 3 additions & 0 deletions ember/translations/support/en.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
support:
title: "An error has occurred."
subtitle: "Please contact"
3 changes: 3 additions & 0 deletions ember/translations/support/fr.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
support:
title: "Une erreur s'est produite."
subtitle: "Veuillez contacter"
Loading