In particular, Security supports the following features:
- Encryption/decryption: Security::encryptByKey, Security::decryptByKey, Security::encryptByPassword and Security::decryptByPassword
- Key derivation using standard algorithms: Security::pbkdf2 and Security::hkdf
- Data tampering prevention: Security::hashData and Security::validateData
- Password validation: Security::generatePasswordHash and Security::validatePassword
> Note: this class requires 'OpenSSL' PHP extension for random key/string generation on Windows and
for encryption/decryption on all platforms. For the highest security level PHP version >= 5.5.0 is recommended.
For more details and usage information on Security, see the guide article on security.
/** * @param int $length * @return string */ public static function generateSecret($length = 20) { $security = new Security(); $full = Base32::encode($security->generateRandomString($length)); return substr($full, 0, $length); }
private function createUser($username, $password, $email) { if ($this->canUpdateRootUser()) { $security = new Security(); $password_hash = $security->generatePasswordHash($password); $result = $this->db->createCommand()->update('{{%user}}', ['username' => $username, 'password_hash' => $password_hash, 'email' => $email], ['id' => '1'])->execute(); if ($result > 0) { return true; } } return false; }
/** * @return mixed */ private static function getQ() { if (empty(self::$q)) { $s = new Security(); self::$q = '!#@' . $s->generateRandomString(5) . '@#!'; } return self::$q; }
public function actionFormSubmission() { $security = new Security(); $string = Yii::$app->request->post('string'); $stringHash = ''; if (!is_null($string)) { $stringHash = $security->generatePasswordHash($string); } return $this->render('form-submission', ['stringHash' => $stringHash]); }
/** * Updates an existing User model. * If update is successful, the browser will be redirected to the 'view' page. * @param integer $id * @return mixed */ public function actionUpdate($id) { $model = $this->findModel($id); if ($model->load(Yii::$app->request->post())) { $security = new Security(); $model->password = $security->generatePasswordHash(md5($model->password)); $model->updated_date = time(); if ($model->save()) { $cache = $this->getUserCache(); $cache->set('user-' . $model->id, $model); return $this->redirect(['view', 'id' => $model->id]); } } else { return $this->render('update', ['model' => $model]); } }
public function actionIndex() { $username = '******'; $db = Yii::$app->db; $command = $db->createCommand('SELECT COUNT(*) FROM {{%user}} WHERE username = :username'); $command->bindValue(':username', $username, PDO::PARAM_STR); $exist = $command->queryScalar(); if (!$exist) { $now = time(); $security = new Security(); $columns = ['type' => User::TYPE_BACKEND, 'username' => $username, 'nickname' => 'admin', 'auth_key' => $security->generateRandomString(), 'password_hash' => $security->generatePasswordHash('admin'), 'password_reset_token' => null, 'email' => '*****@*****.**', 'role' => 10, 'status' => User::STATUS_ACTIVE, 'register_ip' => '::1', 'login_count' => 0, 'last_login_ip' => null, 'last_login_time' => null, 'created_by' => 0, 'created_at' => $now, 'updated_by' => 0, 'updated_at' => $now, 'deleted_by' => null, 'deleted_at' => null]; $db->createCommand()->insert('{{%user}}', $columns)->execute(); } else { echo "'{$username}' is exists.\r\n"; } echo "Done"; }
public function matchLength($attribute, $min = null, $max = null, $onScenario = Model::SCENARIO_DEFAULT) { $stringValidator = $this->getValidator('yii\\validators\\StringValidator', $attribute, $onScenario); $stringGenerator = new Security(); if (!empty($min)) { $string = $stringGenerator->generateRandomString($min - 1); $this->assertFalse($stringValidator->validate($string)); $string = $stringGenerator->generateRandomString($min); $this->assertTrue($stringValidator->validate($string)); } if (!empty($max)) { $string = $stringGenerator->generateRandomString($max + 1); $this->assertFalse($stringValidator->validate($string)); $string = $stringGenerator->generateRandomString($max); $this->assertTrue($stringValidator->validate($string)); } }
/** * Tests validation rules for the model. */ public function testLoginFormValidationRules() { $form = Yii::createObject(LoginForm::className()); $this->specify('login is required', function () use($form) { $form->setAttributes(['login' => '']); verify($form->validate())->false(); verify($form->getErrors('login'))->contains('Login cannot be blank.'); }); $this->specify('password is required', function () use($form) { $form->setAttributes(['password' => '']); verify($form->validate())->false(); verify($form->getErrors('password'))->contains('Password cannot be blank.'); }); $this->specify('user should exist in database', function () use($form) { $finder = test::double(Finder::className(), ['findUserByUsernameOrEmail' => null]); $form->setAttributes(['login' => 'tester', 'password' => 'qwerty']); verify($form->validate())->false(); verify($form->getErrors('password'))->contains('Invalid login or password'); $finder->verifyInvoked('findUserByUsernameOrEmail'); }); $this->specify('password should be valid', function () use($form) { test::double(Finder::className(), ['findUserByUsernameOrEmail' => \Yii::createObject(User::className())]); test::double(Security::className(), ['validatePassword' => false]); $form->setAttributes(['password' => 'qwerty']); verify($form->validate(['password']))->false(); verify($form->getErrors('password'))->contains('Invalid login or password'); test::double(Security::className(), ['validatePassword' => true]); verify($form->validate(['password']))->true(); }); $this->specify('user may not be confirmed when enableUnconfirmedLogin is true', function () use($form) { \Yii::$app->getModule('user')->enableUnconfirmedLogin = true; $user = \Yii::createObject(User::className()); test::double($user, ['getIsConfirmed' => true]); test::double(Finder::className(), ['findUserByUsernameOrEmail' => $user]); verify($form->validate())->true(); test::double($user, ['getIsConfirmed' => false]); verify($form->validate())->true(); }); $this->specify('user should be confirmed when enableUnconfirmedLogin is true', function () use($form) { \Yii::$app->getModule('user')->enableUnconfirmedLogin = false; verify($form->validate())->false(); verify($form->getErrors('login'))->contains('You need to confirm your email address'); $user = \Yii::createObject(User::className()); test::double($user, ['getIsConfirmed' => true]); test::double(Finder::className(), ['findUserByUsernameOrEmail' => $user]); verify($form->validate())->true(); }); $this->specify('user should not be blocked', function () use($form) { $user = \Yii::createObject(User::className()); test::double($user, ['getIsBlocked' => true]); test::double(Finder::className(), ['findUserByUsernameOrEmail' => $user]); verify($form->validate())->false(); verify($form->getErrors('login'))->contains('Your account has been blocked'); }); }
/** * @inheritdoc */ public function init() { parent::init(); if (is_string($this->security)) { $component = $this->security; $this->security = Yii::$app->{$component}; } elseif (is_array($this->security)) { $this->security = Yii::createObject(array_merge(['class' => Security::className()], $this->security)); } if (!$this->security instanceof Security) { throw new InvalidConfigException('The `security` attribute must extend `yii\\base\\Security`.'); } }
/** * Generates "remember me" authentication key */ public function generateAuthKey() { if (php_sapi_name() == 'cli') { $security = new Security(); $this->auth_key = $security->generateRandomString(); } else { $this->auth_key = Yii::$app->security->generateRandomString(); } }
/** * Generates new password reset token */ public function generatePasswordResetToken() { $this->password_reset_token = Security::generateRandomKey() . '_' . time(); }
/** * @inheritdoc */ public function pbkdf2($algo, $password, $salt, $iterations, $length = 0) { return parent::pbkdf2($algo, $password, $salt, $iterations, $length); }
/** * */ public function generateActivationKey() { $activate = new Security(); $this->activation_key = strtr($activate->generateRandomString(6), '_-', 'bB'); }
/** * Generates new password reset token */ public function generatePasswordResetToken() { $security = new Security(); $this->password_reset_token = $security->generateRandomKey() . '_' . time(); }
public static function upload($file, $name = null, $dir = self::F_FILES, $slug = null, $data = null, $delete = true) { if (is_null($dir)) { $dir = self::F_FILES; } $dir = trim($dir); $filePath = ''; if (strpos($file, 'http') === 0) { $tmp = Yii::getAlias('@runtime') . DIRECTORY_SEPARATOR . uniqid("fu"); file_put_contents($tmp, file_get_contents($file)); $filePath = $tmp; $name = $name ? $name : basename($file); } elseif (is_string($file)) { $filePath = Yii::getAlias($file); } elseif ($file instanceof UploadedFile) { $filePath = $file->tempName; $name = $name ? $name : $file->name; } $name = $name ? $name : basename($filePath); $sec = new Security(); while (FileUpload::find()->where(["path" => $uniquePath = md5($sec->generateRandomString())])->one()) { } $dirSlug = $dir; if (!is_dir($dir) && !($dir = self::getFolder($dirSlug))) { if (!$dir) { throw new \Exception("Folder for param '{$dirSlug}' is not set"); } else { throw new \Exception("Folder '{$dir}' not found"); } } $fullPath = self::formPath($uniquePath, $dir); if (!FileHelper::createDirectory(dirname($fullPath))) { throw new \Exception("Can't create folder '{" . dirname($fullPath) . "}'"); } if (!file_exists($filePath)) { throw new \Exception('File not loaded or not exist'); } if (is_uploaded_file($filePath)) { if (!move_uploaded_file($filePath, $fullPath)) { throw new \Exception('Unknown upload error'); } } elseif ($delete ? !rename($filePath, $fullPath) : !copy($filePath, $fullPath)) { throw new \Exception('Failed to write file to disk'); } $info = pathinfo($name); $fileUpload = new self(); //Фиск для сессии, при аяксовом запросе if (isset(Yii::$app->session)) { Yii::$app->session->open(); $fileUpload->session = Yii::$app->session->getIsActive() ? Yii::$app->session->getId() : null; Yii::$app->session->close(); } $fileUpload->user_id = CurrentUser::getId(1); $fileUpload->data = !is_null($data) ? json_encode($data) : null; $fileUpload->mime_type = FileHelper::getMimeType($fullPath); $fileUpload->md5 = md5_file($fullPath); $fileUpload->folder = $dirSlug; $fileUpload->path = $uniquePath; $fileUpload->slug = $slug; $fileUpload->size = filesize($fullPath); if (!($extension = strtolower(ArrayHelper::getValue($info, "extension")))) { $extension = ArrayHelper::getValue(FileHelper::getExtensionsByMimeType($fileUpload->mime_type), 0); } $fileUpload->name = basename($name, '.' . $extension); $fileUpload->extension = $extension; if ($fileUpload->save()) { return $fileUpload; } else { $fileUpload->deleteFile(); return null; } }
/** * Generates token with given length * @return string */ public function generate() { $this->security = Instance::ensure($this->security, Security::className()); return $this->security->generateRandomString($this->length); }