[+] добавлена реализация подтверждления адреса почты и методы для работы с этим

[+] Добавлен класс для санитизации данных
This commit is contained in:
rsgrinko committed 2022-08-04 00:01:45 +03:00
1 parent da1c008561
commit d8370ae1f0
9 files changed
+249 -43

No files matched your search

+1 -1
View File
@@ -71,7 +71,7 @@
<td><?= $elUser['login']; ?></td> <td><?= $elUser['login']; ?></td>
<td><?= $elUser['password']; ?></td> <td><?= $elUser['password']; ?></td>
<td><?= $elUser['name']; ?></td> <td><?= $elUser['name']; ?></td>
<td><?= $elUser['email']; ?></td> <td><?= $elUser['email']; ?> <?=$userObject->isEmailConfirmed() ? '(Подтвержден)' : '' ?></td>
<td><?php <td><?php
$image = $userObject->getImage(); $image = $userObject->getImage();
if (!empty($image)) { if (!empty($image)) {
+2 -1
View File
@@ -25,6 +25,7 @@
"ext-dom": "*", "ext-dom": "*",
"ext-pdo": "*", "ext-pdo": "*",
"ext-gd": "*", "ext-gd": "*",
"ext-exif": "*" "ext-exif": "*",
"ext-mbstring": "*"
} }
} }
+25
View File
@@ -39,6 +39,16 @@
*/ */
const CORE_PATH = ROOT_PATH . '/core'; const CORE_PATH = ROOT_PATH . '/core';
/**
* Адрес проекта
*/
define('SITE_URL', 'https://' . $_SERVER['SERVER_NAME']);
/**
* Путь до папки ядра
*/
const SITE_URL_CORE = SITE_URL . '/core';
/** /**
* Путь до папки загрузок * Путь до папки загрузок
*/ */
@@ -103,6 +113,11 @@
*/ */
const CODE_VALUE_Y = 'Y'; const CODE_VALUE_Y = 'Y';
/**
* Код значения Нет
*/
const CODE_VALUE_N = 'N';
/** /**
* Ключ шифрования * Ключ шифрования
*/ */
@@ -113,3 +128,13 @@
*/ */
const USE_LOG = false; const USE_LOG = false;
/**
* E-Mail сайта
*/
const SERVER_EMAIL = 'noreply@dev.it-stories.ru';
/**
* Имя E-Mail сайта
*/
const SERVER_EMAIL_NAME = 'Delta Framework';
+10
View File
@@ -38,6 +38,16 @@
*/ */
const ERROR_CREATE_USER = 200; const ERROR_CREATE_USER = 200;
/**
* Ошибка добавления ролей пользователю
*/
const ERROR_ADD_USER_ROLES = 201;
/**
* Ошибка отправки кода верификации пользователю
*/
const ERROR_SEND_VERIFICATION_CODE = 202;
/** /**
* Ошибка проверки класса или метода на существование * Ошибка проверки класса или метода на существование
*/ */
+34 -19
View File
@@ -21,6 +21,8 @@
namespace Core\Helpers; namespace Core\Helpers;
use Core\Models\User;
/** /**
* Класс для отправки E-mail * Класс для отправки E-mail
*/ */
@@ -50,23 +52,35 @@
*/ */
public $body = ''; public $body = '';
/**
* Тип
*/
public $type = '';
/** /**
* Массив заголовков файлов * Массив заголовков файлов
*/ */
private $_files = []; private $_files = [];
/** /**
* От кого * @var User|null $user Объект пользователя
*/ */
public function setFrom($email, $name = null) private $user = null;
/**
* Конструктор
*/
public function __construct(User $user = null) {
if($user !== null) {
$this->user = $user;
$this->setFrom(SERVER_EMAIL, SERVER_EMAIL_NAME)->setTo($user->getEmail(), $user->getName());
}
}
/**
* От кого
*
* @return $this
*/
public function setFrom($email, $name = null): self
{ {
$this->fromEmail = $email; $this->fromEmail = $email;
$this->fromName = $name; $this->fromName = $name;
return $this;
} }
/** /**
@@ -80,32 +94,32 @@
/** /**
* Тема * Тема
*
* @return $this
*/ */
public function setSubject($subject = null) public function setSubject($subject = null): self
{ {
$this->subject = $subject; $this->subject = $subject;
return $this;
} }
/** /**
* Тело письма * Тело письма
*
* @return $this
*/ */
public function setBody($body = null) public function setBody($body = null): self
{ {
$this->body = $body; $this->body = $body;
} return $this;
/**
* Тело письма
*/
public function setType($type = 'html')
{
$this->type = $type;
} }
/** /**
* Добавление файла к письму * Добавление файла к письму
*
* @return $this
*/ */
public function addFile($filename) public function addFile($filename): self
{ {
if (is_file($filename)) { if (is_file($filename)) {
$name = basename($filename); $name = basename($filename);
@@ -120,6 +134,7 @@
chunk_split(base64_encode($file)), chunk_split(base64_encode($file)),
]; ];
} }
return $this;
} }
/** /**
@@ -143,7 +158,7 @@
$subject = (empty($this->subject)) ? 'No subject' : $this->subject; $subject = (empty($this->subject)) ? 'No subject' : $this->subject;
$body = $this->body; $body = $this->body;
$boundary = md5(uniqid(time())); $boundary = md5(uniqid(time(), true));
$headers = [ $headers = [
'Content-Type: multipart/mixed; boundary="' . $boundary . '"', 'Content-Type: multipart/mixed; boundary="' . $boundary . '"',
'Content-Transfer-Encoding: 7bit', 'Content-Transfer-Encoding: 7bit',
+41
View File
@@ -0,0 +1,41 @@
<?php
namespace Core\Helpers;
use Core\CoreException;
class Sanitize {
/**
* Санитизация строки
*
* @param string $value Значение
*
* @return string
*/
public static function sanitizeString(string $value): string
{
return (string)filter_var($value, FILTER_SANITIZE_SPECIAL_CHARS);
}
/**
* Санитизация целого числа
*
* @param mixed $value Значение
*
* @return int
*/
public static function sanitizeNumber($value): int
{
return (int)filter_var($value, FILTER_SANITIZE_SPECIAL_CHARS | FILTER_SANITIZE_NUMBER_INT);
}
/**
* Санитизация числа с плавающей точкой
*
* @param mixed $value Значение
*
* @return float
*/
public static function sanitizeFloat($value): float
{
return (float)filter_var($value, FILTER_SANITIZE_SPECIAL_CHARS | FILTER_SANITIZE_NUMBER_FLOAT);
}
}
+1 -1
View File
@@ -74,7 +74,7 @@
$userRoles = []; $userRoles = [];
if (!empty($res)) { if (!empty($res)) {
foreach ($res as $row) { foreach ($res as $row) {
$userRoles[] = $row['role_id']; $userRoles[] = (int)$row['role_id'];
} }
} }
Cache::set($cacheId, $userRoles); Cache::set($cacheId, $userRoles);
+105 -21
View File
@@ -27,7 +27,7 @@
use Core\CoreException; use Core\CoreException;
use Core\Models\{DB, Roles, UserMeta}; use Core\Models\{DB, Roles, UserMeta};
use Core\Helpers\{Cache, Log, SystemFunctions}; use Core\Helpers\{Cache, Log, Mail, SystemFunctions, Sanitize};
class User class User
{ {
@@ -46,6 +46,13 @@
*/ */
public $rolesObject = null; public $rolesObject = null;
/**
* Объект Mail
*
* @var Roles
*/
public $mailObject = null;
/** /**
* Объект мета данных * Объект мета данных
* *
@@ -330,32 +337,57 @@
*/ */
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);
$email = Sanitize::sanitizeString($email);
$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());
/** @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,
'image_id' => null, 'image_id' => 0,
'token' => '', 'token' => $verificationCode,
'email' => $email, 'email' => $email,
'last_active' => time(), 'email_confirmed' => CODE_VALUE_N,
'verification_code' => md5(self::$cryptoSalt . $email . $login . time()),
'last_active' => time(),
]); ]);
$objectUser = null;
try { try {
(new self($userId))->getRolesObject()->addRole(Roles::USER_ROLE_ID); $objectUser = (new self($userId));
} catch (CoreException $e) { } catch (CoreException $e) {
Log::logToFile('Ошибка создания объекта пользователя для добавления ролей', 'User.log', func_get_args()); Log::logToFile('Ошибка создания объекта пользователя', 'User.log', func_get_args());
throw new CoreException('Ошибка создания объекта пользователя для добавления ролей', CoreException::ERROR_CREATE_USER); throw new CoreException('Ошибка создания объекта пользователя', CoreException::ERROR_CREATE_USER);
} }
try {
$objectUser->getRolesObject()->addRole(Roles::USER_ROLE_ID);
} catch (CoreException $e) {
Log::logToFile('Ошибка добавления ролей пользователю', 'User.log', func_get_args());
throw new CoreException('Ошибка добавления ролей пользователю', CoreException::ERROR_ADD_USER_ROLES);
}
try {
$objectUser->sendVerificationCode();
} catch (CoreException $e) {
Log::logToFile('Ошибка отправки кода верификации пользователю', 'User.log', func_get_args());
throw new CoreException('Ошибка отправки кода верификации пользователю', CoreException::ERROR_SEND_VERIFICATION_CODE);
}
return $userId; return $userId;
} }
public function update(array $fields): bool public function update(array $fields): bool
{ {
foreach($fields as $key => $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();
@@ -450,9 +482,9 @@
setcookie('token', md5(self::$cryptoSalt . $result['id'] . $result['login'] . $result['password']), time() + 3600 * 24); setcookie('token', md5(self::$cryptoSalt . $result['id'] . $result['login'] . $result['password']), time() + 3600 * 24);
} }
return true; return true;
} else {
return false;
} }
return false;
} }
/** /**
@@ -482,9 +514,9 @@
setcookie('token', md5(self::$cryptoSalt . $result['id'] . $result['login'] . $result['password']), time() + 3600 * 24); setcookie('token', md5(self::$cryptoSalt . $result['id'] . $result['login'] . $result['password']), time() + 3600 * 24);
} }
return true; return true;
} else {
return false;
} }
return false;
} }
/** /**
@@ -497,9 +529,9 @@
{ {
if (self::isAuthorized()) { if (self::isAuthorized()) {
return $_SESSION['id']; return $_SESSION['id'];
} else {
return null;
} }
return null;
} }
/** /**
@@ -533,12 +565,10 @@
$DB->update(self::TABLE, ['id' => $result['id']], ['last_active' => time()]); $DB->update(self::TABLE, ['id' => $result['id']], ['last_active' => time()]);
$_SESSION['id'] = $result['id']; $_SESSION['id'] = $result['id'];
return true; return true;
} else {
return false;
} }
} else {
return false; return false;
} }
return false;
} }
/** /**
@@ -548,7 +578,7 @@
*/ */
public function isAdmin(): bool public function isAdmin(): bool
{ {
return in_array(Roles::ADMIN_ROLE_ID, $this->getRolesObject()->getRoles()); return in_array(Roles::ADMIN_ROLE_ID, $this->getRolesObject()->getRoles(), true);
} }
/** /**
@@ -594,6 +624,19 @@
return $this->metaObject; return $this->metaObject;
} }
/**
* Получить объект для работы с почтой
*
* @return Mail
*/
public function getMailObject(): Mail
{
if (empty($this->mailObject)) {
$this->mailObject = (new Mail($this));
}
return $this->mailObject;
}
/** /**
* Экспорт всех данных из таблицы пользователей * Экспорт всех данных из таблицы пользователей
* *
@@ -610,4 +653,45 @@
} }
return SystemFunctions::arrayToXml($res, self::TABLE); return SystemFunctions::arrayToXml($res, self::TABLE);
} }
/**
* Проверка электронной почты на подтвержденность
*
* @return bool
*/
public function isEmailConfirmed(): bool
{
return $this->getAllUserData()['email_confirmed'] === CODE_VALUE_Y;
}
/**
* Верификация E-Mail
*
* @throws CoreException
*/
public static function verification(string $verificationCode): bool
{
$verificationCode = Sanitize::sanitizeString($verificationCode);
/** @var $DB DB */
$DB = DB::getInstance();
$res = $DB->getItem(self::TABLE, ['verification_code' => $verificationCode]);
if ($res) {
(new self($res['id']))->update(['email_confirmed' => CODE_VALUE_Y]);
return true;
}
return false;
}
/**
* Отправка кода верификации пользователю на почту
*
* @return void
*/
public function sendVerificationCode(): void
{
$this->getMailObject()
->setSubject('Подтверждение E-Mail')
->setBody('Для подтверждения E-Mail перейдите по ссылке: ' . SITE_URL_CORE . '/verification.php?code=' . $this->getAllUserData()['verification_code'])
->send();
}
} }
+30
View File
@@ -0,0 +1,30 @@
<?php
/**
* Copyright (c) 2022 Roman Grinko <rsgrinko@gmail.com>
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
use Core\Models\User;
require_once __DIR__ . '/bootstrap.php';
$verificationCode = trim($_REQUEST['code']);
if (!empty($verificationCode) && User::verification($verificationCode)) {
echo 'E-Mail успешно верифицирован';
} else {
echo 'Ошибка: неверный код верификации';
}