diff --git a/appinfo/app.php b/appinfo/app.php index 3a6d7de..998e3fc 100644 --- a/appinfo/app.php +++ b/appinfo/app.php @@ -24,7 +24,7 @@ require_once __DIR__ . '/../3rdparty/vendor/autoload.php'; // If we run in CLI mode do not setup the app as it can fail the OCC execution // since the URLGenerator isn't accessible. $cli = false; -if(OC::$CLI) { +if (OC::$CLI) { $cli = true; } try { @@ -70,7 +70,7 @@ $params = []; // Setting up the one login config may fail, if so, do not catch the requests later. $returnScript = false; $type = ''; -switch($config->getAppValue('user_saml', 'type')) { +switch ($config->getAppValue('user_saml', 'type')) { case 'saml': try { $oneLoginSettings = new \OneLogin\Saml2\Settings($samlSettings->getOneLoginSettingsArray(1)); @@ -96,7 +96,7 @@ if ($type === 'environment-variable') { OC_User::handleApacheAuth(); } -if($returnScript === true) { +if ($returnScript === true) { return; } @@ -122,7 +122,7 @@ if ($user !== null) { // All requests that are not authenticated and match against the "/login" route are // redirected to the SAML login endpoint -if(!$cli && +if (!$cli && !$userSession->isLoggedIn() && \OC::$server->getRequest()->getPathInfo() === '/login' && $type !== '') { @@ -145,10 +145,10 @@ if(!$cli && // UX (users don't have to reauthenticate) we default to disallow the access via // SAML at the moment. $useSamlForDesktopClients = $config->getAppValue('user_saml', 'general-use_saml_auth_for_desktop', '0'); -if($useSamlForDesktopClients === '1') { +if ($useSamlForDesktopClients === '1') { $currentUrl = substr(explode('?',$request->getRequestUri(), 2)[0], strlen(\OC::$WEBROOT)); - if(substr($currentUrl, 0, 12) === '/remote.php/' || substr($currentUrl, 0, 5) === '/ocs/') { - if(!$userSession->isLoggedIn() && $request->isUserAgent([\OCP\IRequest::USER_AGENT_CLIENT_DESKTOP])) { + if (substr($currentUrl, 0, 12) === '/remote.php/' || substr($currentUrl, 0, 5) === '/ocs/') { + if (!$userSession->isLoggedIn() && $request->isUserAgent([\OCP\IRequest::USER_AGENT_CLIENT_DESKTOP])) { $redirectSituation = true; if (preg_match('/^.*\/(\d+\.\d+\.\d+).*$/', $request->getHeader('USER_AGENT'), $matches) === 1) { @@ -173,7 +173,7 @@ if ($redirectSituation === true && $showLoginOptions) { // ignore exception when PUT is called since getParams cannot parse parameters in that case } $redirectUrl = ''; - if(isset($params['redirect_url'])) { + if (isset($params['redirect_url'])) { $redirectUrl = $params['redirect_url']; } @@ -185,17 +185,16 @@ if ($redirectSituation === true && $showLoginOptions) { ); header('Location: '.$targetUrl); exit(); - } -if($redirectSituation === true) { +if ($redirectSituation === true) { try { $params = $request->getParams(); } catch (\LogicException $e) { // ignore exception when PUT is called since getParams cannot parse parameters in that case } $originalUrl = ''; - if(isset($params['redirect_url'])) { + if (isset($params['redirect_url'])) { $originalUrl = $urlGenerator->getAbsoluteURL($params['redirect_url']); } diff --git a/lib/AppInfo/Application.php b/lib/AppInfo/Application.php index a56671e..975a095 100644 --- a/lib/AppInfo/Application.php +++ b/lib/AppInfo/Application.php @@ -28,7 +28,7 @@ use OCP\AppFramework\IAppContainer; use OCP\SabrePluginEvent; class Application extends App { - public function __construct(array $urlParams = array()) { + public function __construct(array $urlParams = []) { parent::__construct('user_saml', $urlParams); $container = $this->getContainer(); @@ -57,7 +57,6 @@ class Application extends App { } public function registerDavAuth() { - $container = $this->getContainer(); $dispatcher = $container->getServer()->getEventDispatcher(); @@ -74,7 +73,7 @@ class Application extends App { $config = $container->getServer()->getConfig(); $dispatcher = $container->getServer()->getEventDispatcher(); - $dispatcher->addListener('OCA\Files::loadAdditionalScripts', function() use ($session, $config, $userSession) { + $dispatcher->addListener('OCA\Files::loadAdditionalScripts', function () use ($session, $config, $userSession) { if (!$userSession->isLoggedIn()) { return; } diff --git a/lib/Controller/SAMLController.php b/lib/Controller/SAMLController.php index 33be675..d3f8573 100644 --- a/lib/Controller/SAMLController.php +++ b/lib/Controller/SAMLController.php @@ -38,8 +38,6 @@ use OCP\ILogger; use OCP\IRequest; use OCP\ISession; use OCP\IURLGenerator; -use OCP\IUser; -use OCP\IUserManager; use OCP\IUserSession; use OCP\Security\ICrypto; use OneLogin\Saml2\Auth; @@ -120,7 +118,7 @@ class SAMLController extends Controller { private function autoprovisionIfPossible() { $auth = $this->userData->getAttributes(); - if(!$this->userData->hasUidMappingAttribute()) { + if (!$this->userData->hasUidMappingAttribute()) { throw new NoUserFoundException('IDP parameter for the UID not found. Possible parameters are: ' . json_encode(array_keys($auth))); } @@ -142,17 +140,17 @@ class SAMLController extends Controller { return; } $autoProvisioningAllowed = $this->userBackend->autoprovisionAllowed(); - if($userExists) { - if($autoProvisioningAllowed) { + if ($userExists) { + if ($autoProvisioningAllowed) { $this->userBackend->updateAttributes($uid, $auth); } return; } $uid = $this->userData->getOriginalUid(); $uid = $this->userData->testEncodedObjectGUID($uid); - if(!$userExists && !$autoProvisioningAllowed) { + if (!$userExists && !$autoProvisioningAllowed) { throw new NoUserFoundException('Auto provisioning not allowed and user ' . $uid . ' does not exist'); - } elseif(!$userExists && $autoProvisioningAllowed) { + } elseif (!$userExists && $autoProvisioningAllowed) { $this->userBackend->createUserIfNotExists($uid, $auth); $this->userBackend->updateAttributes($uid, $auth); return; @@ -171,7 +169,7 @@ class SAMLController extends Controller { */ public function login($idp) { $type = $this->config->getAppValue($this->appName, 'type'); - switch($type) { + switch ($type) { case 'saml': $auth = new Auth($this->SAMLSettings->getOneLoginSettingsArray($idp)); $ssoUrl = $auth->login(null, [], false, false, true); @@ -182,7 +180,7 @@ class SAMLController extends Controller { if ($this->session->get(ClientFlowLoginController::STATE_NAME) !== null) { $flowData['cf1'] = $this->session->get(ClientFlowLoginController::STATE_NAME); - } else if ($this->session->get(ClientFlowLoginV2Controller::TOKEN_NAME) !== null) { + } elseif ($this->session->get(ClientFlowLoginV2Controller::TOKEN_NAME) !== null) { $flowData['cf2'] = [ 'token' => $this->session->get(ClientFlowLoginV2Controller::TOKEN_NAME), 'state' => $this->session->get(ClientFlowLoginV2Controller::STATE_NAME), @@ -291,18 +289,17 @@ class SAMLController extends Controller { if (isset($data['flow'])) { if (isset($data['flow']['cf1'])) { $this->session->set(ClientFlowLoginController::STATE_NAME, $data['flow']['cf1']); - } else if (isset($data['flow']['cf2'])) { + } elseif (isset($data['flow']['cf2'])) { $this->session->set(ClientFlowLoginV2Controller::TOKEN_NAME, $data['flow']['cf2']['token']); $this->session->set(ClientFlowLoginV2Controller::STATE_NAME, $data['flow']['cf2']['state']); } - } $AuthNRequestID = $data['AuthNRequestID']; $idp = $data['Idp']; // need to keep the IdP config ID during session lifetime (SAMLSettings::getPrefix) $this->session->set('user_saml.Idp', $idp); - if(is_null($AuthNRequestID) || $AuthNRequestID === '' || is_null($idp)) { + if (is_null($AuthNRequestID) || $AuthNRequestID === '' || is_null($idp)) { $this->logger->debug('Invalid auth payload', ['app' => 'user_saml']); return new Http\RedirectResponse($this->urlGenerator->getAbsoluteURL('/')); } @@ -315,7 +312,7 @@ class SAMLController extends Controller { $errors = $auth->getErrors(); if (!empty($errors)) { - foreach($errors as $error) { + foreach ($errors as $error) { $this->logger->error($error, ['app' => $this->appName]); } $this->logger->error($auth->getLastErrorReason(), ['app' => $this->appName]); @@ -363,14 +360,14 @@ class SAMLController extends Controller { } $originalUrl = $data['OriginalUrl']; - if($originalUrl !== null && $originalUrl !== '') { + if ($originalUrl !== null && $originalUrl !== '') { $response = new Http\RedirectResponse($originalUrl); } else { $response = new Http\RedirectResponse(\OC::$server->getURLGenerator()->getAbsoluteURL('/')); } // The Nextcloud desktop client expects a cookie with the key of "_shibsession" // to be there. - if($this->request->isUserAgent(['/^.*(mirall|csyncoC)\/.*$/'])) { + if ($this->request->isUserAgent(['/^.*(mirall|csyncoC)\/.*$/'])) { $response->addCookie('_shibsession_', 'authenticated'); } @@ -392,17 +389,17 @@ class SAMLController extends Controller { // Some IDPs send the SLO request via POST, but OneLogin php-saml only handles GET. // To hack around this issue we copy the request from _POST to _GET. - if(!empty($_POST['SAMLRequest'])) { + if (!empty($_POST['SAMLRequest'])) { $_GET['SAMLRequest'] = $_POST['SAMLRequest']; } $isFromIDP = !$isFromGS && !empty($_GET['SAMLRequest']); - if($isFromIDP) { + if ($isFromIDP) { // requests comes from the IDP so let it manage the logout // (or raise Error if request is invalid) - $pass = True ; - } elseif($isFromGS) { + $pass = true ; + } elseif ($isFromGS) { // Request is from master GlobalScale // Request validity is check via a JSON Web Token $jwt = $this->request->getParam('jwt', ''); @@ -412,7 +409,7 @@ class SAMLController extends Controller { $pass = $this->request->passesCSRFCheck(); } - if($pass) { + if ($pass) { $idp = $this->session->get('user_saml.Idp'); $auth = new Auth($this->SAMLSettings->getOneLoginSettingsArray($idp)); $stay = true ; // $auth will return the redirect URL but won't perform the redirect himself @@ -428,14 +425,14 @@ class SAMLController extends Controller { $errors = $auth->getErrors(); if (!empty($errors)) { - foreach($errors as $error) { + foreach ($errors as $error) { $this->logger->error($error, ['app' => $this->appName]); } $this->logger->error($auth->getLastErrorReason(), ['app' => $this->appName]); } } else { // If request is not from IDP, we send the logout request to the IDP - $parameters = array(); + $parameters = []; $nameId = $this->session->get('user_saml.samlNameId'); $nameIdFormat = $this->session->get('user_saml.samlNameIdFormat'); $nameIdNameQualifier = $this->session->get('user_saml.samlNameIdNameQualifier'); @@ -448,11 +445,11 @@ class SAMLController extends Controller { $this->userSession->logout(); } } - if(!empty($targetUrl) && !$auth->getLastErrorReason()){ + if (!empty($targetUrl) && !$auth->getLastErrorReason()) { $this->userSession->logout(); } } - if(empty($targetUrl)){ + if (empty($targetUrl)) { $targetUrl = $this->urlGenerator->getAbsoluteURL('/'); } @@ -491,7 +488,6 @@ class SAMLController extends Controller { * @return Http\TemplateResponse */ public function selectUserBackEnd($redirectUrl) { - $attributes = ['loginUrls' => []]; if ($this->SAMLSettings->allowMultipleUserBackEnds()) { @@ -543,9 +539,8 @@ class SAMLController extends Controller { * @return string */ private function getSSOUrl($redirectUrl, $idp) { - $originalUrl = ''; - if(!empty($redirectUrl)) { + if (!empty($redirectUrl)) { $originalUrl = $this->urlGenerator->getAbsoluteURL($redirectUrl); } @@ -561,7 +556,6 @@ class SAMLController extends Controller { ); return $ssoUrl; - } /** @@ -612,5 +606,4 @@ class SAMLController extends Controller { $message = $this->l->t('This page should not be visited directly.'); return new Http\TemplateResponse($this->appName, 'error', ['message' => $message], 'guest'); } - } diff --git a/lib/Controller/SettingsController.php b/lib/Controller/SettingsController.php index fb76ef5..58f2361 100644 --- a/lib/Controller/SettingsController.php +++ b/lib/Controller/SettingsController.php @@ -116,5 +116,4 @@ class SettingsController extends Controller { } return new Response(); } - } diff --git a/lib/Controller/TimezoneController.php b/lib/Controller/TimezoneController.php index 46218c7..cadafe1 100644 --- a/lib/Controller/TimezoneController.php +++ b/lib/Controller/TimezoneController.php @@ -1,4 +1,5 @@ diff --git a/lib/DavPlugin.php b/lib/DavPlugin.php index 5340760..59285c4 100644 --- a/lib/DavPlugin.php +++ b/lib/DavPlugin.php @@ -24,11 +24,8 @@ namespace OCA\User_SAML; use OCA\DAV\Connector\Sabre\Auth; use OCP\IConfig; use OCP\ISession; -use Sabre\DAV\CorePlugin; -use Sabre\DAV\FS\Directory; use Sabre\DAV\Server; use Sabre\DAV\ServerPlugin; -use Sabre\DAV\Tree; use Sabre\HTTP\RequestInterface; use Sabre\HTTP\ResponseInterface; diff --git a/lib/Middleware/OnlyLoggedInMiddleware.php b/lib/Middleware/OnlyLoggedInMiddleware.php index 6a3bfdf..d46c03a 100644 --- a/lib/Middleware/OnlyLoggedInMiddleware.php +++ b/lib/Middleware/OnlyLoggedInMiddleware.php @@ -21,7 +21,6 @@ namespace OCA\User_SAML\Middleware; -use OCP\AppFramework\Http\JSONResponse; use OCP\AppFramework\Http\RedirectResponse; use OCP\AppFramework\Middleware; use OCP\AppFramework\Utility\IControllerMethodReflector; @@ -61,8 +60,8 @@ class OnlyLoggedInMiddleware extends Middleware { * @param string $methodName * @throws \Exception */ - public function beforeController($controller, $methodName){ - if($this->reflector->hasAnnotation('OnlyUnauthenticatedUsers') && $this->userSession->isLoggedIn()) { + public function beforeController($controller, $methodName) { + if ($this->reflector->hasAnnotation('OnlyUnauthenticatedUsers') && $this->userSession->isLoggedIn()) { throw new \Exception('User is already logged-in'); } } @@ -75,7 +74,7 @@ class OnlyLoggedInMiddleware extends Middleware { * @throws \Exception */ public function afterException($controller, $methodName, \Exception $exception) { - if($exception->getMessage() === 'User is already logged-in') { + if ($exception->getMessage() === 'User is already logged-in') { return new RedirectResponse($this->urlGenerator->getAbsoluteURL('/')); } diff --git a/lib/SAMLSettings.php b/lib/SAMLSettings.php index 29a6839..efc35bb 100644 --- a/lib/SAMLSettings.php +++ b/lib/SAMLSettings.php @@ -21,7 +21,6 @@ namespace OCA\User_SAML; -use OCP\AppFramework\Http; use OCP\IConfig; use OCP\IRequest; use OCP\ISession; @@ -99,7 +98,6 @@ class SAMLSettings { * @return array */ public function getOneLoginSettingsArray($idp) { - $prefix = ''; if ($idp > 1) { $prefix = $idp . '-'; @@ -142,20 +140,20 @@ class SAMLSettings { $spx509cert = $this->config->getAppValue('user_saml', $prefix . 'sp-x509cert', ''); $spxprivateKey = $this->config->getAppValue('user_saml', $prefix . 'sp-privateKey', ''); - if($spx509cert !== '') { + if ($spx509cert !== '') { $settings['sp']['x509cert'] = $spx509cert; } - if($spxprivateKey !== '') { + if ($spxprivateKey !== '') { $settings['sp']['privateKey'] = $spxprivateKey; } $idpx509cert = $this->config->getAppValue('user_saml', $prefix . 'idp-x509cert', ''); - if($idpx509cert !== '') { + if ($idpx509cert !== '') { $settings['idp']['x509cert'] = $idpx509cert; } $slo = $this->config->getAppValue('user_saml', $prefix . 'idp-singleLogoutService.url', ''); - if($slo !== '') { + if ($slo !== '') { $settings['idp']['singleLogoutService'] = [ 'url' => $this->config->getAppValue('user_saml', $prefix . 'idp-singleLogoutService.url', ''), ]; @@ -164,7 +162,7 @@ class SAMLSettings { ]; $sloResponseUrl = $this->config->getAppValue('user_saml', $prefix . 'idp-singleLogoutService.responseUrl', ''); - if($sloResponseUrl !== '') { + if ($sloResponseUrl !== '') { $settings['idp']['singleLogoutService']['responseUrl'] = $sloResponseUrl; } } @@ -179,7 +177,6 @@ class SAMLSettings { * @return string */ public function getPrefix($setting = '') { - $prefix = ''; if (!empty($setting) && in_array($setting, $this->globalSettings)) { return $prefix; @@ -192,5 +189,4 @@ class SAMLSettings { return $prefix; } - } diff --git a/lib/Settings/Admin.php b/lib/Settings/Admin.php index 5ed13dc..9423ad0 100644 --- a/lib/Settings/Admin.php +++ b/lib/Settings/Admin.php @@ -64,7 +64,7 @@ class Admin implements ISettings { $providers[] = [ 'id' => $id, 'name' => $name === '' ? $this->l10n->t('Provider ') . $id : $name - ]; + ]; } $serviceProviderFields = [ 'x509cert' => $this->l10n->t('X.509 certificate of the Service Provider'), @@ -86,7 +86,7 @@ class Admin implements ISettings { 'wantXMLValidation' => $this->l10n->t('Indicates if the SP will validate all received XML.'), ]; $securityGeneral = [ - 'lowercaseUrlencoding' => $this->l10n->t('ADFS URL-Encodes SAML data as lowercase, and the toolkit by default uses uppercase. Enable for ADFS compatibility on signature verification.'), + 'lowercaseUrlencoding' => $this->l10n->t('ADFS URL-Encodes SAML data as lowercase, and the toolkit by default uses uppercase. Enable for ADFS compatibility on signature verification.'), 'signatureAlgorithm' => [ 'type' => 'line', 'text' => $this->l10n->t('Algorithm that the toolkit will use on signing process.') @@ -175,7 +175,7 @@ class Admin implements ISettings { ]; $type = $this->config->getAppValue('user_saml', 'type'); - if($type === 'saml') { + if ($type === 'saml') { $generalSettings['use_saml_auth_for_desktop'] = [ 'text' => $this->l10n->t('Use SAML auth for the %s desktop clients (requires user re-authentication)', [$this->defaults->getName()]), 'type' => 'checkbox', @@ -226,5 +226,4 @@ class Admin implements ISettings { public function getPriority() { return 0; } - } diff --git a/lib/UserBackend.php b/lib/UserBackend.php index c33fac2..d7c1f3a 100644 --- a/lib/UserBackend.php +++ b/lib/UserBackend.php @@ -35,7 +35,6 @@ use OCP\IConfig; use OCP\IURLGenerator; use OCP\ISession; use Symfony\Component\EventDispatcher\GenericEvent; -use function base64_decode; class UserBackend implements IApacheBackend, UserInterface, IUserBackend { /** @var IConfig */ @@ -108,8 +107,8 @@ class UserBackend implements IApacheBackend, UserInterface, IUserBackend { * @param string $uid * @param array $attributes */ - public function createUserIfNotExists($uid, array $attributes = array()) { - if(!$this->userExistsInDatabase($uid)) { + public function createUserIfNotExists($uid, array $attributes = []) { + if (!$this->userExistsInDatabase($uid)) { $values = [ 'uid' => $uid, ]; @@ -124,12 +123,12 @@ class UserBackend implements IApacheBackend, UserInterface, IUserBackend { if ($home !== '') { //if attribute's value is an absolute path take this, otherwise append it to data dir //check for / at the beginning or pattern c:\ resp. c:/ - if( '/' !== $home[0] + if ('/' !== $home[0] && !(3 < strlen($home) && ctype_alpha($home[0]) && $home[1] === ':' && ('\\' === $home[2] || '/' === $home[2])) ) { $home = $this->config->getSystemValue('datadirectory', - \OC::$SERVERROOT.'/data' ) . '/' . $home; + \OC::$SERVERROOT.'/data') . '/' . $home; } $values['home'] = $home; @@ -138,13 +137,12 @@ class UserBackend implements IApacheBackend, UserInterface, IUserBackend { /* @var $qb IQueryBuilder */ $qb = $this->db->getQueryBuilder(); $qb->insert('user_saml_users'); - foreach($values as $column => $value) { + foreach ($values as $column => $value) { $qb->setValue($column, $qb->createNamedParameter($value)); } $qb->execute(); $this->initializeHomeDir($uid); - } } @@ -204,8 +202,8 @@ class UserBackend implements IApacheBackend, UserInterface, IUserBackend { $data = $result->fetchAll(); $result->closeCursor(); - foreach($data as $passwords) { - if(password_verify($password, $passwords['token'])) { + foreach ($data as $passwords) { + if (password_verify($password, $passwords['token'])) { return $uid; } } @@ -220,7 +218,7 @@ class UserBackend implements IApacheBackend, UserInterface, IUserBackend { * @since 4.5.0 */ public function deleteUser($uid) { - if($this->userExistsInDatabase($uid)) { + if ($this->userExistsInDatabase($uid)) { /* @var $qb IQueryBuilder */ $qb = $this->db->getQueryBuilder(); $qb->delete('user_saml_users') @@ -238,7 +236,7 @@ class UserBackend implements IApacheBackend, UserInterface, IUserBackend { * @return string */ public function getHome($uid) { - if($this->userExistsInDatabase($uid)) { + if ($this->userExistsInDatabase($uid)) { $qb = $this->db->getQueryBuilder(); $qb->select('home') ->from('user_saml_users') @@ -278,7 +276,7 @@ class UserBackend implements IApacheBackend, UserInterface, IUserBackend { * @since 4.5.0 */ public function userExists($uid) { - if($backend = $this->getActualUserBackend($uid)) { + if ($backend = $this->getActualUserBackend($uid)) { return $backend->userExists($uid); } else { return $this->userExistsInDatabase($uid); @@ -286,7 +284,7 @@ class UserBackend implements IApacheBackend, UserInterface, IUserBackend { } public function setDisplayName($uid, $displayName) { - if($backend = $this->getActualUserBackend($uid)) { + if ($backend = $this->getActualUserBackend($uid)) { return $backend->setDisplayName($uid, $displayName); } @@ -310,10 +308,10 @@ class UserBackend implements IApacheBackend, UserInterface, IUserBackend { * @since 4.5.0 */ public function getDisplayName($uid) { - if($backend = $this->getActualUserBackend($uid)) { + if ($backend = $this->getActualUserBackend($uid)) { return $backend->getDisplayName($uid); } else { - if($this->userExistsInDatabase($uid)) { + if ($this->userExistsInDatabase($uid)) { $qb = $this->db->getQueryBuilder(); $qb->select('displayname') ->from('user_saml_users') @@ -375,7 +373,7 @@ class UserBackend implements IApacheBackend, UserInterface, IUserBackend { * @since 4.5.0 */ public function hasUserListings() { - if($this->autoprovisionAllowed()) { + if ($this->autoprovisionAllowed()) { return true; } @@ -398,7 +396,7 @@ class UserBackend implements IApacheBackend, UserInterface, IUserBackend { public function getLogoutUrl() { $prefix = $this->settings->getPrefix(); $slo = $this->config->getAppValue('user_saml', $prefix . 'idp-singleLogoutService.url', ''); - if($slo === '') { + if ($slo === '') { return ''; } @@ -486,14 +484,14 @@ class UserBackend implements IApacheBackend, UserInterface, IUserBackend { public function getCurrentUserId() { $user = \OC::$server->getUserSession()->getUser(); - if($user instanceof IUser && $this->session->get('user_saml.samlUserData')) { + if ($user instanceof IUser && $this->session->get('user_saml.samlUserData')) { $uid = $user->getUID(); } else { $this->userData->setAttributes($this->session->get('user_saml.samlUserData') ?? []); $uid = $this->userData->getEffectiveUid(); } - if($uid !== '' && $this->userExists($uid)) { + if ($uid !== '' && $this->userExists($uid)) { $this->session->set('last-password-confirm', strtotime('+4 year', time())); return $uid; } @@ -526,8 +524,8 @@ class UserBackend implements IApacheBackend, UserInterface, IUserBackend { * @return null|UserInterface */ public function getActualUserBackend($uid) { - foreach(self::$backends as $backend) { - if($backend->userExists($uid)) { + foreach (self::$backends as $backend) { + if ($backend->userExists($uid)) { return $backend; } } @@ -545,8 +543,7 @@ class UserBackend implements IApacheBackend, UserInterface, IUserBackend { self::$backends = $backends; } - private function getAttributeKeys($name) - { + private function getAttributeKeys($name) { $prefix = $this->settings->getPrefix($name); $keys = explode(' ', $this->config->getAppValue('user_saml', $prefix . $name, '')); @@ -560,17 +557,17 @@ class UserBackend implements IApacheBackend, UserInterface, IUserBackend { $keys = $this->getAttributeKeys($name); $value = ''; - foreach($keys as $key) { + foreach ($keys as $key) { if (isset($attributes[$key])) { if (is_array($attributes[$key])) { foreach ($attributes[$key] as $attribute_part_value) { - if($value !== '') { + if ($value !== '') { $value .= ' '; } $value .= $attribute_part_value; } } else { - if($value !== '') { + if ($value !== '') { $value .= ' '; } $value .= $attributes[$key]; @@ -584,8 +581,8 @@ class UserBackend implements IApacheBackend, UserInterface, IUserBackend { private function getAttributeArrayValue($name, array $attributes) { $keys = $this->getAttributeKeys($name); - $value = array(); - foreach($keys as $key) { + $value = []; + foreach ($keys as $key) { if (isset($attributes[$key])) { if (is_array($attributes[$key])) { $value = array_merge($value, array_values($attributes[$key])); diff --git a/lib/UserData.php b/lib/UserData.php index 098a9be..01613c4 100644 --- a/lib/UserData.php +++ b/lib/UserData.php @@ -1,4 +1,5 @@ @@ -67,7 +68,7 @@ class UserData { } public function getEffectiveUid(): string { - if($this->uid !== null) { + if ($this->uid !== null) { return $this->uid; } $this->assertIsInitialized(); @@ -85,7 +86,7 @@ class UserData { protected function extractSamlUserId(): string { $prefix = $this->samlSettings->getPrefix(); $uidMapping = $this->config->getAppValue('user_saml', $prefix . 'general-uid_mapping'); - if(isset($this->attributes[$uidMapping])) { + if (isset($this->attributes[$uidMapping])) { if (is_array($this->attributes[$uidMapping])) { return trim($this->attributes[$uidMapping][0]); } else { @@ -107,13 +108,13 @@ class UserData { } $candidate = base64_decode($uid, true); - if($candidate === false) { + if ($candidate === false) { return $uid; } $candidate = $this->convertObjectGUID2Str($candidate); // the regex only matches the structure of the UUID, not its semantic // (i.e. version or variant) simply to be future compatible - if(preg_match('/^[a-f0-9]{8}(-[a-f0-9]{4}){4}[a-f0-9]{8}$/i', $candidate) === 1) { + if (preg_match('/^[a-f0-9]{8}(-[a-f0-9]{4}){4}[a-f0-9]{8}$/i', $candidate) === 1) { $uid = $candidate; } return $uid; @@ -125,15 +126,15 @@ class UserData { protected function convertObjectGUID2Str($oguid): string { $hex_guid = bin2hex($oguid); $hex_guid_to_guid_str = ''; - for($k = 1; $k <= 4; ++$k) { + for ($k = 1; $k <= 4; ++$k) { $hex_guid_to_guid_str .= substr($hex_guid, 8 - 2 * $k, 2); } $hex_guid_to_guid_str .= '-'; - for($k = 1; $k <= 2; ++$k) { + for ($k = 1; $k <= 2; ++$k) { $hex_guid_to_guid_str .= substr($hex_guid, 12 - 2 * $k, 2); } $hex_guid_to_guid_str .= '-'; - for($k = 1; $k <= 2; ++$k) { + for ($k = 1; $k <= 2; ++$k) { $hex_guid_to_guid_str .= substr($hex_guid, 16 - 2 * $k, 2); } $hex_guid_to_guid_str .= '-' . substr($hex_guid, 16, 4); @@ -143,7 +144,7 @@ class UserData { } protected function assertIsInitialized() { - if($this->attributes === null) { + if ($this->attributes === null) { throw new \LogicException('UserData have to be initialized with setAttributes first'); } } diff --git a/lib/UserResolver.php b/lib/UserResolver.php index 8a0c43b..d65daa1 100644 --- a/lib/UserResolver.php +++ b/lib/UserResolver.php @@ -1,4 +1,5 @@ @@ -40,18 +41,18 @@ class UserResolver { * @throws NoUserFoundException */ public function findExistingUserId(string $rawUidCandidate, bool $force = false): string { - if($force) { + if ($force) { $this->ensureUser($rawUidCandidate); } - if($this->userManager->userExists($rawUidCandidate)) { + if ($this->userManager->userExists($rawUidCandidate)) { return $rawUidCandidate; } try { $sanitized = $this->sanitizeUserIdCandidate($rawUidCandidate); - } catch(\InvalidArgumentException $e) { + } catch (\InvalidArgumentException $e) { $sanitized = ''; } - if($this->userManager->userExists($sanitized)) { + if ($this->userManager->userExists($sanitized)) { return $sanitized; } throw new NoUserFoundException('User' . $rawUidCandidate . ' not valid or not found'); @@ -63,7 +64,7 @@ class UserResolver { public function findExistingUser(string $rawUidCandidate): IUser { $uid = $this->findExistingUserId($rawUidCandidate); $user = $this->userManager->get($uid); - if($user === null) { + if ($user === null) { throw new NoUserFoundException('User' . $rawUidCandidate . ' not valid or not found'); } return $user; @@ -73,7 +74,7 @@ class UserResolver { try { $this->findExistingUserId($uid, $force); return true; - } catch(NoUserFoundException $e) { + } catch (NoUserFoundException $e) { return false; } } @@ -91,7 +92,7 @@ class UserResolver { // Transliteration to ASCII $transliterated = @iconv('UTF-8', 'ASCII//TRANSLIT', $sanitized); - if($transliterated !== false) { + if ($transliterated !== false) { // depending on system config iconv can work or not $sanitized = $transliterated; } @@ -102,7 +103,7 @@ class UserResolver { // Every remaining disallowed characters will be removed $sanitized = preg_replace('/[^a-zA-Z0-9_.@-]/u', '', $sanitized); - if($sanitized === '') { + if ($sanitized === '') { throw new \InvalidArgumentException('provided name template for username does not contain any allowed characters'); } diff --git a/templates/admin.php b/templates/admin.php index 6d1b754..4d03984 100644 --- a/templates/admin.php +++ b/templates/admin.php @@ -52,15 +52,15 @@ style('user_saml', 'admin');