diff --git a/phpstan.neon b/phpstan.neon index bce03bcc..faa85406 100644 --- a/phpstan.neon +++ b/phpstan.neon @@ -1,5 +1,5 @@ parameters: - level: 1 + level: 5 paths: - src excludePaths: diff --git a/src/User/Bootstrap.php b/src/User/Bootstrap.php index 1b92e446..2bd40719 100755 --- a/src/User/Bootstrap.php +++ b/src/User/Bootstrap.php @@ -15,10 +15,12 @@ use Da\User\Contracts\AuthManagerInterface; use Da\User\Controller\SecurityController; use Da\User\Event\FormEvent; +use Da\User\Form\LoginForm; use Da\User\Helper\ClassMapHelper; use Da\User\Model\SessionHistory; use Da\User\Model\User; use Da\User\Search\SessionHistorySearch; +use Da\User\Traits\ModuleAwareTrait; use Yii; use yii\authclient\Collection; use yii\base\Application; @@ -37,6 +39,8 @@ */ class Bootstrap implements BootstrapInterface { + use ModuleAwareTrait; + /** * {@inheritdoc} * @@ -57,7 +61,9 @@ public function bootstrap($app) $this->initAuthCollection($app); $this->initAuthManager($app); } else { - /* @var $app ConsoleApplication */ + if(!($app instanceof ConsoleApplication)) { + throw new InvalidConfigException(); + } $this->initConsoleCommands($app); $this->initAuthManager($app); } @@ -155,10 +161,12 @@ function () use ($model) { } // Attach an event to check if the password has expired - if (null !== Yii::$app->getModule('user')->maxPasswordAge) { + if (null !== $this->getModule()->maxPasswordAge) { YiiEvent::on(SecurityController::class, FormEvent::EVENT_AFTER_LOGIN, function (FormEvent $event) { - $user = $event->form->user; - if ($user->password_age >= Yii::$app->getModule('user')->maxPasswordAge) { + /** @var LoginForm $form */ + $form = $event->form; + $user = $form->getUser(); + if ($user->password_age >= $this->getModule()->maxPasswordAge) { // Force password change Yii::$app->session->setFlash('warning', Yii::t('usuario', 'Your password has expired, you must change it now')); Yii::$app->response->redirect(['/user/settings/account'])->send(); @@ -195,9 +203,9 @@ function () use ($model) { ] ]; - $app->getModule('user')->twoFactorAuthenticationValidators = ArrayHelper::merge( + $this->getModule()->twoFactorAuthenticationValidators = ArrayHelper::merge( $defaultTwoFactorAuthenticationValidators, - $app->getModule('user')->twoFactorAuthenticationValidators + $this->getModule()->twoFactorAuthenticationValidators ); if ($app instanceof WebApplication) { @@ -205,7 +213,7 @@ function () use ($model) { $di->set( 'yii\web\User', [ - 'enableAutoLogin' => $app->getModule('user')->enableAutoLogin, + 'enableAutoLogin' => $this->getModule()->enableAutoLogin, 'loginUrl' => ['/user/security/login'], 'identityClass' => $di->get(ClassMapHelper::class)->get(User::class), ] @@ -262,8 +270,7 @@ protected function initAuthManager(Application $app) */ protected function initUrlRoutes(WebApplication $app) { - /** @var $module Module */ - $module = $app->getModule('user'); + $module = $this->getModule(); $config = [ 'class' => 'yii\web\GroupUrlRule', 'prefix' => $module->prefix, @@ -300,19 +307,16 @@ protected function initUrlRestRoutes(WebApplication $app) /** * Ensures required mail parameters needed for the mail service. - * - * @param Application $app - * @param Module|\yii\base\Module $module */ protected function initMailServiceConfiguration(Application $app, Module $module) { $defaults = [ 'fromEmail' => 'no-reply@example.com', - 'welcomeMailSubject' => Yii::t('usuario', 'Welcome to {0}', $app->name), - 'confirmationMailSubject' => Yii::t('usuario', 'Confirm account on {0}', $app->name), - 'reconfirmationMailSubject' => Yii::t('usuario', 'Confirm email change on {0}', $app->name), - 'recoveryMailSubject' => Yii::t('usuario', 'Complete password reset on {0}', $app->name), - 'twoFactorMailSubject' => Yii::t('usuario', 'Code for two factor authentication on {0}', $app->name), + 'welcomeMailSubject' => Yii::t('usuario', 'Welcome to {0}', [$app->name]), + 'confirmationMailSubject' => Yii::t('usuario', 'Confirm account on {0}', [$app->name]), + 'reconfirmationMailSubject' => Yii::t('usuario', 'Confirm email change on {0}', [$app->name]), + 'recoveryMailSubject' => Yii::t('usuario', 'Complete password reset on {0}', [$app->name]), + 'twoFactorMailSubject' => Yii::t('usuario', 'Code for two factor authentication on {0}', [$app->name]), ]; $module->mailParams = array_merge($defaults, $module->mailParams); @@ -339,7 +343,7 @@ protected function initAuthCollection(WebApplication $app) */ protected function initConsoleCommands(ConsoleApplication $app) { - $app->getModule('user')->controllerNamespace = $app->getModule('user')->consoleControllerNamespace; + $this->getModule()->controllerNamespace = $this->getModule()->consoleControllerNamespace; } /** @@ -349,7 +353,6 @@ protected function initConsoleCommands(ConsoleApplication $app) */ protected function initControllerNamespace(WebApplication $app) { - $app->getModule('user')->controllerNamespace = $app->getModule('user')->controllerNamespace; $app->getModule('user')->setViewPath($app->getModule('user')->viewPath); } diff --git a/src/User/Command/CreateController.php b/src/User/Command/CreateController.php index 0af7d666..d9efd9eb 100644 --- a/src/User/Command/CreateController.php +++ b/src/User/Command/CreateController.php @@ -64,7 +64,7 @@ public function actionIndex($email, $username, $password = null, $role = null) protected function assignRole(User $user, $role) { $auth = Yii::$app->getAuthManager(); - if (false === $auth) { + if (empty($auth)) { $this->stdout( Yii::t( 'usuario', diff --git a/src/User/Command/PasswordController.php b/src/User/Command/PasswordController.php index 9e97fcb9..8666ae76 100644 --- a/src/User/Command/PasswordController.php +++ b/src/User/Command/PasswordController.php @@ -43,7 +43,7 @@ public function __construct($id, Module $module, UserQuery $userQuery, array $co */ public function actionIndex($usernameOrEmail, $password) { - /** @var User $user */ + /** @var ?User $user */ $user = $this->userQuery->whereUsernameOrEmail($usernameOrEmail)->one(); if ($user === null) { diff --git a/src/User/Component/AuthDbManagerComponent.php b/src/User/Component/AuthDbManagerComponent.php index b2ddf75c..f4a9d7f1 100644 --- a/src/User/Component/AuthDbManagerComponent.php +++ b/src/User/Component/AuthDbManagerComponent.php @@ -16,6 +16,7 @@ use yii\db\Expression; use yii\db\Query; use yii\rbac\DbManager; +use yii\rbac\Item; use yii\rbac\Role; class AuthDbManagerComponent extends DbManager implements AuthManagerInterface @@ -24,7 +25,7 @@ class AuthDbManagerComponent extends DbManager implements AuthManagerInterface * @param int|null $type If null will return all auth items * @param array $excludeItems Items that should be excluded from result array * - * @return array + * @return Item[] */ public function getItems($type = null, $excludeItems = []) { diff --git a/src/User/Contracts/AuthManagerInterface.php b/src/User/Contracts/AuthManagerInterface.php index 915d9110..aae578c8 100644 --- a/src/User/Contracts/AuthManagerInterface.php +++ b/src/User/Contracts/AuthManagerInterface.php @@ -11,6 +11,7 @@ namespace Da\User\Contracts; +use yii\rbac\Item; use yii\rbac\ManagerInterface; interface AuthManagerInterface extends ManagerInterface @@ -19,7 +20,7 @@ interface AuthManagerInterface extends ManagerInterface * @param int|null $type * @param array $excludeItems * - * @return mixed + * @return Item[] */ public function getItems($type = null, $excludeItems = []); diff --git a/src/User/Controller/AdminController.php b/src/User/Controller/AdminController.php index 05b1ca2b..b71e47f0 100755 --- a/src/User/Controller/AdminController.php +++ b/src/User/Controller/AdminController.php @@ -36,6 +36,7 @@ use yii\filters\VerbFilter; use yii\helpers\Url; use yii\web\Controller; +use yii\web\NotFoundHttpException; class AdminController extends Controller { @@ -140,7 +141,6 @@ public function actionCreate() /** @var UserEvent $event */ $event = $this->make(UserEvent::class, [$user]); - $this->make(AjaxRequestModelValidator::class, [$user])->validate(); if ($user->load(Yii::$app->request->post()) && $user->validate()) { @@ -161,7 +161,11 @@ public function actionCreate() public function actionUpdate($id) { + /** @var ?User $user */ $user = $this->userQuery->where(['id' => $id])->one(); + if($user === null) { + throw new NotFoundHttpException(); + } $user->setScenario('update'); /** @var UserEvent $event */ $event = $this->make(UserEvent::class, [$user]); @@ -187,9 +191,8 @@ public function actionUpdate($id) public function actionUpdateProfile($id) { - /** @var User $user */ + /** @var ?User $user */ $user = $this->userQuery->where(['id' => $id])->one(); - /** @var Profile $profile */ $profile = $user->profile; if ($profile === null) { $profile = $this->make(Profile::class); diff --git a/src/User/Controller/RecoveryController.php b/src/User/Controller/RecoveryController.php index 9925c874..9e675c19 100644 --- a/src/User/Controller/RecoveryController.php +++ b/src/User/Controller/RecoveryController.php @@ -134,7 +134,7 @@ public function actionReset($id, $code) if (!$this->module->allowPasswordRecovery && !$this->module->allowAdminPasswordRecovery) { throw new NotFoundHttpException(); } - /** @var Token $token */ + /** @var ?Token $token */ $token = $this->tokenQuery->whereUserId($id)->whereCode($code)->whereIsRecoveryType()->one(); /** @var ResetPasswordEvent $event */ $event = $this->make(ResetPasswordEvent::class, [$token]); diff --git a/src/User/Controller/RegistrationController.php b/src/User/Controller/RegistrationController.php index 0cfe1953..0463b319 100644 --- a/src/User/Controller/RegistrationController.php +++ b/src/User/Controller/RegistrationController.php @@ -157,7 +157,7 @@ public function actionConnect($code) throw new NotFoundHttpException(); } - /** @var SocialNetworkAccount $account */ + /** @var ?SocialNetworkAccount $account */ $account = $this->socialNetworkAccountQuery->whereCode($code)->one(); if ($account === null || $account->getIsConnected()) { throw new NotFoundHttpException(); @@ -205,7 +205,7 @@ public function actionConnect($code) */ public function actionConfirm($id, $code) { - /** @var User $user */ + /** @var ?User $user */ $user = $this->userQuery->whereId($id)->one(); if ($user === null || $this->module->enableEmailConfirmation === false) { @@ -254,7 +254,7 @@ public function actionResend() $this->make(AjaxRequestModelValidator::class, [$form])->validate(); if ($form->load(Yii::$app->request->post()) && $form->validate()) { - /** @var User $user */ + /** @var ?User $user */ $user = $this->userQuery->whereEmail($form->email)->one(); $success = true; if ($user !== null) { diff --git a/src/User/Controller/RuleController.php b/src/User/Controller/RuleController.php index f3a5f2c4..a6dfaf76 100644 --- a/src/User/Controller/RuleController.php +++ b/src/User/Controller/RuleController.php @@ -21,6 +21,7 @@ use Yii; use yii\filters\AccessControl; use yii\filters\VerbFilter; +use yii\rbac\DbManager; use yii\web\Controller; use yii\web\NotFoundHttpException; @@ -135,7 +136,9 @@ public function actionDelete($name) $rule = $this->findRule($name); $this->getAuthManager()->remove($rule); - $this->getAuthManager()->invalidateCache(); + if($this->getAuthManager() instanceof DbManager) { + $this->getAuthManager()->invalidateCache(); + } Yii::$app->getSession()->setFlash('success', Yii::t('usuario', 'Authorization rule has been removed.')); return $this->redirect(['index']); diff --git a/src/User/Controller/SecurityController.php b/src/User/Controller/SecurityController.php index c49cf79b..d3bae0e1 100644 --- a/src/User/Controller/SecurityController.php +++ b/src/User/Controller/SecurityController.php @@ -217,7 +217,7 @@ public function actionConfirm() return $this->goBack(); } } else { - $module = Yii::$app->getModule('user'); + $module = $this->getModule(); $validators = $module->twoFactorAuthenticationValidators; $credentials = Yii::$app->session->get('credentials'); $login = $credentials['login']; diff --git a/src/User/Controller/SettingsController.php b/src/User/Controller/SettingsController.php index a96040bc..e3ee6b84 100644 --- a/src/User/Controller/SettingsController.php +++ b/src/User/Controller/SettingsController.php @@ -38,6 +38,7 @@ use Da\User\Validator\TwoFactorCodeValidator; use Da\User\Validator\TwoFactorEmailValidator; use Da\User\Validator\TwoFactorTextMessageValidator; +use http\Exception\InvalidArgumentException; use Yii; use yii\base\DynamicModel; use yii\base\InvalidParamException; @@ -463,7 +464,7 @@ public function actionTwoFactor($id) } $choice = Yii::$app->request->post('choice'); - /** @var User $user */ + /** @var ?User $user */ $user = $this->userQuery->whereId($id)->one(); if (null === $user) { @@ -483,7 +484,7 @@ public function actionTwoFactor($id) $smsCode = $this->make(TwoFactorSmsCodeGeneratorService::class, [$user])->run(); return $this->renderAjax('two-factor-sms', ['id' => $id, 'code' => $smsCode, 'mobilePhone' => $mobilePhone]); default: - throw new InvalidParamException("Invalid 2FA choice"); + throw new InvalidArgumentException("Invalid 2FA choice"); } } @@ -495,7 +496,7 @@ public function actionTwoFactorEnable($id) Yii::$app->response->format = Response::FORMAT_JSON; - /** @var User $user */ + /** @var ?User $user */ $user = $this->userQuery->whereId($id)->one(); if (null === $user) { @@ -505,7 +506,7 @@ public function actionTwoFactorEnable($id) ]; } $code = Yii::$app->request->get('code'); - $module = Yii::$app->getModule('user'); + $module = $this->getModule(); $validators = $module->twoFactorAuthenticationValidators; $choice = Yii::$app->request->get('choice'); $codeDurationTime = ArrayHelper::getValue($validators, $choice.'.codeDurationTime', 300); @@ -533,9 +534,7 @@ public function actionTwoFactorDisable($id) throw new ForbiddenHttpException(); } - /** - * @var User $user - */ + /** @var ?User $user */ $user = $this->userQuery->whereId($id)->one(); if (null === $user) { @@ -585,11 +584,7 @@ public function actionTwoFactorMobilePhone($id) { Yii::$app->response->format = Response::FORMAT_JSON; - /** - * - * - * @var User $user - */ + /** @var ?User $user */ $user = $this->userQuery->whereId($id)->one(); if (null === $user) { @@ -626,11 +621,7 @@ public function actionTwoFactorMobilePhone($id) */ protected function disconnectSocialNetwork($id) { - /** - * - * - * @var SocialNetworkAccount $account - */ + /** @var ?SocialNetworkAccount $account */ $account = $this->socialNetworkAccountQuery->whereId($id)->one(); if ($account === null) { diff --git a/src/User/Controller/api/v1/AdminController.php b/src/User/Controller/api/v1/AdminController.php index 4579585a..351f7171 100644 --- a/src/User/Controller/api/v1/AdminController.php +++ b/src/User/Controller/api/v1/AdminController.php @@ -24,6 +24,7 @@ use Da\User\Service\UserCreateService; use Da\User\Traits\ContainerAwareTrait; use Yii; +use yii\base\Action; use yii\base\Module; use yii\db\ActiveRecord; use yii\filters\Cors; @@ -106,6 +107,9 @@ public function actions() */ public function behaviors() { + /** @var \Da\User\Module $module */ + $module = $this->module; + $behaviors = parent::behaviors(); // Remove the (default) authentication filter unset($behaviors['authenticator']); @@ -117,7 +121,7 @@ public function behaviors() // Re-add authentication filter $behaviors['authenticator'] = [ - 'class' => $this->module->authenticatorClass, // Class depends on the module parameter + 'class' => $module->authenticatorClass, // Class depends on the module parameter 'except' => ['options'] ]; // Return @@ -126,15 +130,20 @@ public function behaviors() /** * {@inheritdoc} + * @param string|Action $action */ public function checkAccess($action, $model = null, $params = []) { + /** @var \Da\User\Module $module */ + $module = $this->module; // Check if the REST APIs are enabled - if (!$this->module->enableRestApi) { + if (!$module->enableRestApi) { throw new NotFoundHttpException(Yii::t('usuario', 'The requested page does not exist.')); } // Access for admins only - if (!Yii::$app->user->identity->isAdmin) { + + $user = Yii::$app->user->identity; + if (!($user instanceof User) or !$user->isAdmin) { throw new ForbiddenHttpException(Yii::t('usuario', 'User does not have sufficient permissions.')); } } @@ -182,7 +191,7 @@ public function actionUpdate($id) $this->checkAccess($this->action); // Get user model - /** @var User $user */ + /** @var ?User $user */ $user = $this->userQuery->whereIdOrUsernameOrEmail($id)->one(); if (is_null($user)) { // Check user, so `$id` parameter $this->throwUser404(); @@ -216,7 +225,7 @@ public function actionDelete($id) $this->checkAccess($this->action); // Get user model - /** @var User $user */ + /** @var ?User $user */ $user = $this->userQuery->whereIdOrUsernameOrEmail($id)->one(); if (is_null($user)) { // Check user, so `$id` parameter $this->throwUser404(); @@ -251,14 +260,14 @@ public function actionUpdateProfile($id) $this->checkAccess($this->action); // Get user model - /** @var User $user */ + /** @var ?User $user */ $user = $this->userQuery->whereIdOrUsernameOrEmail($id)->one(); if (is_null($user)) { // Check user, so `$id` parameter $this->throwUser404(); } // Get profile model - /** @var Profile $profile */ + /** @var ?Profile $profile */ $profile = $user->profile; if ($profile === null) { $profile = $this->make(Profile::class); @@ -289,7 +298,7 @@ public function actionAssignments($id) $this->checkAccess($this->action); // Get user model - /** @var User $user */ + /** @var ?User $user */ $user = $this->userQuery->whereIdOrUsernameOrEmail($id)->one(); if (is_null($user)) { // Check user, so `$id` parameter $this->throwUser404(); @@ -310,7 +319,7 @@ public function actionConfirm($id) $this->checkAccess($this->action); // Get user model - /** @var User $user */ + /** @var ?User $user */ $user = $this->userQuery->whereIdOrUsernameOrEmail($id)->one(); if (is_null($user)) { // Check user, so `$id` parameter $this->throwUser404(); @@ -345,7 +354,7 @@ public function actionBlock($id) } // Get user model - /** @var User $user */ + /** @var ?User $user */ $user = $this->userQuery->whereIdOrUsernameOrEmail($id)->one(); if (is_null($user)) { // Check user, so `$id` parameter $this->throwUser404(); @@ -373,7 +382,7 @@ public function actionPasswordReset($id) $this->checkAccess($this->action); // Get user model - /** @var User $user */ + /** @var ?User $user */ $user = $this->userQuery->whereIdOrUsernameOrEmail($id)->one(); if (is_null($user)) { // Check user, so `$id` parameter $this->throwUser404(); @@ -398,7 +407,7 @@ public function actionForcePasswordChange($id) $this->checkAccess($this->action); // Get user model - /** @var User $user */ + /** @var ?User $user */ $user = $this->userQuery->whereIdOrUsernameOrEmail($id)->one(); if (is_null($user)) { // Check user, so `$id` parameter $this->throwUser404(); diff --git a/src/User/Exception/NotImplementedException.php b/src/User/Exception/NotImplementedException.php new file mode 100644 index 00000000..84caeeb8 --- /dev/null +++ b/src/User/Exception/NotImplementedException.php @@ -0,0 +1,8 @@ +mailParams['fromEmail']; $subject = $module->mailParams['recoveryMailSubject']; $params = [ - 'user' => $token && $token->user ? $token->user : null, + 'user' => $token ? $token->user : null, 'token' => $token, ]; @@ -82,7 +82,7 @@ public static function makeConfirmationMailerService(User $user, Token $token = $from = $module->mailParams['fromEmail']; $subject = $module->mailParams['confirmationMailSubject']; $params = [ - 'user' => $token && $token->user ? $token->user : null, + 'user' => $token ? $token->user : null, 'token' => $token, ]; @@ -107,7 +107,7 @@ public static function makeReconfirmationMailerService(User $user, Token $token) $from = $module->mailParams['fromEmail']; $subject = $module->mailParams['reconfirmationMailSubject']; $params = [ - 'user' => $token && $token->user ? $token->user : null, + 'user' => $token->user, 'token' => $token, ]; diff --git a/src/User/Factory/TokenFactory.php b/src/User/Factory/TokenFactory.php index 8f91e21a..7c12b1e0 100644 --- a/src/User/Factory/TokenFactory.php +++ b/src/User/Factory/TokenFactory.php @@ -81,10 +81,12 @@ public static function makeRecoveryToken($userId) * @param $type * * @throws InvalidConfigException - * @return Token|\object + * @return Token */ protected static function make($userId, $type) { - return Yii::createObject(['class' => Token::class, 'user_id' => $userId, 'type' => $type]); + /** @var Token $model */ + $model = Yii::createObject(['class' => Token::class, 'user_id' => $userId, 'type' => $type]); + return $model; } } diff --git a/src/User/Filter/TwoFactorAuthenticationEnforceFilter.php b/src/User/Filter/TwoFactorAuthenticationEnforceFilter.php index f0d07092..933972c3 100644 --- a/src/User/Filter/TwoFactorAuthenticationEnforceFilter.php +++ b/src/User/Filter/TwoFactorAuthenticationEnforceFilter.php @@ -14,17 +14,18 @@ use Da\User\Model\User; use Da\User\Module; use Da\User\Traits\AuthManagerAwareTrait; +use Da\User\Traits\ModuleAwareTrait; use Yii; use yii\base\ActionFilter; class TwoFactorAuthenticationEnforceFilter extends ActionFilter { use AuthManagerAwareTrait; + use ModuleAwareTrait; public function beforeAction($action) { - /** @var Module $module */ - $module = Yii::$app->getModule('user'); + $module = $this->getModule(); $enableTwoFactorAuthentication = $module->enableTwoFactorAuthentication; // If enableTwoFactorAuthentication is set to false do nothing @@ -39,6 +40,7 @@ public function beforeAction($action) $permissions = $module->twoFactorAuthenticationForcedPermissions; + /** @var User $user */ $user = Yii::$app->user->identity; $itemsByUser = array_keys($this->getAuthManager()->getItemsByUser($user->id)); if (!empty(array_intersect($permissions, $itemsByUser)) && !$user->auth_tf_enabled) { diff --git a/src/User/Form/GdprDeleteForm.php b/src/User/Form/GdprDeleteForm.php index a7209074..93832193 100644 --- a/src/User/Form/GdprDeleteForm.php +++ b/src/User/Form/GdprDeleteForm.php @@ -69,12 +69,15 @@ function ($attribute) { } /** - * @return User|null|\yii\web\IdentityInterface + * @return User|null */ public function getUser() { if ($this->user == null) { - $this->user = Yii::$app->user->identity; + $user = Yii::$app->user->identity; + if($user instanceof User) { + $this->user = $user; + } } return $this->user; diff --git a/src/User/Form/LoginForm.php b/src/User/Form/LoginForm.php index 18106157..0b613ab1 100644 --- a/src/User/Form/LoginForm.php +++ b/src/User/Form/LoginForm.php @@ -116,13 +116,13 @@ function ($attribute) { if ($this->user === null) { $this->addError($attribute, Yii::t('usuario', 'Invalid two factor authentication code')); } else { - $module = Yii::$app->getModule('user'); + $module = $this->getModule(); $validators = $module->twoFactorAuthenticationValidators; $type = $this->user->auth_tf_type; $class = ArrayHelper::getValue($validators, $type.'.class'); $codeDurationTime = ArrayHelper::getValue($validators, $type.'.codeDurationTime', 300); $validator = $this - ->make($class, [$this->user, $this->twoFactorAuthenticationCode, $this->module->twoFactorAuthenticationCycles]); + ->make($class, [$this->user, $this->twoFactorAuthenticationCode, $module->twoFactorAuthenticationCycles]); $success = $validator->validate(); if (!$success) { $this->addError($attribute, $validator->getUnsuccessLoginMessage($codeDurationTime)); @@ -172,11 +172,12 @@ public function login() public function beforeValidate() { if (parent::beforeValidate()) { - $this->user = $this->query->whereUsernameOrEmail(trim($this->login))->one(); - + $identity = $this->query->whereUsernameOrEmail(trim($this->login))->one(); + if($identity instanceof User) { + $this->user = $identity; + } return true; } - return false; } @@ -189,10 +190,9 @@ public function getUser() } /** - * @param IdentityInterface $user * @return User */ - public function setUser(IdentityInterface $user) + public function setUser(User $user) { return $this->user = $user; } diff --git a/src/User/Form/SettingsForm.php b/src/User/Form/SettingsForm.php index 803a6d62..81e1049c 100644 --- a/src/User/Form/SettingsForm.php +++ b/src/User/Form/SettingsForm.php @@ -48,7 +48,7 @@ class SettingsForm extends Model */ protected $securityHelper; - /** @var User */ + /** @var ?User */ protected $user; /** @@ -121,12 +121,15 @@ public function attributeLabels() } /** - * @return User|null|\yii\web\IdentityInterface + * @return ?User */ public function getUser() { if (null === $this->user) { - $this->user = Yii::$app->user->identity; + $identity = Yii::$app->user->identity; + if($identity instanceof User) { + $this->user = $identity; + } } return $this->user; diff --git a/src/User/Helper/AuthHelper.php b/src/User/Helper/AuthHelper.php index e85e191f..e8b6e683 100644 --- a/src/User/Helper/AuthHelper.php +++ b/src/User/Helper/AuthHelper.php @@ -14,8 +14,10 @@ use Da\User\Model\AbstractAuthItem; use Da\User\Module; use Da\User\Traits\AuthManagerAwareTrait; +use Da\User\Traits\ModuleAwareTrait; use Yii; use yii\helpers\ArrayHelper; +use yii\rbac\Item; use yii\rbac\Permission; use yii\rbac\Role; use yii\rbac\Rule; @@ -23,6 +25,7 @@ class AuthHelper { use AuthManagerAwareTrait; + use ModuleAwareTrait; /** * Checks whether a user has certain role. @@ -34,13 +37,8 @@ class AuthHelper */ public function hasRole($userId, $role) { - if ($this->getAuthManager()) { - $roles = array_keys($this->getAuthManager()->getRolesByUser($userId)); - - return in_array($role, $roles, true); - } - - return false; + $roles = array_keys($this->getAuthManager()->getRolesByUser($userId)); + return in_array($role, $roles, true); } /** @@ -50,9 +48,9 @@ public function hasRole($userId, $role) */ public function isAdmin($username) { - /** @var Module $module */ - $module = Yii::$app->getModule('user'); - $hasAdministratorPermissionName = $this->getAuthManager() && $module->administratorPermissionName + $module = $this->getModule(); + $this->getAuthManager(); + $hasAdministratorPermissionName = $module->administratorPermissionName ? Yii::$app->getUser()->can($module->administratorPermissionName) : false; @@ -105,7 +103,7 @@ public function getUnassignedItems(AbstractAuthItem $model) return ArrayHelper::map( $items, 'name', - function ($item) { + function (Item $item) { return empty($item->description) ? $item->name : "{$item->name} ({$item->description})"; } ); diff --git a/src/User/Model/AbstractAuthItem.php b/src/User/Model/AbstractAuthItem.php index aee8d6e4..2ed9df7e 100644 --- a/src/User/Model/AbstractAuthItem.php +++ b/src/User/Model/AbstractAuthItem.php @@ -124,7 +124,7 @@ public function getIsNewRecord() } /** - * @return Item + * @return int */ abstract public function getType(); } diff --git a/src/User/Model/SessionHistory.php b/src/User/Model/SessionHistory.php index 1713c8c0..32957736 100755 --- a/src/User/Model/SessionHistory.php +++ b/src/User/Model/SessionHistory.php @@ -103,6 +103,9 @@ public static function primaryKey() return ['user_id', 'session_id']; } + /** + * @return SessionHistoryQuery + */ public static function find() { return new SessionHistoryQuery(static::class); diff --git a/src/User/Model/SocialNetworkAccount.php b/src/User/Model/SocialNetworkAccount.php index e076327e..3f7e112e 100644 --- a/src/User/Model/SocialNetworkAccount.php +++ b/src/User/Model/SocialNetworkAccount.php @@ -27,7 +27,6 @@ * @property string $provider Name of service * @property string $client_id Account id * @property string $data Account properties returned by social network (json encoded) - * @property string $decodedData Json-decoded properties * @property string $code * @property string $email * @property string $username @@ -42,7 +41,7 @@ class SocialNetworkAccount extends ActiveRecord /** * @var array json decoded properties */ - protected $decodedData; + protected $decodedData = []; /** * {@inheritdoc} @@ -66,7 +65,10 @@ public function getIsConnected() public function getDecodedData() { if ($this->data !== null && $this->decodedData === null) { - $this->decodedData = json_decode($this->data); + $decoded = json_decode($this->data); + if(is_array($decoded)) { + $this->decodedData = $decoded; + } } return $this->decodedData; diff --git a/src/User/Model/User.php b/src/User/Model/User.php index 1e60d71b..4a6d9907 100644 --- a/src/User/Model/User.php +++ b/src/User/Model/User.php @@ -39,27 +39,27 @@ * @property int $id * @property string $username * @property string $email - * @property string $unconfirmed_email + * @property ?string $unconfirmed_email * @property string $password_hash * @property string $auth_key - * @property string $auth_tf_key + * @property ?string $auth_tf_key * @property int $auth_tf_enabled - * @property string $auth_tf_type - * @property string $auth_tf_mobile_phone - * @property string $registration_ip - * @property int $confirmed_at - * @property int $blocked_at + * @property ?string $auth_tf_type + * @property ?string $auth_tf_mobile_phone + * @property ?string $registration_ip + * @property ?int $confirmed_at + * @property ?int $blocked_at * @property int $flags * @property int $created_at * @property int $updated_at - * @property int $last_login_at - * @property int $gdpr_consent_date date of agreement of data processing - * @property string $last_login_ip - * @property int $password_changed_at + * @property ?int $last_login_at + * @property ?int $gdpr_consent_date date of agreement of data processing + * @property ?string $last_login_ip + * @property ?int $password_changed_at * @property int $password_age * Defined relations: * @property SocialNetworkAccount[] $socialNetworkAccounts - * @property Profile $profile + * @property ?Profile $profile */ class User extends ActiveRecord implements IdentityInterface { @@ -364,7 +364,7 @@ public function getSocialNetworkAccounts() /** * Returns password age in days - * @return integer + * @return int */ public function getPassword_age() { @@ -373,7 +373,7 @@ public function getPassword_age() } $d = new \DateTime("@{$this->password_changed_at}"); - return $d->diff(new \DateTime(), true)->format("%a"); + return intval($d->diff(new \DateTime(), true)->format("%a")); } /** @@ -387,7 +387,7 @@ public function getAuthTfType() /** * Returns the mobile phone number used for sms authentication two factor for the user - * @return string + * @return ?string */ public function getAuthTfMobilePhone() { diff --git a/src/User/Module.php b/src/User/Module.php index 2cbbcda1..5cd8d639 100755 --- a/src/User/Module.php +++ b/src/User/Module.php @@ -157,8 +157,9 @@ class Module extends BaseModule * @var bool whether user can remove his account */ public $allowAccountDelete = false; + /** - * @var string the class name of the strategy class to handle user's email change + * @var int the class name of the strategy class to handle user's email change */ public $emailChangeStrategy = MailChangeStrategyInterface::TYPE_DEFAULT; /** @@ -234,9 +235,9 @@ class Module extends BaseModule */ public $switchIdentitySessionKey = 'yuik_usuario'; /** - * @var integer If != NULL sets a max password age in days + * @var ?integer If != NULL sets a max password age in days */ - public $maxPasswordAge; + public $maxPasswordAge = null; /** * @var boolean whether to restrict assignment of permissions to users */ diff --git a/src/User/Search/AbstractAuthItemSearch.php b/src/User/Search/AbstractAuthItemSearch.php index 75010773..a92e2849 100644 --- a/src/User/Search/AbstractAuthItemSearch.php +++ b/src/User/Search/AbstractAuthItemSearch.php @@ -11,11 +11,13 @@ namespace Da\User\Search; +use Da\User\Exception\NotImplementedException; use Da\User\Traits\AuthManagerAwareTrait; use Da\User\Traits\ContainerAwareTrait; use yii\base\Model; use yii\data\ArrayDataProvider; use yii\db\Query; +use yii\rbac\DbManager; abstract class AbstractAuthItemSearch extends Model { @@ -52,13 +54,18 @@ public function scenarios() public function search($params = []) { + $authManager = $this->getAuthManager(); + if(!($authManager instanceof DbManager)) { + throw new NotImplementedException(); + } + /** @var ArrayDataProvider $dataProvider */ $dataProvider = $this->make(ArrayDataProvider::class); $query = (new Query()) ->select(['name', 'description', 'rule_name']) ->andWhere(['type' => $this->getType()]) - ->from($this->getAuthManager()->itemTable); + ->from($authManager->itemTable); if ($this->load($params) && $this->validate()) { $query @@ -67,7 +74,7 @@ public function search($params = []) ->andFilterWhere(['like', 'rule_name', $this->rule_name]); } - $dataProvider->allModels = $query->all($this->getAuthManager()->db); + $dataProvider->allModels = $query->all($authManager->db); return $dataProvider; } diff --git a/src/User/Search/RuleSearch.php b/src/User/Search/RuleSearch.php index d56b855c..923aacf9 100644 --- a/src/User/Search/RuleSearch.php +++ b/src/User/Search/RuleSearch.php @@ -11,6 +11,7 @@ namespace Da\User\Search; +use Da\User\Exception\NotImplementedException; use Da\User\Model\Rule; use Da\User\Traits\ContainerAwareTrait; use yii\base\InvalidConfigException; @@ -18,6 +19,7 @@ use yii\base\Model; use yii\data\ActiveDataProvider; use yii\db\Query; +use yii\rbac\DbManager; class RuleSearch extends Rule { @@ -55,9 +57,13 @@ public function rules() */ public function search(array $params = []) { + $authManager = $this->getAuthManager(); + if(!($authManager instanceof DbManager)) { + throw new NotImplementedException(); + } $query = (new Query()) ->select(['name', 'data', 'created_at', 'updated_at']) - ->from($this->getAuthManager()->ruleTable) + ->from($authManager->ruleTable) ->orderBy(['name' => SORT_ASC]); if ($this->load($params)) { @@ -73,7 +79,7 @@ public function search(array $params = []) [], [ 'query' => $query, - 'db' => $this->getAuthManager()->db, + 'db' => $authManager->db, 'sort' => [ 'attributes' => ['name', 'created_at', 'updated_at'] ] diff --git a/src/User/Search/UserSearch.php b/src/User/Search/UserSearch.php index b9367660..3155c53d 100644 --- a/src/User/Search/UserSearch.php +++ b/src/User/Search/UserSearch.php @@ -113,12 +113,12 @@ public function search($params) $userClass = $this->getClassMap()->get(User::class); if ($this->created_at !== null) { - $date = strtotime($this->created_at); + $date = strtotime((string)$this->created_at); $query->andFilterWhere(['between', $userClass::tableName().'.created_at', $date, $date + 3600 * 24]); } if ($this->last_login_at !== null) { - $date = strtotime($this->last_login_at); + $date = strtotime((string)$this->last_login_at); $query->andFilterWhere(['between', $userClass::tableName().'.last_login_at', $date, $date + 3600 * 24]); } diff --git a/src/User/Service/AuthRuleEditionService.php b/src/User/Service/AuthRuleEditionService.php index 55983d78..3097c330 100644 --- a/src/User/Service/AuthRuleEditionService.php +++ b/src/User/Service/AuthRuleEditionService.php @@ -16,13 +16,14 @@ use Da\User\Traits\AuthManagerAwareTrait; use Da\User\Traits\ContainerAwareTrait; use Exception; +use yii\rbac\DbManager; class AuthRuleEditionService implements ServiceInterface { use AuthManagerAwareTrait; use ContainerAwareTrait; - protected $model; + protected Rule $model; public function __construct(Rule $model) { @@ -35,6 +36,7 @@ public function run() return false; } + /** @var \yii\rbac\Rule $rule */ $rule = $this->make($this->model->className, [], ['name' => $this->model->name]); try { @@ -43,7 +45,9 @@ public function run() } else { $this->getAuthManager()->update($this->model->previousName, $rule); } - $this->getAuthManager()->invalidateCache(); + if($this->getAuthManager() instanceof DbManager) { + $this->getAuthManager()->invalidateCache(); + } } catch (Exception $e) { return false; } diff --git a/src/User/Service/EmailChangeService.php b/src/User/Service/EmailChangeService.php index 3b6db9ab..567ace16 100644 --- a/src/User/Service/EmailChangeService.php +++ b/src/User/Service/EmailChangeService.php @@ -24,12 +24,12 @@ class EmailChangeService implements ServiceInterface { use ModuleAwareTrait; - protected $code; - protected $model; - protected $tokenQuery; - protected $userQuery; + protected string $code; + protected User $model; + protected TokenQuery $tokenQuery; + protected UserQuery $userQuery; - public function __construct($code, User $model, TokenQuery $tokenQuery, UserQuery $userQuery) + public function __construct(string $code, User $model, TokenQuery $tokenQuery, UserQuery $userQuery) { $this->code = $code; $this->model = $model; @@ -39,7 +39,7 @@ public function __construct($code, User $model, TokenQuery $tokenQuery, UserQuer public function run() { - /** @var Token $token */ + /** @var ?Token $token */ $token = $this->tokenQuery ->whereUserId($this->model->id) ->whereCode($this->code) diff --git a/src/User/Service/MailService.php b/src/User/Service/MailService.php index 4aeefc22..910a7519 100644 --- a/src/User/Service/MailService.php +++ b/src/User/Service/MailService.php @@ -40,9 +40,9 @@ class MailService implements ServiceInterface * @param string $subject the email subject * @param string $view the view to render mail * @param array $params view parameters - * @param BaseMailer|MailerInterface $mailer mailer interface + * @param BaseMailer $mailer mailer interface */ - public function __construct($type, $from, $to, $subject, $view, array $params, MailerInterface $mailer) + public function __construct($type, $from, $to, $subject, $view, array $params, BaseMailer $mailer) { $this->type = $type; $this->from = $from; diff --git a/src/User/Service/PasswordRecoveryService.php b/src/User/Service/PasswordRecoveryService.php index 0e5b5978..0ed9aa91 100644 --- a/src/User/Service/PasswordRecoveryService.php +++ b/src/User/Service/PasswordRecoveryService.php @@ -46,7 +46,7 @@ public function run() Yii::t('usuario', 'An email with instructions to create a new password has been sent to {email} if it is associated with an {appName} account. Your existing password has not been changed.', ['email' => $this->email, 'appName' => Yii::$app->name]) ); - /** @var User $user */ + /** @var ?User $user */ $user = $this->query->whereEmail($this->email)->one(); if ($user === null) { @@ -55,10 +55,6 @@ public function run() $token = TokenFactory::makeRecoveryToken($user->id); - if (!$token) { - return false; - } - $this->mailService->setViewParam('user', $user); $this->mailService->setViewParam('token', $token); if (!$this->sendMail($user)) { diff --git a/src/User/Service/SessionHistory/SessionHistoryDecorator.php b/src/User/Service/SessionHistory/SessionHistoryDecorator.php index d999a9a2..ebe416b6 100755 --- a/src/User/Service/SessionHistory/SessionHistoryDecorator.php +++ b/src/User/Service/SessionHistory/SessionHistoryDecorator.php @@ -245,7 +245,7 @@ public function writeSession($id, $data) ] + $this->condition->currentUserData() + $updatedAt); if (!$result = $model->save()) { throw new BaseInvalidArgumentException( - print_r($model->errors, 1) + print_r($model->errors, true) ); } @@ -379,21 +379,21 @@ public function offsetGet($offset) } /** @inheritdoc */ - public function offsetSet($offset, $item) + public function offsetSet($offset, $item) : void { - return $this->session->offsetSet($offset, $item); + $this->session->offsetSet($offset, $item); } /** @inheritdoc */ - public function offsetUnset($offset) + public function offsetUnset($offset) : void { - return $this->session->offsetUnset($offset); + $this->session->offsetUnset($offset); } /** @inheritdoc */ - public function setCacheLimiter($cacheLimiter) + public function setCacheLimiter($cacheLimiter) : void { - return $this->session->setCacheLimiter($cacheLimiter); + $this->session->setCacheLimiter($cacheLimiter); } /** @inheritdoc */ diff --git a/src/User/Service/TwoFactorEmailCodeGeneratorService.php b/src/User/Service/TwoFactorEmailCodeGeneratorService.php index c60e707b..917c69ce 100644 --- a/src/User/Service/TwoFactorEmailCodeGeneratorService.php +++ b/src/User/Service/TwoFactorEmailCodeGeneratorService.php @@ -11,13 +11,13 @@ namespace Da\User\Service; +use Da\TwoFA\Contracts\StringGeneratorServiceInterface; use Da\TwoFA\Manager; -use Da\User\Contracts\ServiceInterface; use Da\User\Factory\MailFactory; use Da\User\Model\User; use Yii; -class TwoFactorEmailCodeGeneratorService implements ServiceInterface +class TwoFactorEmailCodeGeneratorService implements StringGeneratorServiceInterface { /** * @var User @@ -37,7 +37,7 @@ public function __construct(User $user) /** * @inheritdoc */ - public function run() + public function run() : string { $user = $this->user; if (!$user->auth_tf_key) { @@ -46,13 +46,13 @@ public function run() } // generate key $code = random_int(0, 999999); - $code = str_pad($code, 6, 0, STR_PAD_LEFT); + $code = str_pad((string) $code, 6, "0", STR_PAD_LEFT); // send email $mailService = MailFactory::makeTwoFactorCodeMailerService($user, $code); // check the sending emailYii::t( if (!$mailService->run()) { Yii::$app->session->addFlash('error', Yii::t('usuario', 'The email sending failed, please check your configuration.')); - return false; + return ""; } // put key in session Yii::$app->session->set("email_code_time", date('Y-m-d H:i:s')); diff --git a/src/User/Service/TwoFactorQrCodeUriGeneratorService.php b/src/User/Service/TwoFactorQrCodeUriGeneratorService.php index 0492bdc0..639ca61c 100644 --- a/src/User/Service/TwoFactorQrCodeUriGeneratorService.php +++ b/src/User/Service/TwoFactorQrCodeUriGeneratorService.php @@ -11,14 +11,14 @@ namespace Da\User\Service; +use Da\TwoFA\Contracts\StringGeneratorServiceInterface; use Da\TwoFA\Manager; use Da\TwoFA\Service\QrCodeDataUriGeneratorService; use Da\TwoFA\Service\TOTPSecretKeyUriGeneratorService; -use Da\User\Contracts\ServiceInterface; use Da\User\Model\User; use Yii; -class TwoFactorQrCodeUriGeneratorService implements ServiceInterface +class TwoFactorQrCodeUriGeneratorService implements StringGeneratorServiceInterface { /** * @var User @@ -38,7 +38,7 @@ public function __construct(User $user) /** * @inheritdoc */ - public function run() + public function run() : string { $user = $this->user; if (!$user->auth_tf_key) { diff --git a/src/User/Service/TwoFactorSmsCodeGeneratorService.php b/src/User/Service/TwoFactorSmsCodeGeneratorService.php index c541fad2..5c805e13 100644 --- a/src/User/Service/TwoFactorSmsCodeGeneratorService.php +++ b/src/User/Service/TwoFactorSmsCodeGeneratorService.php @@ -13,6 +13,7 @@ use Da\User\Contracts\ServiceInterface; use Da\User\Model\User; +use Da\User\Traits\ModuleAwareTrait; use yetopen\smssender\SmsSenderInterface; use Yii; use yii\di\Instance; @@ -20,13 +21,15 @@ class TwoFactorSmsCodeGeneratorService implements ServiceInterface { + use ModuleAwareTrait; + /** * @var User */ protected $user; /** - * @var Type + * @var string $type */ protected $type; @@ -44,7 +47,7 @@ public function __construct(User $user) { $this->user = $user; $this->type = 'sms'; - $module = Yii::$app->getModule('user'); + $module = $this->getModule(); $validators = $module->twoFactorAuthenticationValidators; $smsSender = ArrayHelper::getValue($validators, 'sms.smsSender'); $this->smsSender = Instance::ensure($smsSender, SmsSenderInterface::class); @@ -57,7 +60,7 @@ public function run() { // generate key $code = random_int(0, 999999); - $code = str_pad($code, 6, 0, STR_PAD_LEFT); + $code = str_pad((string)$code, 6, "0", STR_PAD_LEFT); // get the mobile phone of the user $user = $this->user; $mobilePhone = $user->getAuthTfMobilePhone(); diff --git a/src/User/Traits/AuthManagerAwareTrait.php b/src/User/Traits/AuthManagerAwareTrait.php index 27fee563..6c1a6e51 100644 --- a/src/User/Traits/AuthManagerAwareTrait.php +++ b/src/User/Traits/AuthManagerAwareTrait.php @@ -11,16 +11,21 @@ namespace Da\User\Traits; -use Da\User\Component\AuthDbManagerComponent; +use Da\User\Contracts\AuthManagerInterface; use Yii; +use yii\base\InvalidConfigException; trait AuthManagerAwareTrait { /** - * @return AuthDbManagerComponent|\yii\rbac\ManagerInterface + * @return AuthManagerInterface */ public function getAuthManager() { - return Yii::$app->getAuthManager(); + $authManager = Yii::$app->getAuthManager(); + if($authManager instanceof AuthManagerInterface) { + return $authManager; + } + throw new InvalidConfigException("AuthManager must implement Da\User\Contracts\AuthManagerInterface"); } } diff --git a/src/User/Traits/ModuleAwareTrait.php b/src/User/Traits/ModuleAwareTrait.php index 8a0d1a9e..f05f15a2 100644 --- a/src/User/Traits/ModuleAwareTrait.php +++ b/src/User/Traits/ModuleAwareTrait.php @@ -13,17 +13,20 @@ use Da\User\Module; use Yii; +use yii\base\InvalidConfigException; /** * @property-read Module $module */ trait ModuleAwareTrait { - /** - * @return Module - */ - public function getModule() + + public function getModule() : Module { - return Yii::$app->getModule('user'); + $module = Yii::$app->getModule('user'); + if($module instanceof Module) { + return $module; + } + throw new InvalidConfigException("Expecting Da\User\Module here!"); } } diff --git a/src/User/Validator/AjaxRequestModelValidator.php b/src/User/Validator/AjaxRequestModelValidator.php index 99088128..6682b76b 100644 --- a/src/User/Validator/AjaxRequestModelValidator.php +++ b/src/User/Validator/AjaxRequestModelValidator.php @@ -32,11 +32,11 @@ public function validate() if ($request->getIsAjax() && $this->model->load($request->post())) { Yii::$app->response->format = Response::FORMAT_JSON; - $result = ActiveForm::validate($this->model); - Yii::$app->response->data = $result; + $errors = ActiveForm::validate($this->model); + Yii::$app->response->data = $errors; Yii::$app->response->send(); Yii::$app->end(); - return $result; + return empty($errors); } return false; } diff --git a/src/User/Validator/RbacItemsValidator.php b/src/User/Validator/RbacItemsValidator.php index 45d06c22..c29bbe6e 100644 --- a/src/User/Validator/RbacItemsValidator.php +++ b/src/User/Validator/RbacItemsValidator.php @@ -30,5 +30,6 @@ protected function validateValue($value) return [Yii::t('usuario', 'There is neither role nor permission with name "{0}"', [$item]), []]; } } + return null; } } diff --git a/src/User/Validator/RbacRuleExistsValidator.php b/src/User/Validator/RbacRuleExistsValidator.php index c48ecc32..df891691 100644 --- a/src/User/Validator/RbacRuleExistsValidator.php +++ b/src/User/Validator/RbacRuleExistsValidator.php @@ -26,5 +26,6 @@ protected function validateValue($value) if (!$rule) { return [Yii::t('usuario', 'Rule {0} does not exists', $value), []]; } + return null; } } diff --git a/src/User/Validator/RbacRuleNameValidator.php b/src/User/Validator/RbacRuleNameValidator.php index edb5f9f7..5255fe94 100644 --- a/src/User/Validator/RbacRuleNameValidator.php +++ b/src/User/Validator/RbacRuleNameValidator.php @@ -21,7 +21,7 @@ class RbacRuleNameValidator extends Validator use AuthManagerAwareTrait; /** - * @var + * @var string $previousName */ public $previousName; diff --git a/src/User/Validator/RbacRuleValidator.php b/src/User/Validator/RbacRuleValidator.php index 2591bb37..ffe850ca 100644 --- a/src/User/Validator/RbacRuleValidator.php +++ b/src/User/Validator/RbacRuleValidator.php @@ -32,5 +32,6 @@ protected function validateValue($value) } catch (Exception $e) { return [Yii::t('usuario', 'Authentication rule class {0} can not be instantiated', $value), []]; } + return null; } } diff --git a/src/User/Validator/ReCaptchaValidator.php b/src/User/Validator/ReCaptchaValidator.php index 79f6d2e8..b1ab41c6 100644 --- a/src/User/Validator/ReCaptchaValidator.php +++ b/src/User/Validator/ReCaptchaValidator.php @@ -45,7 +45,7 @@ public function init() public function clientValidateAttribute($model, $attribute, $view) { $message = addslashes( - $this->notCheckedMessage ?: Yii::t('usuario', '{0} cannot be blank.', $model->getAttributeLabel($attribute)) + $this->notCheckedMessage ?: Yii::t('usuario', '{0} cannot be blank.', [$model->getAttributeLabel($attribute)]) ); return "(function(messages){if(!grecaptcha.getResponse()){messages.push('{$message}');}})(messages);"; diff --git a/src/User/Validator/TwoFactorEmailValidator.php b/src/User/Validator/TwoFactorEmailValidator.php index 9466a05e..a45c723d 100644 --- a/src/User/Validator/TwoFactorEmailValidator.php +++ b/src/User/Validator/TwoFactorEmailValidator.php @@ -15,12 +15,14 @@ use Da\User\Model\User; use Da\User\Service\TwoFactorEmailCodeGeneratorService; use Da\User\Traits\ContainerAwareTrait; +use Da\User\Traits\ModuleAwareTrait; use Yii; use yii\helpers\ArrayHelper; class TwoFactorEmailValidator extends TwoFactorCodeValidator { use ContainerAwareTrait; + use ModuleAwareTrait; protected $user; protected $code; @@ -56,7 +58,7 @@ public function validate() $currentTime = new \DateTime('now'); $interval = $currentTime->getTimestamp() - $emailCodeTime->getTimestamp(); - $module = Yii::$app->getModule('user'); + $module = $this->getModule(); $validators = $module->twoFactorAuthenticationValidators; $codeDurationTime = ArrayHelper::getValue($validators, $this->type.'.codeDurationTime', 300); diff --git a/src/User/Validator/TwoFactorTextMessageValidator.php b/src/User/Validator/TwoFactorTextMessageValidator.php index 6925b4fb..1770229c 100644 --- a/src/User/Validator/TwoFactorTextMessageValidator.php +++ b/src/User/Validator/TwoFactorTextMessageValidator.php @@ -15,12 +15,14 @@ use Da\User\Model\User; use Da\User\Service\TwoFactorSmsCodeGeneratorService; use Da\User\Traits\ContainerAwareTrait; +use Da\User\Traits\ModuleAwareTrait; use Yii; use yii\helpers\ArrayHelper; class TwoFactorTextMessageValidator extends TwoFactorCodeValidator { use ContainerAwareTrait; + use ModuleAwareTrait; protected $user; protected $code; @@ -56,7 +58,7 @@ public function validate() $smsCodeTime = new \DateTime(Yii::$app->session->get("sms_code_time")); $currentTime = new \DateTime('now'); $interval = $currentTime->getTimestamp() - $smsCodeTime->getTimestamp(); - $module = Yii::$app->getModule('user'); + $module = $this->getModule(); $validators = $module->twoFactorAuthenticationValidators; $codeDurationTime = ArrayHelper::getValue($validators, $this->type.'.codeDurationTime', 300); diff --git a/src/User/Widget/AssignmentsWidget.php b/src/User/Widget/AssignmentsWidget.php index 90b950c2..b4c0453b 100644 --- a/src/User/Widget/AssignmentsWidget.php +++ b/src/User/Widget/AssignmentsWidget.php @@ -15,6 +15,7 @@ use Da\User\Service\UpdateAuthAssignmentsService; use Da\User\Traits\AuthManagerAwareTrait; use Da\User\Traits\ContainerAwareTrait; +use Da\User\Traits\ModuleAwareTrait; use Yii; use yii\base\InvalidConfigException; use yii\base\InvalidParamException; @@ -26,6 +27,7 @@ class AssignmentsWidget extends Widget { use AuthManagerAwareTrait; use ContainerAwareTrait; + use ModuleAwareTrait; /** * @var int ID of the user to whom auth items will be assigned @@ -64,7 +66,7 @@ public function run() } $items[Yii::t('usuario', 'Roles')] = $this->getAvailableItems(Item::TYPE_ROLE); - if (!Yii::$app->getModule('user')->restrictUserPermissionAssignment) { + if (!$this->getModule()->restrictUserPermissionAssignment) { $items[Yii::t('usuario', 'Permissions')] = $this->getAvailableItems(Item::TYPE_PERMISSION); } @@ -80,8 +82,7 @@ public function run() /** * Returns available auth items to be attached to the user. * - * @param int|null type of auth items or null to return all - * @param null|mixed $type + * @param null|mixed $type type of auth items or null to return all * * @return array */ @@ -90,7 +91,7 @@ protected function getAvailableItems($type = null) return ArrayHelper::map( $this->getAuthManager()->getItems($type), 'name', - function ($item) { + function (Item $item) { return empty($item->description) ? $item->name : $item->name . ' (' . $item->description . ')'; diff --git a/src/User/Widget/ConnectWidget.php b/src/User/Widget/ConnectWidget.php index 03f17845..b7a28e66 100644 --- a/src/User/Widget/ConnectWidget.php +++ b/src/User/Widget/ConnectWidget.php @@ -18,6 +18,7 @@ use yii\base\InvalidParamException; use yii\helpers\Html; use yii\helpers\Url; +use yii\web\View; class ConnectWidget extends AuthChoice { @@ -31,9 +32,11 @@ class ConnectWidget extends AuthChoice */ public function init() { - AuthChoiceAsset::register(Yii::$app->view); + /** @var View $view */ + $view = Yii::$app->view; + AuthChoiceAsset::register($view); if ($this->popupMode) { - Yii::$app->view->registerJs("\$('#" . $this->getId() . "').authchoice();"); + $view->registerJs("\$('#" . $this->getId() . "').authchoice();"); } $this->options['id'] = $this->getId(); echo Html::beginTag('div', $this->options); diff --git a/src/User/Widget/LoginWidget.php b/src/User/Widget/LoginWidget.php deleted file mode 100644 index cf31affb..00000000 --- a/src/User/Widget/LoginWidget.php +++ /dev/null @@ -1,36 +0,0 @@ - - * - * For the full copyright and license information, please view - * the LICENSE file that was distributed with this source code. - */ - -namespace Da\User\Widget; - -use Da\User\Form\LoginForm; -use Da\User\Traits\ModuleAwareTrait; -use Yii; -use yii\base\Widget; - -/** - * @deprecated this seems to be unused by this module. To be deleted in future! - */ -class LoginWidget extends Widget -{ - use ModuleAwareTrait; - public $validate = true; - - public function run() - { - return $this->render( - $this->getModule()->viewPath .'/widgets/login/form', - [ - 'model' => Yii::createObject(LoginForm::class), - ] - ); - } -} diff --git a/src/User/Widget/SessionStatusWidget.php b/src/User/Widget/SessionStatusWidget.php index 972ced81..1f7336d5 100755 --- a/src/User/Widget/SessionStatusWidget.php +++ b/src/User/Widget/SessionStatusWidget.php @@ -19,6 +19,7 @@ use yii\base\InvalidParamException; use yii\base\Widget; use yii\helpers\ArrayHelper; +use yii\rbac\Item; class SessionStatusWidget extends Widget { @@ -68,17 +69,17 @@ public function run() /** * Returns available auth items to be attached to the user. * - * @param int|null type of auth items or null to return all - * @param null|mixed $type + * @param null|mixed $type type of auth items or null to return all * * @return array */ protected function getAvailableItems($type = null) { + $items = $this->getAuthManager()->getItems($type); return ArrayHelper::map( - $this->getAuthManager()->getItems($type), + $items, 'name', - function ($item) { + function (Item $item) { return empty($item->description) ? $item->name : $item->name . ' (' . $item->description . ')'; diff --git a/src/User/resources/views/bootstrap5/admin/index.php b/src/User/resources/views/bootstrap5/admin/index.php index 437dfaaf..44a362ed 100644 --- a/src/User/resources/views/bootstrap5/admin/index.php +++ b/src/User/resources/views/bootstrap5/admin/index.php @@ -100,7 +100,7 @@ ); }, 'format' => 'raw', - 'visible' => Yii::$app->getModule('user')->enableEmailConfirmation, + 'visible' => $module->enableEmailConfirmation, ], 'password_age', [ diff --git a/src/User/resources/views/bootstrap5/profile/show.php b/src/User/resources/views/bootstrap5/profile/show.php index 5f69dcd8..0f671b59 100644 --- a/src/User/resources/views/bootstrap5/profile/show.php +++ b/src/User/resources/views/bootstrap5/profile/show.php @@ -60,7 +60,7 @@
= Yii::t('usuario', 'Two factor authentication protects you in case of stolen credentials') ?>.
- getUser()->auth_tf_enabled): + getUser()!== null && !$model->getUser()->auth_tf_enabled): $validators = $module->twoFactorAuthenticationValidators; $theFirstFound = false; $checked = ''; diff --git a/src/User/resources/views/mail/confirmation.php b/src/User/resources/views/mail/confirmation.php index 20eb842d..913bb843 100644 --- a/src/User/resources/views/mail/confirmation.php +++ b/src/User/resources/views/mail/confirmation.php @@ -20,7 +20,7 @@ = Yii::t('usuario', 'Hello') ?>,- = Yii::t('usuario', 'Thank you for signing up on {0}', Yii::$app->name) ?>. + = Yii::t('usuario', 'Thank you for signing up on {0}', [Yii::$app->name]) ?>. = Yii::t('usuario', 'In order to complete your registration, please click the link below') ?>.
diff --git a/src/User/resources/views/mail/reconfirmation.php b/src/User/resources/views/mail/reconfirmation.php index f41e543c..4dd05e7a 100644 --- a/src/User/resources/views/mail/reconfirmation.php +++ b/src/User/resources/views/mail/reconfirmation.php @@ -22,7 +22,7 @@ = Yii::t( 'usuario', 'We have received a request to change the email address for your account on {0}', - Yii::$app->name + [Yii::$app->name] ) ?>. = Yii::t('usuario', 'In order to complete your request, please click the link below') ?>.
diff --git a/src/User/resources/views/mail/recovery.php b/src/User/resources/views/mail/recovery.php index c06e2761..2afd464d 100644 --- a/src/User/resources/views/mail/recovery.php +++ b/src/User/resources/views/mail/recovery.php @@ -23,7 +23,7 @@ = Yii::t( 'usuario', 'We have received a request to reset the password for your account on {0}', - Yii::$app->name + [Yii::$app->name] ) ?>. = Yii::t('usuario', 'Please click the link below to complete your password reset') ?>. diff --git a/src/User/resources/views/mail/text/confirmation.php b/src/User/resources/views/mail/text/confirmation.php index 20a6928c..c7863c33 100644 --- a/src/User/resources/views/mail/text/confirmation.php +++ b/src/User/resources/views/mail/text/confirmation.php @@ -15,7 +15,7 @@ ?> = Yii::t('usuario', 'Hello') ?>, -= Yii::t('usuario', 'Thank you for signing up on {0}', Yii::$app->name) ?>. += Yii::t('usuario', 'Thank you for signing up on {0}', [Yii::$app->name]) ?>. = Yii::t('usuario', 'In order to complete your registration, please click the link below') ?>. = $token->url ?> diff --git a/src/User/resources/views/mail/text/reconfirmation.php b/src/User/resources/views/mail/text/reconfirmation.php index 808139c7..3b8e353c 100644 --- a/src/User/resources/views/mail/text/reconfirmation.php +++ b/src/User/resources/views/mail/text/reconfirmation.php @@ -18,7 +18,7 @@ = Yii::t( 'usuario', 'We have received a request to change the email address for your account on {0}', - Yii::$app->name + [Yii::$app->name] ) ?>. = Yii::t('usuario', 'In order to complete your request, please click the link below') ?>. diff --git a/src/User/resources/views/mail/text/recovery.php b/src/User/resources/views/mail/text/recovery.php index 08a7210d..4ea5ed02 100644 --- a/src/User/resources/views/mail/text/recovery.php +++ b/src/User/resources/views/mail/text/recovery.php @@ -15,7 +15,7 @@ ?> = Yii::t('usuario', 'Hello') ?>, -= Yii::t('usuario', 'We have received a request to reset the password for your account on {0}', Yii::$app->name) ?>. += Yii::t('usuario', 'We have received a request to reset the password for your account on {0}', [Yii::$app->name]) ?>. = Yii::t('usuario', 'Please click the link below to complete your password reset') ?>. = $token->url ?> diff --git a/src/User/resources/views/mail/text/welcome.php b/src/User/resources/views/mail/text/welcome.php index 0d4516b3..6e70425c 100644 --- a/src/User/resources/views/mail/text/welcome.php +++ b/src/User/resources/views/mail/text/welcome.php @@ -21,7 +21,7 @@ ?> = Yii::t('usuario', 'Hello') ?>, -= Yii::t('usuario', 'Your account on {0} has been created', Yii::$app->name) ?>. += Yii::t('usuario', 'Your account on {0} has been created', [Yii::$app->name]) ?>. generatePasswords): ?> = Yii::t('usuario', 'We have generated a password for you') ?>: = $user->password ?> diff --git a/src/User/resources/views/mail/welcome.php b/src/User/resources/views/mail/welcome.php index 8efa10a9..391ea6dc 100644 --- a/src/User/resources/views/mail/welcome.php +++ b/src/User/resources/views/mail/welcome.php @@ -25,7 +25,7 @@- = Yii::t('usuario', 'Your account on {0} has been created', Yii::$app->name) ?>. + = Yii::t('usuario', 'Your account on {0} has been created', [Yii::$app->name]) ?>. generatePasswords): ?> = Yii::t('usuario', 'We have generated a password for you') ?>: = Html::encode($user->password) ?>