From ce4bab88b1ac2abec88b6dcf0b1e5153fc20809b Mon Sep 17 00:00:00 2001 From: nebulon42 Date: Mon, 29 Aug 2022 19:52:19 +0200 Subject: [PATCH] add setting to allow using user ID from identity provider instead of e-mail address as Matomo user ID (fixes #65) --- Controller.php | 28 +++++++++++++++++++--------- SystemSettings.php | 22 ++++++++++++++++++++++ lang/de.json | 3 +++ lang/en.json | 3 +++ lang/fr.json | 3 +++ 5 files changed, 50 insertions(+), 9 deletions(-) diff --git a/Controller.php b/Controller.php index 8565c11..ac12278 100644 --- a/Controller.php +++ b/Controller.php @@ -361,21 +361,31 @@ private function isPluginSetup($settings) : bool * * @param SystemSettings $settings * @param string $providerUserId Remote user id - * @param string $matomoUserLogin Users email address, will be used as username as well + * @param string $providerEmail Users email address * @return void */ - private function signupUser($settings, string $providerUserId, string $matomoUserLogin = null) + private function signupUser($settings, string $providerUserId, string $providerEmail = null) { // only sign up user if setting is enabled if ($settings->allowSignup->getValue()) { // verify response contains email address - if (empty($matomoUserLogin)) { + if (empty($providerEmail)) { throw new Exception(Piwik::translate("LoginOIDC_ExceptionUserNotFoundAndNoEmail")); } + if (empty($providerUserId)) { + throw new Exception(Piwik::translate("LoginOIDC_ExceptionUserNotFoundAndNoUserId")); + } + + if ($settings->useEmailAsUsername->getValue()) { + $userId = $providerEmail; + } else { + $userId = $providerUserId; + } + // verify email address domain is allowed to sign up if (!empty($settings->allowedSignupDomains->getValue())) { - $signupDomain = substr($matomoUserLogin, strpos($matomoUserLogin, "@") + 1); + $signupDomain = substr($providerEmail, strpos($providerEmail, "@") + 1); $allowedDomains = explode("\n", $settings->allowedSignupDomains->getValue()); if (!in_array($signupDomain, $allowedDomains)) { throw new Exception(Piwik::translate("LoginOIDC_ExceptionAllowedSignupDomainsDenied")); @@ -383,16 +393,16 @@ private function signupUser($settings, string $providerUserId, string $matomoUse } // set an invalid pre-hashed password, to block the user from logging in by password - Access::getInstance()->doAsSuperUser(function () use ($matomoUserLogin, $result) { - UsersManagerApi::getInstance()->addUser($matomoUserLogin, + Access::getInstance()->doAsSuperUser(function () use ($userId, $providerEmail, $result) { + UsersManagerApi::getInstance()->addUser($userId, "(disallow password login)", - $matomoUserLogin, + $providerEmail, /* $_isPasswordHashed = */ true, /* $initialIdSite = */ null); }); $userModel = new Model(); - $user = $userModel->getUser($matomoUserLogin); - $this->linkAccount($providerUserId, $matomoUserLogin); + $user = $userModel->getUser($userId); + $this->linkAccount($providerUserId, $userId); $this->signinAndRedirect($user, $settings); } else { throw new Exception(Piwik::translate("LoginOIDC_ExceptionUserNotFoundAndSignupDisabled")); diff --git a/SystemSettings.php b/SystemSettings.php index 08f2d2e..b541f0a 100644 --- a/SystemSettings.php +++ b/SystemSettings.php @@ -104,6 +104,13 @@ class SystemSettings extends \Piwik\Settings\Plugin\SystemSettings */ public $userinfoId; + /** + * Use the e-mail address as username. + * + * @var bool + */ + public $useEmailAsUsername; + /** * The client id given by the provider. * @@ -158,6 +165,7 @@ protected function init() $this->userinfoUrl = $this->createUserinfoUrlSetting(); $this->endSessionUrl = $this->createEndSessionUrlSetting(); $this->userinfoId = $this->createUserinfoIdSetting(); + $this->useEmailAsUsername = $this->createUseEmailAsUsernameSetting(); $this->clientId = $this->createClientIdSetting(); $this->clientSecret = $this->createClientSecretSetting(); $this->scope = $this->createScopeSetting(); @@ -337,6 +345,20 @@ private function createUserinfoIdSetting() : SystemSetting }); } + /** + * Add useEmailAsUsername setting. + * + * @return SystemSetting + */ + private function createUseEmailAsUsernameSetting() : SystemSetting + { + return $this->makeSetting("useEmailAsUsername", $default = true, FieldConfig::TYPE_BOOL, function(FieldConfig $field) { + $field->title = Piwik::translate("LoginOIDC_SettingUseEmailAsUsername"); + $field->description = Piwik::translate("LoginOIDC_SettingUseEmailAsUsernameHelp"); + $field->uiControl = FieldConfig::UI_CONTROL_CHECKBOX; + }); + } + /** * Add client id setting. * diff --git a/lang/de.json b/lang/de.json index 3d1d44c..ebd578c 100644 --- a/lang/de.json +++ b/lang/de.json @@ -20,6 +20,8 @@ "SettingEndSessionUrlHelp": "Nach dem Logout wird der Benutzer zu dieser URL weitergeleitet, damit die Session beim Provider beendet wird. Bei Unklarheit sollte dieses Feld freigelassen werden.", "SettingUserinfoId": "Userinfo ID", "SettingUserinfoIdHelp": "Name des Feldes, in dem die Benutzer-ID enthalten ist. Normalerweise, für OpenID Connect Dienste wie Auth0, ist das 'sub'. Github gibt die eindeutige Benutzer-ID in dem Feld 'id' an.", + "SettingUseEmailAsUsername": "E-Mail Adresse als Benutzer-ID verwenden", + "SettingUseEmailAsUsernameHelp": "Verwendet die E-Mail-Adresse des OpenID Connect Providers als Matomo Benutzer-ID.", "SettingClientId": "Client ID", "SettingClientIdHelp": "", "SettingClientSecret": "Client Secret", @@ -44,6 +46,7 @@ "ExceptionInvalidResponse": "Unerwartete Antwort vom OAuth-Service.", "ExceptionUserNotFoundAndSignupDisabled": "Benutzer nicht gefunden. Neue Registrierungen über OAuth werden nicht unterstützt.", "ExceptionUserNotFoundAndNoEmail": "Benutzer nicht gefunden. Benutzer konnte nicht erstellt werden, weil der OAuth Service keine E-Mail Adresse zurückgab.", + "ExceptionUserNotFoundAndNoUserId": "Benutzer nicht gefunden. Benutzer konnte nicht erstellt werden, weil der OAuth Service keine Benutzer-ID zurückgab.", "ExceptionSuperUserOauthDisabled": "OAuth Login für Superuser ist deaktiviert.", "ExceptionAllowedSignupDomainsValidationFailed": "Die Liste der zugelassenen Domains hat nicht das richtige Format.", "ExceptionAllowedSignupDomainsDenied": "Die verwendete Domain ist nicht für Registrierungen freigeschaltet.", diff --git a/lang/en.json b/lang/en.json index 411697c..0847df8 100644 --- a/lang/en.json +++ b/lang/en.json @@ -22,6 +22,8 @@ "SettingEndSessionUrlHelp": "After logging out, the user is redirected to this URL to end the session at the provider. If you are unsure, just leave this field empty.", "SettingUserinfoId": "Userinfo ID", "SettingUserinfoIdHelp": "Name of the unique user id field in the userinfo response. Usually for OpenID Connect services like Auth0 this is 'sub'. Github provides the user id in 'id'.", + "SettingUseEmailAsUsername": "Use e-mail address as username", + "SettingUseEmailAsUsernameHelp": "Uses the e-mail address from the OpenID Connect provider as Matomo username.", "SettingClientId": "Client ID", "SettingClientIdHelp": "", "SettingClientSecret": "Client Secret", @@ -46,6 +48,7 @@ "ExceptionInvalidResponse": "Unexpected response from OAuth service.", "ExceptionUserNotFoundAndSignupDisabled": "User not found. OAuth registrations are disabled.", "ExceptionUserNotFoundAndNoEmail": "User not found. User could not be created because the OAuth service did not return an email address.", + "ExceptionUserNotFoundAndNoUserId": "User not found. User could not be created because the OAuth service did not return a user ID.", "ExceptionSuperUserOauthDisabled": "OAuth login disabled for superusers.", "ExceptionAllowedSignupDomainsValidationFailed": "Validation failed for the list of domains allowed for user creation.", "ExceptionAllowedSignupDomainsDenied": "The domain is currently not activated for account creation.", diff --git a/lang/fr.json b/lang/fr.json index 7820f3b..0b8bcfc 100644 --- a/lang/fr.json +++ b/lang/fr.json @@ -20,6 +20,8 @@ "SettingEndSessionUrlHelp": "", "SettingUserinfoId": "ID Userinfo", "SettingUserinfoIdHelp": "Nom du champ de l'identifiant unique utilisateur dans la réponse 'userinfo'. Habituellement, pour les services de connexion OpenID Connect comme Auth0, il s'agit de 'sub'. Github fourni l'identifiant utilisateur avec 'id'.", + "SettingUseEmailAsUsername": "Utiliser l'adresse e-mail comme nom d'utilisateur", + "SettingUseEmailAsUsernameHelp": "Utilise l'adresse e-mail du fournisseur OpenID Connect comme nom d'utilisateur Matomo.", "SettingClientId": "Client ID", "SettingClientIdHelp": "", "SettingClientSecret": "Client Secret", @@ -42,6 +44,7 @@ "ExceptionInvalidResponse": "Réponse inattendue du service OAuth.", "ExceptionUserNotFoundAndSignupDisabled": "Utilisateur non trouvé. Les nouvelles inscriptions via OAuth sont désactivées.", "ExceptionUserNotFoundAndNoEmail": "Utilisateur non trouvé. L'utilisateur n'a pas pu être créé car le service OAuth n'a pas renvoyé d'adresse e-mail.", + "ExceptionUserNotFoundAndNoUserId": "Utilisateur non trouvé. L'utilisateur n'a pas pu être créé car le service OAuth n'a pas renvoyé d'ID utilisateur.", "ExceptionSuperUserOauthDisabled": "La connexion OAuth pour les Supers Utilisateurs est désactivée.", "ExceptionAllowedSignupDomainsValidationFailed": "La validation a échoué pour la liste des domaines autorisés pour la création d'utilisateurs.", "ExceptionAllowedSignupDomainsDenied": "Le domaine n'est pas activé pour la création d'un compte.",