Browse Source

Fix (#1374)

pull/1375/head
Sebastian Stehle 2 weeks ago
committed by GitHub
parent
commit
f8537bc067
No known key found for this signature in database GPG Key ID: B5690EEEBB952194
  1. 7
      backend/i18n/frontend_de.json
  2. 7
      backend/i18n/frontend_en.json
  3. 7
      backend/i18n/frontend_fr.json
  4. 7
      backend/i18n/frontend_it.json
  5. 7
      backend/i18n/frontend_nl.json
  6. 7
      backend/i18n/frontend_pt.json
  7. 7
      backend/i18n/frontend_zh.json
  8. 3
      backend/i18n/source/backend_de.json
  9. 3
      backend/i18n/source/backend_en.json
  10. 7
      backend/i18n/source/frontend_de.json
  11. 7
      backend/i18n/source/frontend_en.json
  12. 7
      backend/src/Squidex.Data.EntityFramework/Domain/Apps/Entities/Teams/EFTeamRepository.cs
  13. 7
      backend/src/Squidex.Data.MongoDb/Domain/Apps/Entities/Teams/MongoTeamRepository.cs
  14. 23
      backend/src/Squidex.Domain.Apps.Core.Model/Teams/Team.cs
  15. 1
      backend/src/Squidex.Domain.Apps.Entities/Squidex.Domain.Apps.Entities.csproj
  16. 23
      backend/src/Squidex.Domain.Apps.Entities/Teams/AuthDomainRecord.cs
  17. 12
      backend/src/Squidex.Domain.Apps.Entities/Teams/Commands/VerifyAuthDomain.cs
  18. 34
      backend/src/Squidex.Domain.Apps.Entities/Teams/DnsAuthDomainVerifier.cs
  19. 34
      backend/src/Squidex.Domain.Apps.Entities/Teams/DomainObject/Guards/GuardTeam.cs
  20. 4
      backend/src/Squidex.Domain.Apps.Entities/Teams/DomainObject/TeamDomainObject.State.cs
  21. 20
      backend/src/Squidex.Domain.Apps.Entities/Teams/DomainObject/TeamDomainObject.cs
  22. 16
      backend/src/Squidex.Domain.Apps.Entities/Teams/IAuthDomainVerifier.cs
  23. 2
      backend/src/Squidex.Domain.Apps.Entities/Teams/Indexes/TeamsIndex.cs
  24. 13
      backend/src/Squidex.Domain.Apps.Events/Teams/TeamAuthDomainVerified.cs
  25. 9
      backend/src/Squidex.Shared/Texts.de.resx
  26. 9
      backend/src/Squidex.Shared/Texts.fr.resx
  27. 9
      backend/src/Squidex.Shared/Texts.it.resx
  28. 9
      backend/src/Squidex.Shared/Texts.nl.resx
  29. 9
      backend/src/Squidex.Shared/Texts.pt.resx
  30. 9
      backend/src/Squidex.Shared/Texts.resx
  31. 9
      backend/src/Squidex.Shared/Texts.zh.resx
  32. 33
      backend/src/Squidex/Areas/Api/Controllers/Teams/Models/AuthSchemeResponseDto.cs
  33. 24
      backend/src/Squidex/Areas/Api/Controllers/Teams/TeamsController.cs
  34. 31
      backend/src/Squidex/Areas/IdentityServer/Config/Dynamic/DynamicSchemeProvider.cs
  35. 7
      backend/src/Squidex/Areas/IdentityServer/Controllers/Account/AccountController.cs
  36. 2
      backend/src/Squidex/Config/Authentication/GithubHandler.cs
  37. 17
      backend/src/Squidex/Config/Authentication/GoogleHandler.cs
  38. 35
      backend/src/Squidex/Config/Authentication/MicrosoftHandler.cs
  39. 46
      backend/src/Squidex/Config/Authentication/OidcHandler.cs
  40. 40
      backend/src/Squidex/Config/Authentication/VerifiedEmailExtensions.cs
  41. 4
      backend/src/Squidex/Config/Domain/CommandsServices.cs
  42. 2
      backend/src/Squidex/Config/MyIdentityOptions.cs
  43. 3
      backend/src/Squidex/appsettings.json
  44. 35
      backend/tests/Squidex.Data.Tests/Shared/TeamRepositoryTests.cs
  45. 1
      backend/tests/Squidex.Domain.Apps.Core.Tests/Model/Teams/Team.json
  46. 49
      backend/tests/Squidex.Domain.Apps.Core.Tests/Model/Teams/TeamTests.cs
  47. 55
      backend/tests/Squidex.Domain.Apps.Entities.Tests/Teams/DomainObject/Guards/GuardTeamTests.cs
  48. 35
      backend/tests/Squidex.Domain.Apps.Entities.Tests/Teams/DomainObject/TeamDomainObjectTests.cs
  49. 19
      backend/tests/Squidex.Domain.Apps.Entities.Tests/Teams/Indexes/TeamsIndexTests.cs
  50. 1
      backend/tests/Squidex.Domain.Apps.Entities.Tests/Verify/TeamDomainObjectTests.AssignContributor_should_create_events_and_add_contributor.verified.txt
  51. 1
      backend/tests/Squidex.Domain.Apps.Entities.Tests/Verify/TeamDomainObjectTests.ChangePlan_from_callback_should_create_events_and_update_plan.verified.txt
  52. 1
      backend/tests/Squidex.Domain.Apps.Entities.Tests/Verify/TeamDomainObjectTests.ChangePlan_from_callback_should_reset_plan_for_free_plan.verified.txt
  53. 1
      backend/tests/Squidex.Domain.Apps.Entities.Tests/Verify/TeamDomainObjectTests.ChangePlan_should_create_events_and_update_plan.verified.txt
  54. 1
      backend/tests/Squidex.Domain.Apps.Entities.Tests/Verify/TeamDomainObjectTests.ChangePlan_should_not_call_billing_manager_for_callback.verified.txt
  55. 1
      backend/tests/Squidex.Domain.Apps.Entities.Tests/Verify/TeamDomainObjectTests.ChangePlan_should_not_make_update_for_redirect_result.verified.txt
  56. 1
      backend/tests/Squidex.Domain.Apps.Entities.Tests/Verify/TeamDomainObjectTests.ChangePlan_should_reset_plan_for_free_plan.verified.txt
  57. 1
      backend/tests/Squidex.Domain.Apps.Entities.Tests/Verify/TeamDomainObjectTests.Create_should_create_events_and_set_intitial_state.verified.txt
  58. 1
      backend/tests/Squidex.Domain.Apps.Entities.Tests/Verify/TeamDomainObjectTests.Create_should_not_assign_client_as_contributor.verified.txt
  59. 1
      backend/tests/Squidex.Domain.Apps.Entities.Tests/Verify/TeamDomainObjectTests.DeleteTeam_should_create_events_and_update_deleted_flag.verified.txt
  60. 1
      backend/tests/Squidex.Domain.Apps.Entities.Tests/Verify/TeamDomainObjectTests.RemoveContributor_should_create_events_and_remove_contributor.verified.txt
  61. 1
      backend/tests/Squidex.Domain.Apps.Entities.Tests/Verify/TeamDomainObjectTests.Update_should_create_events_and_update_label_and_description.verified.txt
  62. 1
      backend/tests/Squidex.Domain.Apps.Entities.Tests/Verify/TeamDomainObjectTests.UpsertAuth_should_create_events_and_remove_scheme.verified.txt
  63. 1
      backend/tests/Squidex.Domain.Apps.Entities.Tests/Verify/TeamDomainObjectTests.UpsertAuth_should_create_events_and_update_scheme.verified.txt
  64. 41
      backend/tests/Squidex.Domain.Apps.Entities.Tests/Verify/TeamDomainObjectTests.VerifyAuthDomain_should_create_events_and_verify_domain.verified.txt
  65. 42
      frontend/src/app/features/teams/pages/auth/auth-page.component.html
  66. 6
      frontend/src/app/features/teams/pages/auth/auth-page.component.scss
  67. 18
      frontend/src/app/features/teams/pages/auth/auth-page.component.ts
  68. 33
      frontend/src/app/features/teams/state/team-auth.state.spec.ts
  69. 76
      frontend/src/app/features/teams/state/team-auth.state.ts
  70. 4
      frontend/src/app/shared/model/custom.ts
  71. 22
      frontend/src/app/shared/model/generated.ts
  72. 47
      frontend/src/app/shared/services/teams.service.spec.ts
  73. 12
      frontend/src/app/shared/services/teams.service.ts

7
backend/i18n/frontend_de.json

@ -1217,6 +1217,7 @@
"teams.auth.domain": "Domäne",
"teams.auth.domainHint": "Die Domäne wird verwendet, um Ihre Benutzer zu identifizieren. Wenn sie ihre E-Mail-Adresse eingeben und die Domäne mit Ihren Einstellungen übereinstimmt, werden sie zu Ihrem Authentifizierungsserver weitergeleitet.",
"teams.auth.domainHintEmail": "E-Mail-Format",
"teams.auth.notVerifiedHint": "Ihre Benutzer können sich erst mit diesem Server anmelden, nachdem Sie bestätigt haben, dass Ihnen die Domäne gehört. Fügen Sie den folgenden DNS-TXT-Eintrag zu Ihrer Domäne hinzu und klicken Sie auf Bestätigen.",
"teams.auth.redirectUrl": "Weiterleitungs-URL",
"teams.auth.redirectUrlHint": "Sie müssen diese URL in Ihrem Authentifizierungsserver zulassen.",
"teams.auth.reloaded": "Authentifizierungseinstellung neu geladen.",
@ -1224,6 +1225,12 @@
"teams.auth.testLogin": "Testanmeldung",
"teams.auth.use": "Benutzerdefinierter OIDC-Server",
"teams.auth.useHint": "Verwenden Sie eine Single-Sign-On (SSO)-Lösung, um Squidex mit Ihrer Infrastruktur zu verbinden. Ihre Mitarbeiter und Kollegen können sich mit ihrem normalen Geschäftskonto verbinden.",
"teams.auth.verificationRecordName": "Eintragsname",
"teams.auth.verificationRecordValue": "Eintragswert",
"teams.auth.verified": "Domäne bestätigt.",
"teams.auth.verifiedHint": "Die Inhaberschaft der Domäne wurde bestätigt.",
"teams.auth.verify": "Domäne bestätigen",
"teams.auth.verifyFailed": "Die Domäne konnte nicht bestätigt werden. Bitte neu laden.",
"teams.create": "Erstellen",
"teams.createFailed": "Fehler beim Erstellen des Teams. Bitte neu laden.",
"teams.delete": "Team löschen",

7
backend/i18n/frontend_en.json

@ -1217,6 +1217,7 @@
"teams.auth.domain": "Domain",
"teams.auth.domainHint": "The domain is used to identity your users. When they enter their email address and the domain matches to your settings they will redirected to your authentication server.",
"teams.auth.domainHintEmail": "Email Format",
"teams.auth.notVerifiedHint": "Your users can only sign in with this server after you have verified that you own the domain. Add the following DNS TXT record to your domain and click verify.",
"teams.auth.redirectUrl": "Redirect URL",
"teams.auth.redirectUrlHint": "You have to allow this URL in your authentication server.",
"teams.auth.reloaded": "Auth setting reloaded.",
@ -1224,6 +1225,12 @@
"teams.auth.testLogin": "Test Login",
"teams.auth.use": "Custom OIDC Server",
"teams.auth.useHint": "Use single-sign-on (SSO) solution to connect Squidex to your infrastructure. Your employees and collegues can connect with their normal business account.",
"teams.auth.verificationRecordName": "Record Name",
"teams.auth.verificationRecordValue": "Record Value",
"teams.auth.verified": "Domain verified.",
"teams.auth.verifiedHint": "The ownership of the domain has been verified.",
"teams.auth.verify": "Verify Domain",
"teams.auth.verifyFailed": "Failed to verify domain. Please reload.",
"teams.create": "Create",
"teams.createFailed": "Failed to create team. Please reload.",
"teams.delete": "Delete Team",

7
backend/i18n/frontend_fr.json

@ -1217,6 +1217,7 @@
"teams.auth.domain": "Domain",
"teams.auth.domainHint": "The domain is used to identity your users. When they enter their email address and the domain matches to your settings they will redirected to your authentication server.",
"teams.auth.domainHintEmail": "Email Format",
"teams.auth.notVerifiedHint": "Your users can only sign in with this server after you have verified that you own the domain. Add the following DNS TXT record to your domain and click verify.",
"teams.auth.redirectUrl": "Redirect URL",
"teams.auth.redirectUrlHint": "You have to allow this URL in your authentication server.",
"teams.auth.reloaded": "Auth setting reloaded.",
@ -1224,6 +1225,12 @@
"teams.auth.testLogin": "Test Login",
"teams.auth.use": "Custom OIDC Server",
"teams.auth.useHint": "Use single-sign-on (SSO) solution to connect Squidex to your infrastructure. Your employees and collegues can connect with their normal business account.",
"teams.auth.verificationRecordName": "Record Name",
"teams.auth.verificationRecordValue": "Record Value",
"teams.auth.verified": "Domain verified.",
"teams.auth.verifiedHint": "The ownership of the domain has been verified.",
"teams.auth.verify": "Verify Domain",
"teams.auth.verifyFailed": "Failed to verify domain. Please reload.",
"teams.create": "Créer",
"teams.createFailed": "Échec de la création de l'équipe. Veuillez recharger.",
"teams.delete": "Delete Team",

7
backend/i18n/frontend_it.json

@ -1217,6 +1217,7 @@
"teams.auth.domain": "Domain",
"teams.auth.domainHint": "The domain is used to identity your users. When they enter their email address and the domain matches to your settings they will redirected to your authentication server.",
"teams.auth.domainHintEmail": "Email Format",
"teams.auth.notVerifiedHint": "Your users can only sign in with this server after you have verified that you own the domain. Add the following DNS TXT record to your domain and click verify.",
"teams.auth.redirectUrl": "Redirect URL",
"teams.auth.redirectUrlHint": "You have to allow this URL in your authentication server.",
"teams.auth.reloaded": "Auth setting reloaded.",
@ -1224,6 +1225,12 @@
"teams.auth.testLogin": "Test Login",
"teams.auth.use": "Custom OIDC Server",
"teams.auth.useHint": "Use single-sign-on (SSO) solution to connect Squidex to your infrastructure. Your employees and collegues can connect with their normal business account.",
"teams.auth.verificationRecordName": "Record Name",
"teams.auth.verificationRecordValue": "Record Value",
"teams.auth.verified": "Domain verified.",
"teams.auth.verifiedHint": "The ownership of the domain has been verified.",
"teams.auth.verify": "Verify Domain",
"teams.auth.verifyFailed": "Failed to verify domain. Please reload.",
"teams.create": "Create",
"teams.createFailed": "Failed to create team. Please reload.",
"teams.delete": "Delete Team",

7
backend/i18n/frontend_nl.json

@ -1217,6 +1217,7 @@
"teams.auth.domain": "Domain",
"teams.auth.domainHint": "The domain is used to identity your users. When they enter their email address and the domain matches to your settings they will redirected to your authentication server.",
"teams.auth.domainHintEmail": "Email Format",
"teams.auth.notVerifiedHint": "Your users can only sign in with this server after you have verified that you own the domain. Add the following DNS TXT record to your domain and click verify.",
"teams.auth.redirectUrl": "Redirect URL",
"teams.auth.redirectUrlHint": "You have to allow this URL in your authentication server.",
"teams.auth.reloaded": "Auth setting reloaded.",
@ -1224,6 +1225,12 @@
"teams.auth.testLogin": "Test Login",
"teams.auth.use": "Custom OIDC Server",
"teams.auth.useHint": "Use single-sign-on (SSO) solution to connect Squidex to your infrastructure. Your employees and collegues can connect with their normal business account.",
"teams.auth.verificationRecordName": "Record Name",
"teams.auth.verificationRecordValue": "Record Value",
"teams.auth.verified": "Domain verified.",
"teams.auth.verifiedHint": "The ownership of the domain has been verified.",
"teams.auth.verify": "Verify Domain",
"teams.auth.verifyFailed": "Failed to verify domain. Please reload.",
"teams.create": "Create",
"teams.createFailed": "Failed to create team. Please reload.",
"teams.delete": "Delete Team",

7
backend/i18n/frontend_pt.json

@ -1217,6 +1217,7 @@
"teams.auth.domain": "Domain",
"teams.auth.domainHint": "The domain is used to identity your users. When they enter their email address and the domain matches to your settings they will redirected to your authentication server.",
"teams.auth.domainHintEmail": "Email Format",
"teams.auth.notVerifiedHint": "Your users can only sign in with this server after you have verified that you own the domain. Add the following DNS TXT record to your domain and click verify.",
"teams.auth.redirectUrl": "Redirect URL",
"teams.auth.redirectUrlHint": "You have to allow this URL in your authentication server.",
"teams.auth.reloaded": "Auth setting reloaded.",
@ -1224,6 +1225,12 @@
"teams.auth.testLogin": "Test Login",
"teams.auth.use": "Custom OIDC Server",
"teams.auth.useHint": "Use single-sign-on (SSO) solution to connect Squidex to your infrastructure. Your employees and collegues can connect with their normal business account.",
"teams.auth.verificationRecordName": "Record Name",
"teams.auth.verificationRecordValue": "Record Value",
"teams.auth.verified": "Domain verified.",
"teams.auth.verifiedHint": "The ownership of the domain has been verified.",
"teams.auth.verify": "Verify Domain",
"teams.auth.verifyFailed": "Failed to verify domain. Please reload.",
"teams.create": "Criar",
"teams.createFailed": "Falhou na criação de uma equipa. Por favor, recarregue.",
"teams.delete": "Delete Team",

7
backend/i18n/frontend_zh.json

@ -1217,6 +1217,7 @@
"teams.auth.domain": "Domain",
"teams.auth.domainHint": "The domain is used to identity your users. When they enter their email address and the domain matches to your settings they will redirected to your authentication server.",
"teams.auth.domainHintEmail": "Email Format",
"teams.auth.notVerifiedHint": "Your users can only sign in with this server after you have verified that you own the domain. Add the following DNS TXT record to your domain and click verify.",
"teams.auth.redirectUrl": "Redirect URL",
"teams.auth.redirectUrlHint": "You have to allow this URL in your authentication server.",
"teams.auth.reloaded": "Auth setting reloaded.",
@ -1224,6 +1225,12 @@
"teams.auth.testLogin": "Test Login",
"teams.auth.use": "Custom OIDC Server",
"teams.auth.useHint": "Use single-sign-on (SSO) solution to connect Squidex to your infrastructure. Your employees and collegues can connect with their normal business account.",
"teams.auth.verificationRecordName": "Record Name",
"teams.auth.verificationRecordValue": "Record Value",
"teams.auth.verified": "Domain verified.",
"teams.auth.verifiedHint": "The ownership of the domain has been verified.",
"teams.auth.verify": "Verify Domain",
"teams.auth.verifyFailed": "Failed to verify domain. Please reload.",
"teams.create": "Create",
"teams.createFailed": "Failed to create team. Please reload.",
"teams.delete": "Delete Team",

3
backend/i18n/source/backend_de.json

@ -336,6 +336,8 @@
"setup.ruleUrl.success": "Herzlichen Glückwunsch, die Umgebungsvariable `URLS__BASEURL` ist korrekt konfiguriert. Diese Variable muss auf die öffentliche URL zeigen, unter der Ihre Squidex-Instanz verfügbar ist.",
"setup.title": "Installation",
"teams.appsAssigned": "Team kann nicht gelöscht werden, wenn Apps zugewiesen sind.",
"teams.authDomainNotConfigured": "Es ist keine Authentifizierungsdomain konfiguriert.",
"teams.authDomainNotVerified": "Der DNS-TXT-Eintrag '{name}' mit dem Wert '{value}' wurde nicht gefunden.",
"teams.domainInUse": "Die Domain wird bereits für ein anderes Team verwendet.",
"users.accessDenied.text": "Diese Operation ist nicht erlaubt, Ihr Konto könnte gesperrt sein.",
"users.accessDenied.title": "Zugriff verweigert",
@ -350,6 +352,7 @@
"users.consent.piiText": "Ich verstehe und stimme zu, dass Squidex die folgenden privaten Informationen sammelt, die von externen Authentifizierungsanbietern wie Google, Microsoft oder Github abgerufen werden. <ul class=\"personal-information\"> <li> Grundlegende persönliche Informationen (Vorname, Nachname und Bild) werden allen anderen Benutzern zur Verfügung gestellt, damit sie Sie zu ihrem Arbeitsbereich hinzufügen können. </li><li> Sie haben jederzeit die Möglichkeit, diese Informationen zu ändern, um Ihr Konto zu anonymisieren. </li><li> Ihr Benutzerkonto hat eine eindeutige Kennung und für alle Ihre Änderungen verfolgen wir, dass Sie diese Änderungen vorgenommen haben und stellen diese Informationen anderen Benutzern zur Verfügung. </li></ul>",
"users.consent.title": "Zustimmung",
"users.deleteYourselfError": "Sie können sich nicht selbst löschen.",
"users.emailNotVerified": "Der Authentifizierungsanbieter hat Ihre E-Mail-Adresse nicht bestätigt.",
"users.error.headline": "Operation fehlgeschlagen",
"users.error.text": "Es tut uns wirklich leid, dass etwas schief gelaufen ist.",
"users.error.title": "Fehler",

3
backend/i18n/source/backend_en.json

@ -340,6 +340,8 @@
"setup.ruleUrl.success": "Congratulations, the <code>URLS__BASEURL</code> environment variable is configured properly. This variable must point to the public URL under which your Squidex instance is available.",
"setup.title": "Installation",
"teams.appsAssigned": "Cannot delete team, when apps are assigned.",
"teams.authDomainNotConfigured": "No authentication domain is configured.",
"teams.authDomainNotVerified": "The DNS TXT record '{name}' with the value '{value}' has not been found.",
"teams.domainInUse": "Domain is already used for another team.",
"users.accessDenied.text": "This operation is not allowed, your account might be locked.",
"users.accessDenied.title": "Access denied",
@ -354,6 +356,7 @@
"users.consent.piiText": "I understand and agree that Squidex collects the following private information that are retrieved from external authentication providers such as Google, Microsoft or Github. <ul class=\"personal-information\"> <li> Basic personal information (first name, last name and picture) are provided to all other users so that they can add you to their working space. </li><li> At anytime you have the option to change these information to anonymize your account. </li><li> Your user account has an unique identifier and for all your changes we track, that you made these changes and provide this information to other users. </li></ul>",
"users.consent.title": "Consent",
"users.deleteYourselfError": "You cannot delete yourself.",
"users.emailNotVerified": "The authentication provider has not verified your email address.",
"users.error.headline": "Operation failed",
"users.error.text": "We are really sorry that something went wrong.",
"users.error.title": "Error",

7
backend/i18n/source/frontend_de.json

@ -1128,6 +1128,7 @@
"teams.auth.domain": "Domäne",
"teams.auth.domainHint": "Die Domäne wird verwendet, um Ihre Benutzer zu identifizieren. Wenn sie ihre E-Mail-Adresse eingeben und die Domäne mit Ihren Einstellungen übereinstimmt, werden sie zu Ihrem Authentifizierungsserver weitergeleitet.",
"teams.auth.domainHintEmail": "E-Mail-Format",
"teams.auth.notVerifiedHint": "Ihre Benutzer können sich erst mit diesem Server anmelden, nachdem Sie bestätigt haben, dass Ihnen die Domäne gehört. Fügen Sie den folgenden DNS-TXT-Eintrag zu Ihrer Domäne hinzu und klicken Sie auf Bestätigen.",
"teams.auth.redirectUrl": "Weiterleitungs-URL",
"teams.auth.redirectUrlHint": "Sie müssen diese URL in Ihrem Authentifizierungsserver zulassen.",
"teams.auth.reloaded": "Authentifizierungseinstellung neu geladen.",
@ -1135,6 +1136,12 @@
"teams.auth.testLogin": "Testanmeldung",
"teams.auth.use": "Benutzerdefinierter OIDC-Server",
"teams.auth.useHint": "Verwenden Sie eine Single-Sign-On (SSO)-Lösung, um Squidex mit Ihrer Infrastruktur zu verbinden. Ihre Mitarbeiter und Kollegen können sich mit ihrem normalen Geschäftskonto verbinden.",
"teams.auth.verificationRecordName": "Eintragsname",
"teams.auth.verificationRecordValue": "Eintragswert",
"teams.auth.verified": "Domäne bestätigt.",
"teams.auth.verifiedHint": "Die Inhaberschaft der Domäne wurde bestätigt.",
"teams.auth.verify": "Domäne bestätigen",
"teams.auth.verifyFailed": "Die Domäne konnte nicht bestätigt werden. Bitte neu laden.",
"teams.create": "Erstellen",
"teams.createFailed": "Fehler beim Erstellen des Teams. Bitte neu laden.",
"teams.delete": "Team löschen",

7
backend/i18n/source/frontend_en.json

@ -1217,6 +1217,7 @@
"teams.auth.domain": "Domain",
"teams.auth.domainHint": "The domain is used to identity your users. When they enter their email address and the domain matches to your settings they will redirected to your authentication server.",
"teams.auth.domainHintEmail": "Email Format",
"teams.auth.notVerifiedHint": "Your users can only sign in with this server after you have verified that you own the domain. Add the following DNS TXT record to your domain and click verify.",
"teams.auth.redirectUrl": "Redirect URL",
"teams.auth.redirectUrlHint": "You have to allow this URL in your authentication server.",
"teams.auth.reloaded": "Auth setting reloaded.",
@ -1224,6 +1225,12 @@
"teams.auth.testLogin": "Test Login",
"teams.auth.use": "Custom OIDC Server",
"teams.auth.useHint": "Use single-sign-on (SSO) solution to connect Squidex to your infrastructure. Your employees and collegues can connect with their normal business account.",
"teams.auth.verificationRecordName": "Record Name",
"teams.auth.verificationRecordValue": "Record Value",
"teams.auth.verified": "Domain verified.",
"teams.auth.verifiedHint": "The ownership of the domain has been verified.",
"teams.auth.verify": "Verify Domain",
"teams.auth.verifyFailed": "Failed to verify domain. Please reload.",
"teams.create": "Create",
"teams.createFailed": "Failed to create team. Please reload.",
"teams.delete": "Delete Team",

7
backend/src/Squidex.Data.EntityFramework/Domain/Apps/Entities/Teams/EFTeamRepository.cs

@ -59,13 +59,14 @@ public sealed class EFTeamRepository<TContext>(IDbContextFactory<TContext> dbCon
{
await using var dbContext = await CreateDbContextAsync(ct);
var entity =
var entities =
await dbContext.Set<EFTeamEntity>()
.Where(x => x.IndexedAuthDomain == authDomain)
.Where(x => !x.IndexedDeleted)
.FirstOrDefaultAsync(ct);
.ToListAsync(ct);
return entity?.Document;
// Several teams can use the same domain, but only one of them can verify it.
return entities.Select(x => x.Document).FirstOrDefault(x => x.IsAuthDomainVerified);
}
}

7
backend/src/Squidex.Data.MongoDb/Domain/Apps/Entities/Teams/MongoTeamRepository.cs

@ -62,11 +62,12 @@ public sealed class MongoTeamRepository(IMongoDatabase database) : MongoSnapshot
{
using (Telemetry.Activities.StartActivity("MongoTeamRepository/FindByAuthDomainAsync"))
{
var entity =
var entities =
await Collection.Find(x => x.IndexedAuthDomain == authDomain && !x.IndexedDeleted)
.FirstOrDefaultAsync(ct);
.ToListAsync(ct);
return entity?.Document;
// Several teams can use the same domain, but only one of them can verify it.
return entities.Select(x => x.Document).FirstOrDefault(x => x.IsAuthDomainVerified);
}
}
}

23
backend/src/Squidex.Domain.Apps.Core.Model/Teams/Team.cs

@ -21,6 +21,8 @@ public record Team : Entity
public AuthScheme? AuthScheme { get; init; }
public bool IsAuthDomainVerified { get; init; }
public bool IsDeleted { get; init; }
[Pure]
@ -55,7 +57,26 @@ public record Team : Entity
return this;
}
return this with { AuthScheme = authScheme };
// The verification is only valid for the domain that has been verified.
var isVerified = IsAuthDomainVerified && string.Equals(authScheme?.Domain, AuthScheme?.Domain, StringComparison.OrdinalIgnoreCase);
return this with { AuthScheme = authScheme, IsAuthDomainVerified = isVerified };
}
[Pure]
public Team VerifyAuthDomain(string domain)
{
if (IsAuthDomainVerified)
{
return this;
}
if (!string.Equals(domain, AuthScheme?.Domain, StringComparison.OrdinalIgnoreCase))
{
return this;
}
return this with { IsAuthDomainVerified = true };
}
[Pure]

1
backend/src/Squidex.Domain.Apps.Entities/Squidex.Domain.Apps.Entities.csproj

@ -29,6 +29,7 @@
<ItemGroup>
<PackageReference Include="ConsoleTables" Version="2.7.0" />
<PackageReference Include="CsvHelper" Version="33.1.0" />
<PackageReference Include="DnsClient" Version="1.6.1" />
<PackageReference Include="FFMpegCore" Version="5.4.0" />
<PackageReference Include="GraphQL" Version="8.8.4" />
<PackageReference Include="GraphQL.DataLoader" Version="8.8.4" />

23
backend/src/Squidex.Domain.Apps.Entities/Teams/AuthDomainRecord.cs

@ -0,0 +1,23 @@
// ==========================================================================
// Squidex Headless CMS
// ==========================================================================
// Copyright (c) Squidex UG (haftungsbeschraenkt)
// All rights reserved. Licensed under the MIT license.
// ==========================================================================
using Squidex.Infrastructure;
namespace Squidex.Domain.Apps.Entities.Teams;
public static class AuthDomainRecord
{
public static string GetName(string domain)
{
return $"_squidex.{domain}";
}
public static string GetValue(DomainId teamId)
{
return $"squidex-team={teamId}";
}
}

12
backend/src/Squidex.Domain.Apps.Entities/Teams/Commands/VerifyAuthDomain.cs

@ -0,0 +1,12 @@
// ==========================================================================
// Squidex Headless CMS
// ==========================================================================
// Copyright (c) Squidex UG (haftungsbeschraenkt)
// All rights reserved. Licensed under the MIT license.
// ==========================================================================
namespace Squidex.Domain.Apps.Entities.Teams.Commands;
public sealed class VerifyAuthDomain : TeamCommand
{
}

34
backend/src/Squidex.Domain.Apps.Entities/Teams/DnsAuthDomainVerifier.cs

@ -0,0 +1,34 @@
// ==========================================================================
// Squidex Headless CMS
// ==========================================================================
// Copyright (c) Squidex UG (haftungsbeschraenkt)
// All rights reserved. Licensed under the MIT license.
// ==========================================================================
using DnsClient;
using Squidex.Infrastructure;
namespace Squidex.Domain.Apps.Entities.Teams;
public sealed class DnsAuthDomainVerifier : IAuthDomainVerifier
{
// Without the cache a record is found immediately after it has been added.
private readonly LookupClient lookupClient = new LookupClient(new LookupClientOptions { UseCache = false, ThrowDnsErrors = false });
public async Task<bool> IsVerifiedAsync(string domain, DomainId teamId,
CancellationToken ct = default)
{
var expected = AuthDomainRecord.GetValue(teamId);
try
{
var response = await lookupClient.QueryAsync(AuthDomainRecord.GetName(domain), QueryType.TXT, cancellationToken: ct);
return response.Answers.TxtRecords().SelectMany(x => x.Text).Any(x => string.Equals(x.Trim(), expected, StringComparison.Ordinal));
}
catch (DnsResponseException)
{
return false;
}
}
}

34
backend/src/Squidex.Domain.Apps.Entities/Teams/DomainObject/Guards/GuardTeam.cs

@ -5,6 +5,7 @@
// All rights reserved. Licensed under the MIT license.
// ==========================================================================
using Squidex.Domain.Apps.Core.Teams;
using Squidex.Domain.Apps.Entities.Billing;
using Squidex.Domain.Apps.Entities.Teams.Commands;
using Squidex.Infrastructure;
@ -122,6 +123,39 @@ public static class GuardTeam
});
}
public static Task CanVerifyAuthDomain(VerifyAuthDomain command, Team team, IAppProvider appProvider, IAuthDomainVerifier verifier,
CancellationToken ct)
{
Guard.NotNull(command);
return Validate.It(async e =>
{
var domain = team.AuthScheme?.Domain;
if (string.IsNullOrWhiteSpace(domain))
{
e(T.Get("teams.authDomainNotConfigured"));
return;
}
var existing = await appProvider.GetTeamByAuthDomainAsync(domain, ct);
if (existing != null && existing.Id != command.TeamId)
{
e(T.Get("teams.domainInUse"));
return;
}
if (!await verifier.IsVerifiedAsync(domain, command.TeamId, ct))
{
var name = AuthDomainRecord.GetName(domain);
var value = AuthDomainRecord.GetValue(command.TeamId);
e(T.Get("teams.authDomainNotVerified", new { name, value }));
}
});
}
public static Task CanDelete(DeleteTeam command, IAppProvider appProvider,
CancellationToken ct)
{

4
backend/src/Squidex.Domain.Apps.Entities/Teams/DomainObject/TeamDomainObject.State.cs

@ -49,6 +49,10 @@ public partial class TeamDomainObject
newSnapshot = snapshot.ChangeAuthScheme(e.Scheme);
break;
case TeamAuthDomainVerified e:
newSnapshot = snapshot.VerifyAuthDomain(e.Domain);
break;
case TeamDeleted:
newSnapshot = snapshot with { Plan = null, IsDeleted = true };
break;

20
backend/src/Squidex.Domain.Apps.Entities/Teams/DomainObject/TeamDomainObject.cs

@ -111,6 +111,16 @@ public partial class TeamDomainObject(
return Snapshot;
}, ct);
case VerifyAuthDomain verifyAuthDomain:
return ApplyReturnAsync(verifyAuthDomain, async (c, ct) =>
{
await GuardTeam.CanVerifyAuthDomain(c, Snapshot, AppProvider, AuthDomainVerifier, ct);
VerifyAuthDomain(c);
return Snapshot;
}, ct);
case DeleteTeam delete:
return ApplyAsync(delete, async (c, ct) =>
{
@ -200,6 +210,11 @@ public partial class TeamDomainObject(
Raise(command, new TeamAuthChanged());
}
private void VerifyAuthDomain(VerifyAuthDomain command)
{
Raise(command, new TeamAuthDomainVerified { Domain = Snapshot.AuthScheme!.Domain });
}
private void AssignContributor(AssignContributor command, bool isAdded)
{
Raise(command, new TeamContributorAssigned { IsAdded = isAdded });
@ -229,6 +244,11 @@ public partial class TeamDomainObject(
get => serviceProvider.GetRequiredService<IAppProvider>();
}
private IAuthDomainVerifier AuthDomainVerifier
{
get => serviceProvider.GetRequiredService<IAuthDomainVerifier>();
}
private IBillingPlans BillingPlans
{
get => serviceProvider.GetRequiredService<IBillingPlans>();

16
backend/src/Squidex.Domain.Apps.Entities/Teams/IAuthDomainVerifier.cs

@ -0,0 +1,16 @@
// ==========================================================================
// Squidex Headless CMS
// ==========================================================================
// Copyright (c) Squidex UG (haftungsbeschraenkt)
// All rights reserved. Licensed under the MIT license.
// ==========================================================================
using Squidex.Infrastructure;
namespace Squidex.Domain.Apps.Entities.Teams;
public interface IAuthDomainVerifier
{
Task<bool> IsVerifiedAsync(string domain, DomainId teamId,
CancellationToken ct = default);
}

2
backend/src/Squidex.Domain.Apps.Entities/Teams/Indexes/TeamsIndex.cs

@ -35,7 +35,7 @@ public sealed class TeamsIndex(ITeamRepository teamRepository) : ITeamsIndex
var team = await teamRepository.FindByAuthDomainAsync(authDomain, ct);
return IsValid(team) ? team : null;
return IsValid(team) && team!.IsAuthDomainVerified ? team : null;
}
}

13
backend/src/Squidex.Domain.Apps.Events/Teams/TeamAuthDomainVerified.cs

@ -0,0 +1,13 @@
// ==========================================================================
// Squidex Headless CMS
// ==========================================================================
// Copyright (c) Squidex UG (haftungsbeschraenkt)
// All rights reserved. Licensed under the MIT license.
// ==========================================================================
namespace Squidex.Domain.Apps.Events.Teams;
public sealed class TeamAuthDomainVerified : TeamEvent
{
public string Domain { get; set; }
}

9
backend/src/Squidex.Shared/Texts.de.resx

@ -1105,6 +1105,12 @@
<data name="teams.appsAssigned" xml:space="preserve">
<value>Team kann nicht gelöscht werden, wenn Apps zugewiesen sind.</value>
</data>
<data name="teams.authDomainNotConfigured" xml:space="preserve">
<value>Es ist keine Authentifizierungsdomain konfiguriert.</value>
</data>
<data name="teams.authDomainNotVerified" xml:space="preserve">
<value>Der DNS-TXT-Eintrag '{name}' mit dem Wert '{value}' wurde nicht gefunden.</value>
</data>
<data name="teams.domainInUse" xml:space="preserve">
<value>Die Domain wird bereits für ein anderes Team verwendet.</value>
</data>
@ -1147,6 +1153,9 @@
<data name="users.deleteYourselfError" xml:space="preserve">
<value>Sie können sich nicht selbst löschen.</value>
</data>
<data name="users.emailNotVerified" xml:space="preserve">
<value>Der Authentifizierungsanbieter hat Ihre E-Mail-Adresse nicht bestätigt.</value>
</data>
<data name="users.error.headline" xml:space="preserve">
<value>Operation fehlgeschlagen</value>
</data>

9
backend/src/Squidex.Shared/Texts.fr.resx

@ -1105,6 +1105,12 @@
<data name="teams.appsAssigned" xml:space="preserve">
<value>Cannot delete team, when apps are assigned.</value>
</data>
<data name="teams.authDomainNotConfigured" xml:space="preserve">
<value>No authentication domain is configured.</value>
</data>
<data name="teams.authDomainNotVerified" xml:space="preserve">
<value>The DNS TXT record '{name}' with the value '{value}' has not been found.</value>
</data>
<data name="teams.domainInUse" xml:space="preserve">
<value>Domain is already used for another team.</value>
</data>
@ -1147,6 +1153,9 @@
<data name="users.deleteYourselfError" xml:space="preserve">
<value>Vous ne pouvez pas vous supprimer.</value>
</data>
<data name="users.emailNotVerified" xml:space="preserve">
<value>The authentication provider has not verified your email address.</value>
</data>
<data name="users.error.headline" xml:space="preserve">
<value>L'opération a échoué</value>
</data>

9
backend/src/Squidex.Shared/Texts.it.resx

@ -1105,6 +1105,12 @@
<data name="teams.appsAssigned" xml:space="preserve">
<value>Cannot delete team, when apps are assigned.</value>
</data>
<data name="teams.authDomainNotConfigured" xml:space="preserve">
<value>No authentication domain is configured.</value>
</data>
<data name="teams.authDomainNotVerified" xml:space="preserve">
<value>The DNS TXT record '{name}' with the value '{value}' has not been found.</value>
</data>
<data name="teams.domainInUse" xml:space="preserve">
<value>Domain is already used for another team.</value>
</data>
@ -1147,6 +1153,9 @@
<data name="users.deleteYourselfError" xml:space="preserve">
<value>Non puoi cancellare te stesso.</value>
</data>
<data name="users.emailNotVerified" xml:space="preserve">
<value>The authentication provider has not verified your email address.</value>
</data>
<data name="users.error.headline" xml:space="preserve">
<value>Operazione non riuscita</value>
</data>

9
backend/src/Squidex.Shared/Texts.nl.resx

@ -1105,6 +1105,12 @@
<data name="teams.appsAssigned" xml:space="preserve">
<value>Cannot delete team, when apps are assigned.</value>
</data>
<data name="teams.authDomainNotConfigured" xml:space="preserve">
<value>No authentication domain is configured.</value>
</data>
<data name="teams.authDomainNotVerified" xml:space="preserve">
<value>The DNS TXT record '{name}' with the value '{value}' has not been found.</value>
</data>
<data name="teams.domainInUse" xml:space="preserve">
<value>Domain is already used for another team.</value>
</data>
@ -1147,6 +1153,9 @@
<data name="users.deleteYourselfError" xml:space="preserve">
<value>Je kan jezelf niet verwijderen.</value>
</data>
<data name="users.emailNotVerified" xml:space="preserve">
<value>The authentication provider has not verified your email address.</value>
</data>
<data name="users.error.headline" xml:space="preserve">
<value>Bewerking mislukt</value>
</data>

9
backend/src/Squidex.Shared/Texts.pt.resx

@ -1105,6 +1105,12 @@
<data name="teams.appsAssigned" xml:space="preserve">
<value>Cannot delete team, when apps are assigned.</value>
</data>
<data name="teams.authDomainNotConfigured" xml:space="preserve">
<value>No authentication domain is configured.</value>
</data>
<data name="teams.authDomainNotVerified" xml:space="preserve">
<value>The DNS TXT record '{name}' with the value '{value}' has not been found.</value>
</data>
<data name="teams.domainInUse" xml:space="preserve">
<value>Domain is already used for another team.</value>
</data>
@ -1147,6 +1153,9 @@
<data name="users.deleteYourselfError" xml:space="preserve">
<value>Não pode remover a si proprio.</value>
</data>
<data name="users.emailNotVerified" xml:space="preserve">
<value>The authentication provider has not verified your email address.</value>
</data>
<data name="users.error.headline" xml:space="preserve">
<value>Operação falhada</value>
</data>

9
backend/src/Squidex.Shared/Texts.resx

@ -1105,6 +1105,12 @@
<data name="teams.appsAssigned" xml:space="preserve">
<value>Cannot delete team, when apps are assigned.</value>
</data>
<data name="teams.authDomainNotConfigured" xml:space="preserve">
<value>No authentication domain is configured.</value>
</data>
<data name="teams.authDomainNotVerified" xml:space="preserve">
<value>The DNS TXT record '{name}' with the value '{value}' has not been found.</value>
</data>
<data name="teams.domainInUse" xml:space="preserve">
<value>Domain is already used for another team.</value>
</data>
@ -1147,6 +1153,9 @@
<data name="users.deleteYourselfError" xml:space="preserve">
<value>You cannot delete yourself.</value>
</data>
<data name="users.emailNotVerified" xml:space="preserve">
<value>The authentication provider has not verified your email address.</value>
</data>
<data name="users.error.headline" xml:space="preserve">
<value>Operation failed</value>
</data>

9
backend/src/Squidex.Shared/Texts.zh.resx

@ -1105,6 +1105,12 @@
<data name="teams.appsAssigned" xml:space="preserve">
<value>Cannot delete team, when apps are assigned.</value>
</data>
<data name="teams.authDomainNotConfigured" xml:space="preserve">
<value>No authentication domain is configured.</value>
</data>
<data name="teams.authDomainNotVerified" xml:space="preserve">
<value>The DNS TXT record '{name}' with the value '{value}' has not been found.</value>
</data>
<data name="teams.domainInUse" xml:space="preserve">
<value>Domain is already used for another team.</value>
</data>
@ -1147,6 +1153,9 @@
<data name="users.deleteYourselfError" xml:space="preserve">
<value>你不能删除自己。</value>
</data>
<data name="users.emailNotVerified" xml:space="preserve">
<value>The authentication provider has not verified your email address.</value>
</data>
<data name="users.error.headline" xml:space="preserve">
<value>操作失败</value>
</data>

33
backend/src/Squidex/Areas/Api/Controllers/Teams/Models/AuthSchemeResponseDto.cs

@ -6,6 +6,7 @@
// ==========================================================================
using Squidex.Domain.Apps.Core.Teams;
using Squidex.Domain.Apps.Entities.Teams;
using Squidex.Web;
namespace Squidex.Areas.Api.Controllers.Teams.Models;
@ -17,6 +18,21 @@ public class AuthSchemeResponseDto : Resource
/// </summary>
public AuthSchemeDto? Scheme { get; set; }
/// <summary>
/// True, if the ownership of the domain has been verified.
/// </summary>
public bool IsVerified { get; set; }
/// <summary>
/// The name of the DNS TXT record to verify the ownership of the domain.
/// </summary>
public string? VerificationRecordName { get; set; }
/// <summary>
/// The value of the DNS TXT record to verify the ownership of the domain.
/// </summary>
public string? VerificationRecordValue { get; set; }
public static AuthSchemeResponseDto FromDomain(Team team, Resources resources)
{
var result = new AuthSchemeResponseDto();
@ -24,6 +40,9 @@ public class AuthSchemeResponseDto : Resource
if (team.AuthScheme != null)
{
result.Scheme = AuthSchemeDto.FromDomain(team.AuthScheme);
result.IsVerified = team.IsAuthDomainVerified;
result.VerificationRecordName = AuthDomainRecord.GetName(team.AuthScheme.Domain);
result.VerificationRecordValue = AuthDomainRecord.GetValue(team.Id);
}
return result.CreateLinks(resources);
@ -35,10 +54,18 @@ public class AuthSchemeResponseDto : Resource
AddSelfLink(resources.Url<TeamsController>(x => nameof(x.GetTeamAuth), values));
if (resources.CanChangeTeamAuth)
if (!resources.CanChangeTeamAuth)
{
return this;
}
AddPutLink("update",
resources.Url<TeamsController>(x => nameof(x.PutTeamAuth), values));
if (Scheme != null && !IsVerified)
{
AddPutLink("update",
resources.Url<TeamsController>(x => nameof(x.PutTeamAuth), values));
AddPostLink("verify",
resources.Url<TeamsController>(x => nameof(x.PostTeamAuthVerify), values));
}
return this;

24
backend/src/Squidex/Areas/Api/Controllers/Teams/TeamsController.cs

@ -167,6 +167,30 @@ public sealed class TeamsController(ICommandBus commandBus, IAppProvider appProv
return Ok(response);
}
/// <summary>
/// Verify the ownership of the team auth domain with a DNS TXT record.
/// </summary>
/// <param name="team">The ID of the team.</param>
/// <response code="200">Domain verified.</response>
/// <response code="400">DNS record not found or domain used by another team.</response>
/// <response code="404">Team not found.</response>
[HttpPost]
[Route("teams/{team}/auth/verify")]
[ProducesResponseType(typeof(AuthSchemeResponseDto), StatusCodes.Status200OK)]
[ApiPermission(PermissionIds.TeamAuthChange)]
[ApiCosts(0)]
public async Task<IActionResult> PostTeamAuthVerify(string team)
{
var command = new VerifyAuthDomain();
var response = await InvokeCommandAsync(command, x =>
{
return AuthSchemeResponseDto.FromDomain(x, Resources);
});
return Ok(response);
}
/// <summary>
/// Delete the team.
/// </summary>

31
backend/src/Squidex/Areas/IdentityServer/Config/Dynamic/DynamicSchemeProvider.cs

@ -67,7 +67,7 @@ public sealed class DynamicSchemeProvider(
var team = await appProvider.GetTeamByAuthDomainAsync(parts[1], default);
if (team?.AuthScheme != null)
{
return CreateScheme(team.Id.ToString(), team.AuthScheme).Scheme;
return CreateScheme(team.Id.ToString(), team.AuthScheme, true).Scheme;
}
return null;
@ -147,14 +147,22 @@ public sealed class DynamicSchemeProvider(
return cached as SchemeResult;
}
var scheme =
await GetSchemeByTeamAsync(name, ct) ??
await GetSchemeByTempNameAsync(name, ct);
SchemeResult? result = null;
var result =
scheme != null ?
CreateScheme(name, scheme) :
null;
var teamScheme = await GetSchemeByTeamAsync(name, ct);
if (teamScheme != null)
{
result = CreateScheme(name, teamScheme, true);
}
else
{
var tempScheme = await GetSchemeByTempNameAsync(name, ct);
if (tempScheme != null)
{
// Temporary schemes can be created by anybody to test the configuration and are never trusted.
result = CreateScheme(name, tempScheme, false);
}
}
if (httpContextAccessor.HttpContext != null)
{
@ -169,7 +177,8 @@ public sealed class DynamicSchemeProvider(
{
var app = await appProvider.GetTeamAsync(DomainId.Create(name), ct);
return app?.AuthScheme;
// Unverified schemes could be used to sign in with emails of a domain that the team does not own.
return app?.IsAuthDomainVerified == true ? app.AuthScheme : null;
}
private async Task<AuthScheme?> GetSchemeByTempNameAsync(string name,
@ -180,7 +189,7 @@ public sealed class DynamicSchemeProvider(
return value != null ? jsonSerializer.Deserialize<AuthScheme>(new MemoryStream(value)) : null;
}
private SchemeResult CreateScheme(string name, AuthScheme config)
private SchemeResult CreateScheme(string name, AuthScheme config, bool isTeamScheme)
{
var scheme = new AuthenticationScheme(name, config.DisplayName, typeof(DynamicOpenIdConnectHandler));
@ -189,7 +198,7 @@ public sealed class DynamicSchemeProvider(
Events = new OidcHandler(new MyIdentityOptions
{
OidcOnSignoutRedirectUrl = config.SignoutRedirectUrl,
}),
}, isTeamScheme, config.Domain ?? string.Empty),
Authority = config.Authority,
CallbackPath = new PathString($"/signin-{name}"),
ClientId = config.ClientId,

7
backend/src/Squidex/Areas/IdentityServer/Controllers/Account/AccountController.cs

@ -11,6 +11,7 @@ using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Squidex.Areas.IdentityServer.Config;
using Squidex.Config;
using Squidex.Config.Authentication;
using Squidex.Domain.Users;
using Squidex.Infrastructure;
using Squidex.Infrastructure.Security;
@ -279,6 +280,12 @@ public sealed class AccountController(
throw new DomainException(T.Get("users.noEmailAddress"));
}
// Otherwise an attacker could squat an email address or claim the account of an invited user.
if (!login.Principal.IsEmailVerified())
{
throw new DomainException(T.Get("users.emailNotVerified"));
}
user = await userService.FindByEmailAsync(email!, HttpContext.RequestAborted);
// User might not have a login or password if the user got invited.

2
backend/src/Squidex/Config/Authentication/GithubHandler.cs

@ -29,6 +29,8 @@ public sealed class GithubHandler : OAuthEvents
throw new DomainException(T.Get("login.githubPrivateEmail"));
}
context.Identity.SetEmailVerified(true);
return base.CreatingTicket(context);
}
}

17
backend/src/Squidex/Config/Authentication/GoogleHandler.cs

@ -7,6 +7,7 @@
using System.Security.Claims;
using System.Text.Json;
using System.Text.Json.Serialization;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.OAuth;
using Squidex.Shared.Identity;
@ -56,6 +57,22 @@ public sealed class GoogleHandler : OAuthEvents
context.Identity?.AddClaim(new Claim(SquidexClaimTypes.PictureUrl, pictureUrl));
}
var user = context.User.Deserialize<GoogleUser>(JsonSerializerOptions.Web);
// The property name depends on the version of the user info endpoint.
var isVerified = user?.EmailVerified == true || user?.VerifiedEmail == true;
context.Identity.SetEmailVerified(isVerified);
return base.CreatingTicket(context);
}
private sealed class GoogleUser
{
[JsonPropertyName("email_verified")]
public bool? EmailVerified { get; init; }
[JsonPropertyName("verified_email")]
public bool? VerifiedEmail { get; init; }
}
}

35
backend/src/Squidex/Config/Authentication/MicrosoftHandler.cs

@ -42,6 +42,41 @@ public sealed class MicrosoftHandler : OAuthEvents
context.Identity?.AddClaim(new Claim(SquidexClaimTypes.PictureUrl, pictureUrl));
}
UseUserPrincipalNameAsEmail(context);
return base.CreatingTicket(context);
}
private static void UseUserPrincipalNameAsEmail(OAuthCreatingTicketContext context)
{
var identity = context.Identity;
if (identity == null)
{
return;
}
// The 'mail' attribute can be set to any value by the admin of any tenant, therefore we cannot trust it.
foreach (var claim in identity.FindAll(ClaimTypes.Email).ToList())
{
identity.RemoveClaim(claim);
}
var upn = context.User.Deserialize<MicrosoftUser>(JsonSerializerOptions.Web)?.UserPrincipalName;
// The UPN must use a domain that has been verified by the tenant. Guest accounts contain '#EXT#' and are not verified.
var isValid = !string.IsNullOrWhiteSpace(upn) && upn.Contains('@', StringComparison.Ordinal) && !upn.Contains('#', StringComparison.Ordinal);
if (isValid)
{
identity.AddClaim(new Claim(ClaimTypes.Email, upn!));
}
identity.SetEmailVerified(isValid);
}
private sealed class MicrosoftUser
{
public string? UserPrincipalName { get; init; }
}
}

46
backend/src/Squidex/Config/Authentication/OidcHandler.cs

@ -6,12 +6,14 @@
// ==========================================================================
using System.Security.Claims;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Squidex.Infrastructure.Security;
using Squidex.Shared.Identity;
namespace Squidex.Config.Authentication;
public sealed class OidcHandler(MyIdentityOptions options) : OpenIdConnectEvents
public sealed class OidcHandler(MyIdentityOptions options, bool trustEmails = true, string? emailDomain = null) : OpenIdConnectEvents
{
public override Task TokenValidated(TokenValidatedContext context)
{
@ -34,6 +36,18 @@ public sealed class OidcHandler(MyIdentityOptions options) : OpenIdConnectEvents
return base.TokenValidated(context);
}
public override Task TicketReceived(TicketReceivedContext context)
{
var principal = context.Principal;
if (principal != null)
{
(principal.Identity as ClaimsIdentity).SetEmailVerified(IsEmailVerified(principal));
}
return base.TicketReceived(context);
}
public override Task RedirectToIdentityProviderForSignOut(RedirectContext context)
{
if (!string.IsNullOrEmpty(options.OidcOnSignoutRedirectUrl))
@ -48,4 +62,34 @@ public sealed class OidcHandler(MyIdentityOptions options) : OpenIdConnectEvents
return base.RedirectToIdentityProviderForSignOut(context);
}
private bool IsEmailVerified(ClaimsPrincipal principal)
{
if (!trustEmails)
{
return false;
}
var email = principal.GetEmail();
if (string.IsNullOrWhiteSpace(email))
{
return false;
}
// Dynamic providers can only vouch for emails of their own domain.
if (emailDomain != null && !email.EndsWith($"@{emailDomain}", StringComparison.OrdinalIgnoreCase))
{
return false;
}
var verified = principal.FindFirst("email_verified")?.Value;
if (verified != null)
{
return bool.TryParse(verified, out var isVerified) && isVerified;
}
return !options.OidcRequireVerifiedEmail;
}
}

40
backend/src/Squidex/Config/Authentication/VerifiedEmailExtensions.cs

@ -0,0 +1,40 @@
// ==========================================================================
// Squidex Headless CMS
// ==========================================================================
// Copyright (c) Squidex UG (haftungsbeschraenkt)
// All rights reserved. Licensed under the MIT license.
// ==========================================================================
using System.Security.Claims;
namespace Squidex.Config.Authentication;
public static class VerifiedEmailExtensions
{
// Not prefixed with 'urn:squidex:' so that it is never stored as a custom user claim.
private const string ClaimType = "squidex_email_verified";
public static void SetEmailVerified(this ClaimsIdentity? identity, bool verified)
{
if (identity == null)
{
return;
}
// Never trust a value that has been provided by the external identity provider.
foreach (var claim in identity.FindAll(ClaimType).ToList())
{
identity.RemoveClaim(claim);
}
if (verified)
{
identity.AddClaim(new Claim(ClaimType, "true"));
}
}
public static bool IsEmailVerified(this ClaimsPrincipal principal)
{
return principal.HasClaim(ClaimType, "true");
}
}

4
backend/src/Squidex/Config/Domain/CommandsServices.cs

@ -22,6 +22,7 @@ using Squidex.Domain.Apps.Entities.Schemas;
using Squidex.Domain.Apps.Entities.Schemas.Commands;
using Squidex.Domain.Apps.Entities.Schemas.DomainObject;
using Squidex.Domain.Apps.Entities.Schemas.Indexes;
using Squidex.Domain.Apps.Entities.Teams;
using Squidex.Domain.Apps.Entities.Teams.Commands;
using Squidex.Domain.Apps.Entities.Teams.DomainObject;
using Squidex.Domain.Apps.Entities.Teams.Indexes;
@ -105,6 +106,9 @@ public static class CommandsServices
services.AddSingletonAs<TeamsIndex>()
.As<ITeamsIndex>();
services.AddSingletonAs<DnsAuthDomainVerifier>()
.As<IAuthDomainVerifier>();
services.AddSingletonAs<AppCommandMiddleware>()
.As<ICommandMiddleware>();

2
backend/src/Squidex/Config/MyIdentityOptions.cs

@ -72,6 +72,8 @@ public sealed class MyIdentityOptions
public bool OidcOverridePermissionsWithCustomClaimsOnLogin { get; set; }
public bool OidcRequireVerifiedEmail { get; set; }
public bool AdminRecreate { get; set; }
public bool AllowPasswordAuth { get; set; }

3
backend/src/Squidex/appsettings.json

@ -824,6 +824,9 @@
"oidcResponseType": "id_token", // or "code"
"oidcGetClaimsFromUserInfoEndpoint": false,
"oidcOverridePermissionsWithCustomClaimsOnLogin": false,
// Set to true to require the "email_verified" claim. Without this claim the email of the OIDC provider is trusted.
// Only users with a verified email can create an account or claim an account they got invited to.
"oidcRequireVerifiedEmail": false,
"oidcOnSignoutRedirectUrl": "",
// Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectOptions by default contains scopes "openid" and "profile".
// When oidcDisableProfileScope is set to true scope "profile" will be removed.

35
backend/tests/Squidex.Data.Tests/Shared/TeamRepositoryTests.cs

@ -53,6 +53,15 @@ public abstract class TeamRepositoryTests
CreatedBy = createdBy,
};
var byAuthUnverified = new Team
{
Id = DomainId.NewGuid(),
Name = "by-auth-unverified",
Created = created,
CreatedBy = createdBy,
AuthScheme = new AuthScheme { Domain = "squidex.io" },
};
var byAuth = new Team
{
Id = DomainId.NewGuid(),
@ -60,6 +69,7 @@ public abstract class TeamRepositoryTests
Created = created,
CreatedBy = createdBy,
AuthScheme = new AuthScheme { Domain = "squidex.io" },
IsAuthDomainVerified = true,
};
var byContributors = new Team
@ -73,6 +83,7 @@ public abstract class TeamRepositoryTests
await PrepareAsync(sut, [
known,
byAuthUnverified,
byAuth,
byContributors,
]);
@ -100,6 +111,29 @@ public abstract class TeamRepositoryTests
Assert.Equal("by-auth", found!.Name);
}
[Fact]
public async Task Should_not_find_by_auth_schema_if_not_verified()
{
var sut = await CreateSutAsync();
var authDomain = $"{Guid.NewGuid()}.io";
var unverified = new Team
{
Id = DomainId.NewGuid(),
Name = "unverified",
Created = SystemClock.Instance.GetCurrentInstant(),
CreatedBy = RefToken.Client("client1"),
AuthScheme = new AuthScheme { Domain = authDomain },
};
await PrepareAsync(sut, [unverified]);
var found = await sut.FindByAuthDomainAsync(authDomain);
Assert.Null(found);
}
[Theory]
[InlineData("1")]
[InlineData("2")]
@ -139,6 +173,7 @@ public abstract class TeamRepositoryTests
Created = SystemClock.Instance.GetCurrentInstant(),
CreatedBy = RefToken.Client("client1"),
AuthScheme = new AuthScheme { Domain = authDomain },
IsAuthDomainVerified = true,
Contributors = Contributors.Empty.Assign(contributorId, Role.Owner),
IsDeleted = true,
};

1
backend/tests/Squidex.Domain.Apps.Core.Tests/Model/Teams/Team.json

@ -5,6 +5,7 @@
"created": "2022-12-05T11:00:23Z",
"createdBy": "subject:63761585e06d5466c71521b3",
"id": "265aaf1e-5dff-4c40-b1e6-1149f652cd30",
"isAuthDomainVerified": false,
"isDeleted": false,
"lastModified": "2022-12-05T11:00:23Z",
"lastModifiedBy": "subject:63761585e06d5466c71521b3",

49
backend/tests/Squidex.Domain.Apps.Core.Tests/Model/Teams/TeamTests.cs

@ -68,6 +68,55 @@ public class TeamTests
Assert.Same(team_1, team_2);
}
[Fact]
public void Should_verify_auth_domain()
{
var team_1 = team_0.ChangeAuthScheme(new AuthScheme { Domain = "squidex.io" });
var team_2 = team_1.VerifyAuthDomain("SQUIDEX.io");
var team_3 = team_2.VerifyAuthDomain("squidex.io");
Assert.False(team_1.IsAuthDomainVerified);
Assert.True(team_2.IsAuthDomainVerified);
Assert.Same(team_2, team_3);
}
[Fact]
public void Should_not_verify_auth_domain_if_domain_does_not_match()
{
var team_1 = team_0.ChangeAuthScheme(new AuthScheme { Domain = "squidex.io" });
var team_2 = team_1.VerifyAuthDomain("other.io");
Assert.Same(team_1, team_2);
Assert.False(team_2.IsAuthDomainVerified);
}
[Fact]
public void Should_keep_verification_if_domain_does_not_change()
{
var team_1 = team_0.ChangeAuthScheme(new AuthScheme { Domain = "squidex.io" }).VerifyAuthDomain("squidex.io");
var team_2 = team_1.ChangeAuthScheme(new AuthScheme { Domain = "Squidex.io", DisplayName = "Changed" });
Assert.True(team_2.IsAuthDomainVerified);
}
[Fact]
public void Should_reset_verification_if_domain_changes()
{
var team_1 = team_0.ChangeAuthScheme(new AuthScheme { Domain = "squidex.io" }).VerifyAuthDomain("squidex.io");
var team_2 = team_1.ChangeAuthScheme(new AuthScheme { Domain = "other.io" });
Assert.False(team_2.IsAuthDomainVerified);
}
[Fact]
public void Should_reset_verification_if_scheme_removed()
{
var team_1 = team_0.ChangeAuthScheme(new AuthScheme { Domain = "squidex.io" }).VerifyAuthDomain("squidex.io");
var team_2 = team_1.ChangeAuthScheme(null);
Assert.False(team_2.IsAuthDomainVerified);
}
[Fact]
public void Should_update_contributors()
{

55
backend/tests/Squidex.Domain.Apps.Entities.Tests/Teams/DomainObject/Guards/GuardTeamTests.cs

@ -8,6 +8,7 @@
using Squidex.Domain.Apps.Core.Teams;
using Squidex.Domain.Apps.Core.TestHelpers;
using Squidex.Domain.Apps.Entities.Billing;
using Squidex.Domain.Apps.Entities.Teams;
using Squidex.Domain.Apps.Entities.Teams.Commands;
using Squidex.Domain.Apps.Entities.Teams.DomainObject.Guards;
using Squidex.Domain.Apps.Entities.TestHelpers;
@ -19,6 +20,7 @@ namespace Squidex.Domain.Teams.Apps.Teams.DomainObject.Guards;
public class GuardTeamTests : GivenContext, IClassFixture<TranslationsFixture>
{
private readonly IAuthDomainVerifier verifier = A.Fake<IAuthDomainVerifier>();
private readonly IUserResolver users = A.Fake<IUserResolver>();
private readonly IBillingPlans billingPlans = A.Fake<IBillingPlans>();
private readonly Plan planBasic = new Plan();
@ -177,6 +179,59 @@ public class GuardTeamTests : GivenContext, IClassFixture<TranslationsFixture>
await GuardTeam.CanUpsertAuth(command, AppProvider, CancellationToken);
}
[Fact]
public async Task CanVerifyAuthDomain_should_throw_exception_if_no_scheme_configured()
{
var command = new VerifyAuthDomain { TeamId = Team.Id };
await ValidationAssert.ThrowsAsync(() => GuardTeam.CanVerifyAuthDomain(command, Team with { AuthScheme = null }, AppProvider, verifier, CancellationToken),
new ValidationError("No authentication domain is configured."));
}
[Fact]
public async Task CanVerifyAuthDomain_should_throw_exception_if_domain_verified_by_another_team()
{
A.CallTo(() => AppProvider.GetTeamByAuthDomainAsync("squidex.io", CancellationToken))
.Returns(Team with { Id = DomainId.NewGuid() });
var command = new VerifyAuthDomain { TeamId = Team.Id };
await ValidationAssert.ThrowsAsync(() => GuardTeam.CanVerifyAuthDomain(command, Team with { AuthScheme = scheme }, AppProvider, verifier, CancellationToken),
new ValidationError("Domain is already used for another team."));
A.CallTo(() => verifier.IsVerifiedAsync(A<string>._, A<DomainId>._, A<CancellationToken>._))
.MustNotHaveHappened();
}
[Fact]
public async Task CanVerifyAuthDomain_should_throw_exception_if_record_not_found()
{
A.CallTo(() => AppProvider.GetTeamByAuthDomainAsync("squidex.io", CancellationToken))
.Returns(Task.FromResult<Team?>(null));
A.CallTo(() => verifier.IsVerifiedAsync("squidex.io", Team.Id, CancellationToken))
.Returns(false);
var command = new VerifyAuthDomain { TeamId = Team.Id };
await ValidationAssert.ThrowsAsync(() => GuardTeam.CanVerifyAuthDomain(command, Team with { AuthScheme = scheme }, AppProvider, verifier, CancellationToken),
new ValidationError($"The DNS TXT record '_squidex.squidex.io' with the value 'squidex-team={Team.Id}' has not been found."));
}
[Fact]
public async Task CanVerifyAuthDomain_should_not_throw_exception_if_record_found()
{
A.CallTo(() => AppProvider.GetTeamByAuthDomainAsync("squidex.io", CancellationToken))
.Returns(Team);
A.CallTo(() => verifier.IsVerifiedAsync("squidex.io", Team.Id, CancellationToken))
.Returns(true);
var command = new VerifyAuthDomain { TeamId = Team.Id };
await GuardTeam.CanVerifyAuthDomain(command, Team with { AuthScheme = scheme }, AppProvider, verifier, CancellationToken);
}
[Fact]
public async Task CanDelete_should_throw_exception_if_app_is_assigned()
{

35
backend/tests/Squidex.Domain.Apps.Entities.Tests/Teams/DomainObject/TeamDomainObjectTests.cs

@ -13,6 +13,7 @@ using Squidex.Domain.Apps.Entities.Billing;
using Squidex.Domain.Apps.Entities.Teams.Commands;
using Squidex.Domain.Apps.Entities.TestHelpers;
using Squidex.Infrastructure;
using Squidex.Infrastructure.Validation;
using Squidex.Shared.Users;
namespace Squidex.Domain.Apps.Entities.Teams.DomainObject;
@ -20,6 +21,7 @@ namespace Squidex.Domain.Apps.Entities.Teams.DomainObject;
public class TeamDomainObjectTests : HandlerTestBase<Team>
{
private readonly IAppProvider appProvider = A.Fake<IAppProvider>();
private readonly IAuthDomainVerifier authDomainVerifier = A.Fake<IAuthDomainVerifier>();
private readonly IBillingPlans billingPlans = A.Fake<IBillingPlans>();
private readonly IBillingManager billingManager = A.Fake<IBillingManager>();
private readonly IUser user;
@ -70,6 +72,7 @@ public class TeamDomainObjectTests : HandlerTestBase<Team>
var serviceProvider =
new ServiceCollection()
.AddSingleton(appProvider)
.AddSingleton(authDomainVerifier)
.AddSingleton(billingPlans)
.AddSingleton(billingManager)
.AddSingleton(userResolver)
@ -139,6 +142,38 @@ public class TeamDomainObjectTests : HandlerTestBase<Team>
await VerifySutAsync(actual);
}
[Fact]
public async Task VerifyAuthDomain_should_create_events_and_verify_domain()
{
A.CallTo(() => authDomainVerifier.IsVerifiedAsync(scheme.Domain, TeamId, A<CancellationToken>._))
.Returns(true);
var command = new VerifyAuthDomain();
await ExecuteCreateAsync();
await ExecuteUpsertAuthAsync();
var actual = await PublishIdempotentAsync(sut, command);
await VerifySutAsync(actual);
}
[Fact]
public async Task VerifyAuthDomain_should_throw_exception_if_record_not_found()
{
A.CallTo(() => authDomainVerifier.IsVerifiedAsync(scheme.Domain, TeamId, A<CancellationToken>._))
.Returns(false);
var command = new VerifyAuthDomain();
await ExecuteCreateAsync();
await ExecuteUpsertAuthAsync();
await Assert.ThrowsAsync<ValidationException>(() => PublishAsync(sut, command));
Assert.False(sut.Snapshot.IsAuthDomainVerified);
}
[Fact]
public async Task ChangePlan_should_create_events_and_update_plan()
{

19
backend/tests/Squidex.Domain.Apps.Entities.Tests/Teams/Indexes/TeamsIndexTests.cs

@ -70,11 +70,26 @@ public class TeamsIndexTests : GivenContext
[Fact]
public async Task Should_resolve_team_by_domain()
{
var team = Team with { IsAuthDomainVerified = true };
A.CallTo(() => teamRepository.FindByAuthDomainAsync("squidex.io", CancellationToken))
.Returns(Team);
.Returns(team);
var actual = await sut.GetTeamByAuthDomainAsync("squidex.io", CancellationToken);
Assert.Same(actual, Team);
Assert.Same(actual, team);
}
[Fact]
public async Task Should_not_resolve_team_by_domain_if_not_verified()
{
var team = Team with { IsAuthDomainVerified = false };
A.CallTo(() => teamRepository.FindByAuthDomainAsync("squidex.io", CancellationToken))
.Returns(team);
var actual = await sut.GetTeamByAuthDomainAsync("squidex.io", CancellationToken);
Assert.Null(actual);
}
}

1
backend/tests/Squidex.Domain.Apps.Entities.Tests/Verify/TeamDomainObjectTests.AssignContributor_should_create_events_and_add_contributor.verified.txt

@ -4,6 +4,7 @@
Guid_1: Owner,
me: Owner
},
IsAuthDomainVerified: false,
IsDeleted: false,
Id: Guid_2,
CreatedBy: subject:me,

1
backend/tests/Squidex.Domain.Apps.Entities.Tests/Verify/TeamDomainObjectTests.ChangePlan_from_callback_should_create_events_and_update_plan.verified.txt

@ -10,6 +10,7 @@
Owner: subject:me,
PlanId: premium
},
IsAuthDomainVerified: false,
IsDeleted: false,
Id: Guid_1,
CreatedBy: subject:me,

1
backend/tests/Squidex.Domain.Apps.Entities.Tests/Verify/TeamDomainObjectTests.ChangePlan_from_callback_should_reset_plan_for_free_plan.verified.txt

@ -6,6 +6,7 @@
Contributors: {
me: Owner
},
IsAuthDomainVerified: false,
IsDeleted: false,
Id: Guid_1,
CreatedBy: subject:me,

1
backend/tests/Squidex.Domain.Apps.Entities.Tests/Verify/TeamDomainObjectTests.ChangePlan_should_create_events_and_update_plan.verified.txt

@ -10,6 +10,7 @@
Owner: subject:me,
PlanId: premium
},
IsAuthDomainVerified: false,
IsDeleted: false,
Id: Guid_1,
CreatedBy: subject:me,

1
backend/tests/Squidex.Domain.Apps.Entities.Tests/Verify/TeamDomainObjectTests.ChangePlan_should_not_call_billing_manager_for_callback.verified.txt

@ -10,6 +10,7 @@
Owner: subject:me,
PlanId: premium
},
IsAuthDomainVerified: false,
IsDeleted: false,
Id: Guid_1,
CreatedBy: subject:me,

1
backend/tests/Squidex.Domain.Apps.Entities.Tests/Verify/TeamDomainObjectTests.ChangePlan_should_not_make_update_for_redirect_result.verified.txt

@ -6,6 +6,7 @@
Contributors: {
me: Owner
},
IsAuthDomainVerified: false,
IsDeleted: false,
Id: Guid_1,
CreatedBy: subject:me,

1
backend/tests/Squidex.Domain.Apps.Entities.Tests/Verify/TeamDomainObjectTests.ChangePlan_should_reset_plan_for_free_plan.verified.txt

@ -6,6 +6,7 @@
Contributors: {
me: Owner
},
IsAuthDomainVerified: false,
IsDeleted: false,
Id: Guid_1,
CreatedBy: subject:me,

1
backend/tests/Squidex.Domain.Apps.Entities.Tests/Verify/TeamDomainObjectTests.Create_should_create_events_and_set_intitial_state.verified.txt

@ -6,6 +6,7 @@
Contributors: {
me: Owner
},
IsAuthDomainVerified: false,
IsDeleted: false,
Id: Guid_1,
CreatedBy: subject:me,

1
backend/tests/Squidex.Domain.Apps.Entities.Tests/Verify/TeamDomainObjectTests.Create_should_not_assign_client_as_contributor.verified.txt

@ -3,6 +3,7 @@
UniqueId: Guid_1,
Snapshot: {
Name: My Team,
IsAuthDomainVerified: false,
IsDeleted: false,
Id: Guid_1,
CreatedBy: client:client,

1
backend/tests/Squidex.Domain.Apps.Entities.Tests/Verify/TeamDomainObjectTests.DeleteTeam_should_create_events_and_update_deleted_flag.verified.txt

@ -6,6 +6,7 @@
Contributors: {
me: Owner
},
IsAuthDomainVerified: false,
IsDeleted: true,
Id: Guid_1,
CreatedBy: subject:me,

1
backend/tests/Squidex.Domain.Apps.Entities.Tests/Verify/TeamDomainObjectTests.RemoveContributor_should_create_events_and_remove_contributor.verified.txt

@ -3,6 +3,7 @@
Contributors: {
me: Owner
},
IsAuthDomainVerified: false,
IsDeleted: false,
Id: Guid_1,
CreatedBy: subject:me,

1
backend/tests/Squidex.Domain.Apps.Entities.Tests/Verify/TeamDomainObjectTests.Update_should_create_events_and_update_label_and_description.verified.txt

@ -6,6 +6,7 @@
Contributors: {
me: Owner
},
IsAuthDomainVerified: false,
IsDeleted: false,
Id: Guid_1,
CreatedBy: subject:me,

1
backend/tests/Squidex.Domain.Apps.Entities.Tests/Verify/TeamDomainObjectTests.UpsertAuth_should_create_events_and_remove_scheme.verified.txt

@ -6,6 +6,7 @@
Contributors: {
me: Owner
},
IsAuthDomainVerified: false,
IsDeleted: false,
Id: Guid_1,
CreatedBy: subject:me,

1
backend/tests/Squidex.Domain.Apps.Entities.Tests/Verify/TeamDomainObjectTests.UpsertAuth_should_create_events_and_update_scheme.verified.txt

@ -13,6 +13,7 @@
ClientSecret: clientSecret,
Authority: https://identity.squidex.io
},
IsAuthDomainVerified: false,
IsDeleted: false,
Id: Guid_1,
CreatedBy: subject:me,

41
backend/tests/Squidex.Domain.Apps.Entities.Tests/Verify/TeamDomainObjectTests.VerifyAuthDomain_should_create_events_and_verify_domain.verified.txt

@ -0,0 +1,41 @@
{
sut: {
UniqueId: Guid_1,
Snapshot: {
Name: My Team,
Contributors: {
me: Owner
},
AuthScheme: {
Domain: squidex.io,
DisplayName: Squidex,
ClientId: clientId,
ClientSecret: clientSecret,
Authority: https://identity.squidex.io
},
IsAuthDomainVerified: true,
IsDeleted: false,
Id: Guid_1,
CreatedBy: subject:me,
LastModifiedBy: subject:me,
Version: 3,
UniqueId: Guid_1
},
Version: 3,
ObjectState: Created
},
events: [
{
Headers: {
AggregateId: Guid_1,
EventId: Guid_2
},
Payload: {
Domain: squidex.io,
TeamId: Guid_1,
Actor: subject:me,
FromRule: false
}
}
]
}

42
frontend/src/app/features/teams/pages/auth/auth-page.component.html

@ -16,6 +16,48 @@
</div>
</div>
@if (isEditing() && isSaved()) {
<div class="card-body verification">
@if (isVerified()) {
<div class="alert alert-success mb-0">{{ "teams.auth.verifiedHint" | sqxTranslate }}</div>
} @else {
<div class="alert alert-warning">{{ "teams.auth.notVerifiedHint" | sqxTranslate }}</div>
<sqx-form-row for="verificationRecordName" label="teams.auth.verificationRecordName">
<div class="input-group">
<input class="form-control" id="verificationRecordName" #recordName readonly value="{{ verificationRecordName() }}" />
<button
class="btn btn-outline-secondary"
attr.aria-label="{{ 'common.copy' | sqxTranslate }}"
[sqxCopy]="recordName"
type="button">
<i class="icon-copy"></i>
</button>
</div>
</sqx-form-row>
<sqx-form-row for="verificationRecordValue" label="teams.auth.verificationRecordValue">
<div class="input-group">
<input class="form-control" id="verificationRecordValue" #recordValue readonly value="{{ verificationRecordValue() }}" />
<button
class="btn btn-outline-secondary"
attr.aria-label="{{ 'common.copy' | sqxTranslate }}"
[sqxCopy]="recordValue"
type="button">
<i class="icon-copy"></i>
</button>
</div>
</sqx-form-row>
@if (canVerify()) {
<button class="btn btn-primary" (click)="verify()" type="button">
{{ "teams.auth.verify" | sqxTranslate }}
</button>
}
}
</div>
}
@if (isEditing()) {
<form (ngSubmit)="save()">
<div class="card-body">

6
frontend/src/app/features/teams/pages/auth/auth-page.component.scss

@ -4,4 +4,8 @@
.card-header,
.card-footer {
padding: 1.25rem;
}
}
.verification {
border-bottom: 1px solid $color-border;
}

18
frontend/src/app/features/teams/pages/auth/auth-page.component.ts

@ -45,6 +45,16 @@ export class AuthPageComponent {
protected readonly isEditing = signal(false);
protected readonly canVerify = this.authState.canVerify;
protected readonly isVerified = this.authState.isVerified;
protected readonly verificationRecordName = this.authState.verificationRecordName;
protected readonly verificationRecordValue = this.authState.verificationRecordValue;
protected readonly isSaved = computed(() => !!this.authState.scheme());
protected readonly urlToRedirect = computed(() => {
const team = this.teamsState.selectedTeam();
if (!team) {
@ -84,6 +94,14 @@ export class AuthPageComponent {
}
}
protected verify() {
if (!this.canVerify()) {
return;
}
this.authState.verify();
}
protected save() {
if (!this.isEditable()) {
return;

33
frontend/src/app/features/teams/state/team-auth.state.spec.ts

@ -52,6 +52,10 @@ describe('TeamAuthState', () => {
expect(authState.snapshot.scheme).toEqual(scheme);
expect(authState.snapshot.isLoaded).toBeTruthy();
expect(authState.snapshot.canUpdate).toBeTruthy();
expect(authState.snapshot.canVerify).toBeTruthy();
expect(authState.snapshot.isVerified).toBeFalsy();
expect(authState.snapshot.verificationRecordName).toEqual('_squidex.squidex.io');
expect(authState.snapshot.verificationRecordValue).toEqual('squidex-team=42');
expect(authState.snapshot.version).toEqual(version);
dialogs.verify(x => x.notifyInfo(It.isAnyString()), Times.never());
});
@ -106,14 +110,35 @@ describe('TeamAuthState', () => {
expect(authState.snapshot.scheme).toEqual(newScheme);
expect(authState.snapshot.version).toEqual(newVersion);
});
it('should verify domain', () => {
authService.setup(x => x.verifyTeamAuth(It.isAny(), version))
.returns(() => of(versioned(newVersion, createAuthResponse(scheme, true)))).verifiable();
authState.verify().subscribe();
expect(authState.snapshot.isVerified).toBeTruthy();
expect(authState.snapshot.canVerify).toBeFalsy();
expect(authState.snapshot.version).toEqual(newVersion);
dialogs.verify(x => x.notifyInfo(It.isAnyString()), Times.once());
});
});
});
function createAuthResponse(scheme: AuthSchemeDto | undefined): AuthSchemeResponseDto {
function createAuthResponse(scheme: AuthSchemeDto | undefined, isVerified = false): AuthSchemeResponseDto {
const _links: Record<string, ResourceLinkDto> = {
update: new ResourceLinkDto({ method: 'PUT', href: 'teams/42/auth' }),
};
if (!isVerified) {
_links['verify'] = new ResourceLinkDto({ method: 'POST', href: 'teams/42/auth/verify' });
}
return new AuthSchemeResponseDto({
scheme,
_links: {
update: new ResourceLinkDto({ method: 'PUT', href: 'teams/42/auth' }),
},
isVerified,
verificationRecordName: '_squidex.squidex.io',
verificationRecordValue: 'squidex-team=42',
_links,
});
}

76
frontend/src/app/features/teams/state/team-auth.state.ts

@ -8,15 +8,30 @@
import { inject, Service } from '@angular/core';
import { Observable } from 'rxjs';
import { finalize, map, tap } from 'rxjs/operators';
import { AuthSchemeDto, AuthSchemeValueDto, debug, DialogService, LoadingState, shareSubscribed, State, TeamsService, TeamsState, VersionTag } from '@app/shared';
import { AuthSchemeDto, AuthSchemeResponseDto, AuthSchemeValueDto, debug, DialogService, LoadingState, shareSubscribed, State, TeamsService, TeamsState, VersionTag } from '@app/shared';
interface Snapshot extends LoadingState {
// The current scheme.
scheme?: AuthSchemeDto | null;
// The current response, needed for the links.
response?: AuthSchemeResponseDto;
// Indicates if the user can update the auth settings.
canUpdate?: boolean;
// Indicates if the user can verify the domain.
canVerify?: boolean;
// Indicates if the domain is verified.
isVerified?: boolean;
// The name of the DNS record to verify the domain.
verificationRecordName?: string;
// The value of the DNS record to verify the domain.
verificationRecordValue?: string;
// The team version.
version: VersionTag;
}
@ -33,6 +48,18 @@ export class TeamAuthState extends State<Snapshot> {
public readonly canUpdate =
this.project(x => x.canUpdate === true);
public readonly canVerify =
this.project(x => x.canVerify === true);
public readonly isVerified =
this.project(x => x.isVerified === true);
public readonly verificationRecordName =
this.project(x => x.verificationRecordName);
public readonly verificationRecordValue =
this.project(x => x.verificationRecordValue);
public readonly isLoaded =
this.project(x => x.isLoaded === true);
@ -66,14 +93,7 @@ export class TeamAuthState extends State<Snapshot> {
this.dialogs.notifyInfo('i18n:teams.auth.reloaded');
}
const { scheme, canUpdate } = payload;
this.next({
canUpdate,
isLoaded: true,
isLoading: false,
scheme,
version,
}, 'Loading Success');
this.replacePayload(payload, version, { isLoaded: true, isLoading: false }, 'Loading Success');
}),
finalize(() => {
this.next({ isLoading: false }, 'Loading Done');
@ -84,10 +104,7 @@ export class TeamAuthState extends State<Snapshot> {
public update(scheme: AuthSchemeDto | undefined): Observable<AuthSchemeDto | undefined | null> {
return this.teamService.putTeamAuth(this.teamId, AuthSchemeValueDto.fromJSON({ scheme }), this.version).pipe(
tap(({ version, payload }) => {
this.next({
...payload,
version,
}, 'Change');
this.replacePayload(payload, version, {}, 'Change');
}),
map(({ payload }) => {
return payload.scheme;
@ -95,7 +112,38 @@ export class TeamAuthState extends State<Snapshot> {
shareSubscribed(this.dialogs));
}
public verify(): Observable<any> {
const response = this.snapshot.response;
if (!response) {
throw new Error('Auth settings not loaded.');
}
return this.teamService.verifyTeamAuth(response, this.version).pipe(
tap(({ version, payload }) => {
this.dialogs.notifyInfo('i18n:teams.auth.verified');
this.replacePayload(payload, version, {}, 'Verified');
}),
shareSubscribed(this.dialogs));
}
private replacePayload(payload: AuthSchemeResponseDto, version: VersionTag, state: Partial<Snapshot>, event: string) {
const { canUpdate, canVerify, isVerified, scheme, verificationRecordName, verificationRecordValue } = payload;
this.next({
...state,
canUpdate,
canVerify,
isVerified,
response: payload,
scheme,
verificationRecordName,
verificationRecordValue,
version,
}, event);
}
private get version() {
return this.snapshot.version;
}
}
}

4
frontend/src/app/shared/model/custom.ts

@ -213,6 +213,10 @@ export class AuthSchemeResponseDto extends generated.AuthSchemeResponseDto {
public get canUpdate() {
return this.compute('canUpdate', () => hasAnyLink(this._links, 'update'));
}
public get canVerify() {
return this.compute('canVerify', () => hasAnyLink(this._links, 'verify'));
}
}
export class ClientDto extends generated.ClientDto {

22
frontend/src/app/shared/model/generated.ts

@ -1582,11 +1582,21 @@ export interface IUpdateTeamDto {
export class AuthSchemeResponseDto extends ResourceDto implements IAuthSchemeResponseDto {
/** The auth scheme if configured. */
readonly scheme?: AuthSchemeDto | undefined;
/** True, if the ownership of the domain has been verified. */
readonly isVerified!: boolean;
/** The name of the DNS TXT record to verify the ownership of the domain. */
readonly verificationRecordName?: string | undefined;
/** The value of the DNS TXT record to verify the ownership of the domain. */
readonly verificationRecordValue?: string | undefined;
public get canUpdate() {
return this.compute('canUpdate', () => hasAnyLink(this._links, 'update'));
}
public get canVerify() {
return this.compute('canVerify', () => hasAnyLink(this._links, 'verify'));
}
constructor(data?: IAuthSchemeResponseDto) {
super(data);
}
@ -1594,6 +1604,9 @@ export class AuthSchemeResponseDto extends ResourceDto implements IAuthSchemeRes
init(_data: any) {
super.init(_data);
(<any>this).scheme = _data["scheme"] ? AuthSchemeDto.fromJSON(_data["scheme"]) : <any>undefined;
(<any>this).isVerified = _data["isVerified"];
(<any>this).verificationRecordName = _data["verificationRecordName"];
(<any>this).verificationRecordValue = _data["verificationRecordValue"];
this.cleanup(this);
return this;
}
@ -1607,6 +1620,9 @@ export class AuthSchemeResponseDto extends ResourceDto implements IAuthSchemeRes
toJSON(data?: any) {
data = typeof data === 'object' ? data : {};
data["scheme"] = this.scheme ? this.scheme.toJSON() : <any>undefined;
data["isVerified"] = this.isVerified;
data["verificationRecordName"] = this.verificationRecordName;
data["verificationRecordValue"] = this.verificationRecordValue;
super.toJSON(data);
this.cleanup(data);
return data;
@ -1616,6 +1632,12 @@ export class AuthSchemeResponseDto extends ResourceDto implements IAuthSchemeRes
export interface IAuthSchemeResponseDto extends IResourceDto {
/** The auth scheme if configured. */
readonly scheme?: AuthSchemeDto | undefined;
/** True, if the ownership of the domain has been verified. */
readonly isVerified: boolean;
/** The name of the DNS TXT record to verify the ownership of the domain. */
readonly verificationRecordName?: string | undefined;
/** The value of the DNS TXT record to verify the ownership of the domain. */
readonly verificationRecordValue?: string | undefined;
}
export class AuthSchemeDto implements IAuthSchemeDto {

47
frontend/src/app/shared/services/teams.service.spec.ts

@ -156,6 +156,42 @@ describe('TeamsService', () => {
},
));
it('should make post request to verify auth domain', inject(
[TeamsService, HttpTestingController],
(teamsService: TeamsService, httpMock: HttpTestingController) => {
const resource: Resource = {
_links: {
verify: { method: 'POST', href: '/api/teams/my-team/auth/verify' },
},
};
let auth: Versioned<AuthSchemeResponseDto>;
teamsService
.verifyTeamAuth(resource, version)
.subscribe((result) => {
auth = result;
});
const req = httpMock.expectOne(
'http://service/p/api/teams/my-team/auth/verify',
);
expect(req.request.method).toEqual('POST');
expect(req.request.headers.get('If-Match')).toBe(version.value);
req.flush(teamAuthResponse(12), {
headers: {
etag: '2',
},
});
expect(auth!).toEqual({
payload: createTeamAuth(12),
version: new VersionTag('2'),
});
},
));
it('should make put request to update auth', inject(
[TeamsService, HttpTestingController],
(teamsService: TeamsService, httpMock: HttpTestingController) => {
@ -262,8 +298,12 @@ describe('TeamsService', () => {
clientSecret: 'client-secret',
authority: 'squidex.io/authority',
},
isVerified: false,
verificationRecordName: '_squidex.squidex.io',
verificationRecordValue: `squidex-team=${id}`,
_links: {
update: { method: 'PUT', href: `teams/${id}/auth` },
verify: { method: 'POST', href: `teams/${id}/auth/verify` },
},
};
}
@ -296,11 +336,18 @@ export function createTeamAuth(id: number) {
clientSecret: 'client-secret',
authority: 'squidex.io/authority',
}),
isVerified: false,
verificationRecordName: '_squidex.squidex.io',
verificationRecordValue: `squidex-team=${id}`,
_links: {
update: new ResourceLinkDto({
method: 'PUT',
href: `teams/${id}/auth`,
}),
verify: new ResourceLinkDto({
method: 'POST',
href: `teams/${id}/auth/verify`,
}),
},
});
}

12
frontend/src/app/shared/services/teams.service.ts

@ -79,6 +79,18 @@ export class TeamsService {
pretifyError('i18n:teams.teamLoadFailed'));
}
public verifyTeamAuth(resource: Resource, version: VersionOrTag): Observable<Versioned<AuthSchemeResponseDto>> {
const link = resource._links['verify'];
const url = this.apiUrl.buildUrl(link.href);
return HTTP.requestVersioned(this.http, link.method, url, version).pipe(
mapVersioned((payload) => {
return AuthSchemeResponseDto.fromJSON(payload.body);
}),
pretifyError('i18n:teams.auth.verifyFailed'));
}
public leaveTeam(teamId: string, resource: Resource): Observable<any> {
const link = resource._links['leave'];

Loading…
Cancel
Save