[*] небольшой код стайл User класса

This commit is contained in:
rsgrinko committed 2022-08-15 19:15:31 +03:00
1 parent 51d11c838f
commit 1ea49a1c10
3 files changed
+86 -35

No files matched your search

+8 -3
View File
@@ -20,6 +20,7 @@
*/ */
use Core\Models\User; use Core\Models\User;
use Core\CoreException;
require_once __DIR__ . '/inc/bootstrap.php'; require_once __DIR__ . '/inc/bootstrap.php';
if (User::isAuthorized()) { if (User::isAuthorized()) {
@@ -44,10 +45,14 @@
} }
if (empty($arErrors)) { if (empty($arErrors)) {
$userId = User::create($_REQUEST['login'], $_REQUEST['pass'], $_REQUEST['email'], $_REQUEST['name']); try {
$userId = User::create($_REQUEST['login'], $_REQUEST['pass'], $_REQUEST['email'], $_REQUEST['name']);
User::authorize($userId); User::authorize($userId);
header('Location: index.php'); header('Location: index.php');
} catch (CoreException $e){
$arErrors[] = $e->getMessage();
}
} }
} }
+23 -1
View File
@@ -21,10 +21,15 @@
* @param mixed $value Значение * @param mixed $value Значение
* *
* @return int * @return int
* @throws CoreException
*/ */
public static function sanitizeNumber($value): int public static function sanitizeNumber($value): int
{ {
return (int)filter_var($value, FILTER_SANITIZE_SPECIAL_CHARS | FILTER_SANITIZE_NUMBER_INT); $intValue = (int)filter_var($value, FILTER_SANITIZE_SPECIAL_CHARS | FILTER_SANITIZE_NUMBER_INT);
if ($intValue === 0) {
throw new CoreException($value . ' не является числом');
}
return $intValue;
} }
/** /**
@@ -38,4 +43,21 @@
{ {
return (float)filter_var($value, FILTER_SANITIZE_SPECIAL_CHARS | FILTER_SANITIZE_NUMBER_FLOAT); return (float)filter_var($value, FILTER_SANITIZE_SPECIAL_CHARS | FILTER_SANITIZE_NUMBER_FLOAT);
} }
/**
* Санитизация E-Mail
*
* @param mixed $email E-Mail
*
* @return float
*/
public static function sanitizeEmail($email) {
$isValidEmail = filter_var($email, FILTER_VALIDATE_EMAIL, FILTER_FLAG_EMAIL_UNICODE);
$emailTmp = filter_var($email, FILTER_SANITIZE_EMAIL);
if ($email !== $emailTmp || !$isValidEmail || empty($email)) {
throw new CoreException('Email "' . $email . '" некорректен');
}
return $email;
}
} }
+55 -31
View File
@@ -272,9 +272,9 @@
$result = (DB::getInstance())->getItem(self::TABLE, ['token' => $token]); $result = (DB::getInstance())->getItem(self::TABLE, ['token' => $token]);
if ($result) { if ($result) {
return true; return true;
} else {
return false;
} }
return false;
} }
/** /**
@@ -290,9 +290,9 @@
$result = (DB::getInstance())->getItem(self::TABLE, ['token' => $token]); $result = (DB::getInstance())->getItem(self::TABLE, ['token' => $token]);
if ($result) { if ($result) {
return (new self($result['id'])); return (new self($result['id']));
} else {
return null;
} }
return null;
} }
/** /**
@@ -307,9 +307,9 @@
$result = (DB::getInstance())->getItem(self::TABLE, $where); $result = (DB::getInstance())->getItem(self::TABLE, $where);
if (!empty($result)) { if (!empty($result)) {
return true; return true;
} else {
return false;
} }
return false;
} }
/** /**
@@ -319,7 +319,7 @@
*/ */
public static function getById(int $id): ?self public static function getById(int $id): ?self
{ {
if(self::isUserExistsByParams(['id' => $id])) { if (self::isUserExistsByParams(['id' => $id])) {
return new self($id); return new self($id);
} }
return null; return null;
@@ -354,9 +354,9 @@
$timeNow = time(); $timeNow = time();
if ($last_active > ($timeNow - USER_ONLINE_TIME)) { if ($last_active > ($timeNow - USER_ONLINE_TIME)) {
return true; return true;
} else {
return false;
} }
return false;
} }
/** /**
@@ -386,15 +386,15 @@
public static function create(string $login, string $password, string $email, string $name = ''): int public static function create(string $login, string $password, string $email, string $name = ''): int
{ {
$login = Sanitize::sanitizeString($login); $login = Sanitize::sanitizeString($login);
$email = Sanitize::sanitizeString($email); $email = Sanitize::sanitizeEmail($email);
$name = Sanitize::sanitizeString($name); $name = Sanitize::sanitizeString($name);
Log::logToFile('Создание нового пользователя', 'User.log', func_get_args()); Log::logToFile('Создание нового пользователя', 'User.log', func_get_args());
$verificationCode = md5(self::$cryptoSalt . $email . $login . time()); $verificationCode = md5(self::$cryptoSalt . $email . $login . time());
/** @var $DB DB */ /** @var $DB DB Объект базы данных */
$DB = DB::getInstance(); $DB = DB::getInstance();
$userId = $DB->addItem(self::TABLE, [ $userId = $DB->addItem(self::TABLE, [
'login' => $login, 'login' => $login,
'password' => self::passwordEncryption($password), 'password' => self::passwordEncryption($password),
'name' => $name, 'name' => $name,
@@ -429,6 +429,10 @@
} }
Log::logToFile('Пользователь успешно создан', 'User.log', ['userId' => $userId]); Log::logToFile('Пользователь успешно создан', 'User.log', ['userId' => $userId]);
$objectUser->getMailObject()->setSubject('Регистрация на сайте')->setBody(
'<b>Логин:</b> ' . $objectUser->getLogin() . PHP_EOL . '<b>Пароль:</b> ' . $password
)->setTemplateVars(['TITLE' => 'Создана учетная запись'])->send();
return $userId; return $userId;
} }
@@ -442,16 +446,14 @@
*/ */
public function update(array $fields): bool public function update(array $fields): bool
{ {
foreach($fields as $key => $value) { foreach ($fields as $key => $value) {
$fields[$key] = Sanitize::sanitizeString($value); $fields[$key] = Sanitize::sanitizeString($value);
} }
$cacheId = md5('User_getAllUserData_' . $this->id); $cacheId = md5('User_getAllUserData_' . $this->id);
/** @var $DB DB */ /** @var $DB DB Объект базы данных */
$DB = DB::getInstance(); $DB = DB::getInstance();
Log::logToFile( Log::logToFile(
'Данные пользователя изменены', 'Данные пользователя изменены', 'User.log', ['userId' => $this->id, 'before' => $this->getAllUserData(), 'after' => func_get_args()]
'User.log',
['userId' => $this->id, 'before' => $this->getAllUserData(), 'after' => func_get_args()]
); );
Cache::delete($cacheId); Cache::delete($cacheId);
return $DB->update(self::TABLE, ['id' => $this->id], $fields); return $DB->update(self::TABLE, ['id' => $this->id], $fields);
@@ -470,7 +472,7 @@
if (Cache::check($cacheId)) { if (Cache::check($cacheId)) {
$result = Cache::get($cacheId); $result = Cache::get($cacheId);
} else { } else {
/** @var $DB DB */ /** @var $DB DB Объект базы данных */
$DB = DB::getInstance(); $DB = DB::getInstance();
$result = $DB->getItem(self::TABLE, ['login' => $login]); $result = $DB->getItem(self::TABLE, ['login' => $login]);
Cache::set($cacheId, $result); Cache::set($cacheId, $result);
@@ -494,7 +496,7 @@
if (Cache::check($cacheId) && Cache::getAge($cacheId) < 300) { if (Cache::check($cacheId) && Cache::getAge($cacheId) < 300) {
$result = Cache::get($cacheId); $result = Cache::get($cacheId);
} else { } else {
/** @var $DB DB */ /** @var $DB DB Объект базы данных */
$DB = DB::getInstance(); $DB = DB::getInstance();
$result = $DB->getItems(self::TABLE, ['id' => '>0']); $result = $DB->getItems(self::TABLE, ['id' => '>0']);
Cache::set($cacheId, $result); Cache::set($cacheId, $result);
@@ -518,11 +520,11 @@
*/ */
public static function authorize(?int $id = null, bool $remember = false): bool public static function authorize(?int $id = null, bool $remember = false): bool
{ {
if (empty($id)) { if ($id === null) {
throw new CoreException('Передан некорректный идентификатор пользователя'); throw new CoreException('Передан некорректный идентификатор пользователя');
} }
self::logout(); self::logout();
/** @var $DB DB */ /** @var $DB DB Объект базы данных */
$DB = DB::getInstance(); $DB = DB::getInstance();
$result = $DB->getItem(self::TABLE, ['id' => $id], true); $result = $DB->getItem(self::TABLE, ['id' => $id], true);
@@ -555,7 +557,7 @@
*/ */
public static function securityAuthorize(string $login, string $password, bool $remember = false): bool public static function securityAuthorize(string $login, string $password, bool $remember = false): bool
{ {
/** @var $DB DB */ /** @var $DB DB Объект базы данных */
$DB = DB::getInstance(); $DB = DB::getInstance();
$result = $DB->getItem(self::TABLE, ['login' => $login, 'password' => self::passwordEncryption($password)], true); $result = $DB->getItem(self::TABLE, ['login' => $login, 'password' => self::passwordEncryption($password)], true);
if ($result) { if ($result) {
@@ -599,7 +601,7 @@
*/ */
public static function isAuthorized(): bool public static function isAuthorized(): bool
{ {
/** @var $DB DB */ /** @var $DB DB Объект базы данных */
$DB = DB::getInstance(); $DB = DB::getInstance();
if (!empty($_COOKIE['userId']) if (!empty($_COOKIE['userId'])
@@ -703,7 +705,7 @@
*/ */
public static function exportUsers(): string public static function exportUsers(): string
{ {
/** @var $DB DB */ /** @var $DB DB Объект базы данных */
$DB = DB::getInstance(); $DB = DB::getInstance();
$res = $DB->query('SELECT * FROM ' . self::TABLE); $res = $DB->query('SELECT * FROM ' . self::TABLE);
foreach ($res as $key => $element) { foreach ($res as $key => $element) {
@@ -722,6 +724,7 @@
{ {
return $this->getAllUserData()['email_confirmed'] === CODE_VALUE_Y; return $this->getAllUserData()['email_confirmed'] === CODE_VALUE_Y;
} }
/** /**
* Верификация E-Mail * Верификация E-Mail
* *
@@ -731,10 +734,14 @@
{ {
$verificationCode = Sanitize::sanitizeString($verificationCode); $verificationCode = Sanitize::sanitizeString($verificationCode);
/** @var $DB DB */ /** @var $DB DB Объект базы данных */
$DB = DB::getInstance(); $DB = DB::getInstance();
$res = $DB->getItem(self::TABLE, ['verification_code' => $verificationCode]); $res = $DB->getItem(self::TABLE, ['verification_code' => $verificationCode]);
if ($res) { if ($res) {
if ($res['email_confirmed'] === CODE_VALUE_Y) {
Log::logToFile('E-Mail уже верифицирован', 'User.log', ['userId' => $res['id'], 'code' => $verificationCode]);
return false;
}
(new self($res['id']))->update(['email_confirmed' => CODE_VALUE_Y]); (new self($res['id']))->update(['email_confirmed' => CODE_VALUE_Y]);
Log::logToFile('E-Mail успешно верифицирован', 'User.log', ['userId' => $res['id'], 'code' => $verificationCode]); Log::logToFile('E-Mail успешно верифицирован', 'User.log', ['userId' => $res['id'], 'code' => $verificationCode]);
return true; return true;
@@ -756,10 +763,27 @@
throw new CoreException('Ошибка отправки кода верификации: код отсутствует'); throw new CoreException('Ошибка отправки кода верификации: код отсутствует');
} }
Log::logToFile('Выслан код верификаци', 'User.log', ['userId' => $this->id, 'code' => $this->getAllUserData()['verification_code']]); Log::logToFile('Выслан код верификаци', 'User.log', ['userId' => $this->id, 'code' => $this->getAllUserData()['verification_code']]);
return (bool)$this->getMailObject() return (bool)$this->getMailObject()->setSubject('Подтверждение E-Mail')->setBody(
->setSubject('Подтверждение E-Mail') 'Код верификации: <b>' . $this->getVerificationCode() . '</b>' . PHP_EOL . 'Для подтверждения E-Mail перейдите по <a href="'
->setBody('Код верификации: <b>' . $this->getVerificationCode() . '</b>' . PHP_EOL . 'Для подтверждения E-Mail перейдите по <a href="' . SITE_URL_CORE . '/verification.php?code=' . $this->getVerificationCode() . '">ссылке</a>') . SITE_URL_CORE . '/verification.php?code=' . $this->getVerificationCode() . '">ссылке</a>'
->setTemplateVars(['TITLE' => 'Подтверждение E-Mail']) )->setTemplateVars(['TITLE' => 'Подтверждение E-Mail'])->send()[0];
->send()[0]; }
public function resetPassword(): bool
{
$newPassword = SystemFunctions::generatePassword();
try {
$this->update(['password' => self::passwordEncryption($newPassword)]);
} catch (CoreException $e) {
return false;
}
Log::logToFile('Произведен сброс пароля', 'User.log', ['userId' => $this->id, 'password' => $newPassword]);
$this->getMailObject()->setSubject('Произведен сброс пароля')->setBody(
'<b>Логин:</b> ' . $this->getLogin() . PHP_EOL . '<b>Пароль:</b> ' . $newPassword
)->setTemplateVars(['TITLE' => 'Ваши учетные данные'])->send();
return true;
} }
} }