ltsecurityinc安防产品在线商城代码

This commit is contained in:
2026-09-14 17:47:10 +08:00
parent 57d8444c15
commit 6a3c9c5bd8
14539 changed files with 1775310 additions and 0 deletions
@@ -0,0 +1,143 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Admin Actions Log for Magento 2
*/
namespace Amasty\AdminActionsLog\Model\ActiveSession;
use Amasty\AdminActionsLog\Api\Data\ActiveSessionInterface;
use Magento\Framework\Model\AbstractModel;
class ActiveSession extends AbstractModel implements ActiveSessionInterface
{
/**
* Constants defined for keys of data array
*/
public const ID = 'id';
public const SESSION_ID = 'session_id';
public const ADMIN_SESSION_INFO_ID = 'admin_session_info_id';
public const USER_ID = 'user_id';
public const USERNAME = 'username';
public const FULL_NAME = 'full_name';
public const IP = 'ip';
public const SESSION_START = 'session_start';
public const RECENT_ACTIVITY = 'recent_activity';
public const LOCATION = 'location';
public const COUNTRY_ID = 'country_id';
public function _construct()
{
parent::_construct();
$this->_init(ResourceModel\ActiveSession::class);
$this->setIdFieldName(self::ID);
}
public function getSessionId(): ?string
{
return $this->_getData(self::SESSION_ID);
}
public function setSessionId(string $sessionId): ActiveSessionInterface
{
return $this->setData(self::SESSION_ID, $sessionId);
}
public function getAdminSessionInfoId(): ?int
{
return $this->hasData(self::ADMIN_SESSION_INFO_ID)
? (int)$this->_getData(self::ADMIN_SESSION_INFO_ID)
: null;
}
public function setAdminSessionInfoId(?int $adminSessionInfoId): ActiveSessionInterface
{
return $this->setData(self::ADMIN_SESSION_INFO_ID, $adminSessionInfoId);
}
public function getUserId(): ?int
{
return $this->hasData(self::USER_ID)
? (int)$this->_getData(self::USER_ID)
: null;
}
public function setUserId(?int $userId): ActiveSessionInterface
{
return $this->setData(self::USER_ID, $userId);
}
public function getUsername(): ?string
{
return $this->_getData(self::USERNAME);
}
public function setUsername(string $username): ActiveSessionInterface
{
return $this->setData(self::USERNAME, $username);
}
public function getFullName(): ?string
{
return $this->_getData(self::FULL_NAME);
}
public function setFullName(string $fullName): ActiveSessionInterface
{
return $this->setData(self::FULL_NAME, $fullName);
}
public function getIp(): ?string
{
return $this->_getData(self::IP);
}
public function setIp(string $ip): ActiveSessionInterface
{
return $this->setData(self::IP, $ip);
}
public function getSessionStart(): ?string
{
return $this->_getData(self::SESSION_START);
}
public function setSessionStart(string $startTime): ActiveSessionInterface
{
return $this->setData(self::SESSION_START, $startTime);
}
public function getRecentActivity(): ?string
{
return $this->_getData(self::RECENT_ACTIVITY);
}
public function setRecentActivity(string $activityTime): ActiveSessionInterface
{
return $this->setData(self::RECENT_ACTIVITY, $activityTime);
}
public function getLocation(): ?string
{
return $this->_getData(self::LOCATION);
}
public function setLocation(string $location): ActiveSessionInterface
{
return $this->setData(self::LOCATION, $location);
}
public function getCountryId(): ?string
{
return $this->_getData(self::COUNTRY_ID);
}
public function setCountryId(string $countryId): ActiveSessionInterface
{
return $this->setData(self::COUNTRY_ID, $countryId);
}
}
@@ -0,0 +1,199 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Admin Actions Log for Magento 2
*/
namespace Amasty\AdminActionsLog\Model\ActiveSession;
use Amasty\AdminActionsLog\Api\ActiveSessionManagerInterface;
use Amasty\AdminActionsLog\Api\ActiveSessionRepositoryInterface;
use Amasty\AdminActionsLog\Api\Data\ActiveSessionInterfaceFactory;
use Amasty\AdminActionsLog\Model\ActiveSession\ResourceModel\ActiveSession as ActiveSessionResource;
use Amasty\AdminActionsLog\Model\ActiveSession\ResourceModel\CollectionFactory as ActiveSessionCollectionFactory;
use Amasty\AdminActionsLog\Model\Admin\SessionUserDataProvider;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\App\ObjectManager;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\Stdlib\DateTime\DateTime;
use Magento\Security\Model\AdminSessionInfo;
use Magento\Security\Model\ResourceModel\AdminSessionInfo as AdminSessionInfoResource;
use Magento\Security\Model\ResourceModel\AdminSessionInfo\CollectionFactory;
class ActiveSessionManager implements ActiveSessionManagerInterface
{
public const SESSION_LIFETIME_CONFIG_PATH = 'admin/security/session_lifetime';
/**
* @var SessionUserDataProvider
*/
private $sessionUserDataProvider;
/**
* @var ActiveSessionRepositoryInterface
*/
private $activeSessionRepository;
/**
* @var ActiveSessionInterfaceFactory
*/
private $activeSessionFactory;
/**
* @var DateTime
*/
private $dateTime;
/**
* @var CollectionFactory
*/
private $adminSessionInfoCollectionFactory;
/**
* @var AdminSessionInfoResource
*/
private $adminSessionInfoResource;
/**
* @var ScopeConfigInterface
*/
private $scopeConfig;
/**
* @var ActiveSessionCollectionFactory
*/
private $activeSessionCollectionFactory;
/**
* @var ActiveSessionResource
*/
private $activeSession;
public function __construct(
SessionUserDataProvider $sessionUserDataProvider,
ActiveSessionRepositoryInterface $activeSessionRepository,
ActiveSessionInterfaceFactory $activeSessionFactory,
DateTime $dateTime,
CollectionFactory $adminSessionInfoCollectionFactory,
AdminSessionInfoResource $adminSessionInfoResource,
ScopeConfigInterface $scopeConfig,
ActiveSessionCollectionFactory $activeSessionCollectionFactory,
ActiveSessionResource $activeSession = null
) {
$this->sessionUserDataProvider = $sessionUserDataProvider;
$this->activeSessionRepository = $activeSessionRepository;
$this->activeSessionFactory = $activeSessionFactory;
$this->dateTime = $dateTime;
$this->adminSessionInfoCollectionFactory = $adminSessionInfoCollectionFactory;
$this->adminSessionInfoResource = $adminSessionInfoResource;
$this->scopeConfig = $scopeConfig;
$this->activeSessionCollectionFactory = $activeSessionCollectionFactory;
// OM for backward compatibility
$this->activeSession = $activeSession ?? ObjectManager::getInstance()->get(ActiveSessionResource::class);
}
public function initNew(): void
{
$userData = $this->sessionUserDataProvider->getUserPreparedData();
$activeSessionModel = $this->activeSessionFactory->create()->setData($userData);
$this->activeSessionRepository->save($activeSessionModel);
}
public function update(): void
{
$sessionId = $this->sessionUserDataProvider->getSessionId();
try {
$activeSessionModel = $this->activeSessionRepository->getBySessionId($sessionId);
$activeSessionModel->setRecentActivity($this->dateTime->date());
$this->activeSessionRepository->save($activeSessionModel);
} catch (NoSuchEntityException $e) {
return;
}
}
public function terminate(string $sessionId = null): void
{
if ($sessionId === null) {
$sessionId = $this->sessionUserDataProvider->getSessionId();
}
try {
$activeSessionModel = $this->activeSessionRepository->getBySessionId($sessionId);
$this->activeSessionRepository->delete($activeSessionModel);
} catch (NoSuchEntityException $e) {
return;
}
$adminSessionInfoId = (int)$activeSessionModel->getAdminSessionInfoId();
if ($adminSessionInfoId) {
// Since Magento 2.4.3-p1, 2.3.7-p2 session_id is no longer used in admin_user_session
$this->destroySessionByAdminSessionInfoId($adminSessionInfoId);
} else {
$this->destroySessionBySessionId($sessionId);
}
}
public function getInactiveSessions(): array
{
$sessionLifeTime = $this->scopeConfig->getValue(self::SESSION_LIFETIME_CONFIG_PATH);
if (empty($sessionLifeTime)) {
$sessionLifeTime = 900;
}
$activeSessionCollection = $this->activeSessionCollectionFactory->create();
$activeSessionCollection->addFieldToFilter(
ActiveSession::RECENT_ACTIVITY,
['lteq' => $this->dateTime->gmtDate('Y-m-d H:i:s', "- $sessionLifeTime seconds") ]
);
return $activeSessionCollection->getColumnValues(ActiveSession::SESSION_ID);
}
public function terminateAll(): void
{
$sessionIds = $this->activeSession->getAllSessionIds();
foreach ($sessionIds as $sessionId) {
$this->terminate($sessionId);
}
}
private function destroySessionBySessionId(string $sessionId): void
{
/** @var AdminSessionInfo $adminSessionInfo */
$adminSessionInfo = $this->adminSessionInfoCollectionFactory->create()
->addFieldToFilter('session_id', $sessionId)
->getFirstItem();
if (!$adminSessionInfo->getId()) {
return;
}
$this->updateAdminSessionInfoStatus($adminSessionInfo);
}
private function destroySessionByAdminSessionInfoId(int $adminSessionInfoId): void
{
/** @var AdminSessionInfo $adminSessionInfo */
$adminSessionInfo = $this->adminSessionInfoCollectionFactory->create()
->addFieldToFilter('id', $adminSessionInfoId)
->getFirstItem();
if (!$adminSessionInfo->getId()) {
return;
}
$this->updateAdminSessionInfoStatus($adminSessionInfo);
}
private function updateAdminSessionInfoStatus(AdminSessionInfo $adminSessionInfo): void
{
$this->adminSessionInfoResource->updateStatusByUserId(
AdminSessionInfo::LOGGED_OUT_MANUALLY,
$adminSessionInfo->getUserId(),
[AdminSessionInfo::LOGGED_IN]
);
}
}
@@ -0,0 +1,110 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Admin Actions Log for Magento 2
*/
namespace Amasty\AdminActionsLog\Model\ActiveSession;
use Amasty\AdminActionsLog\Api\ActiveSessionRepositoryInterface;
use Amasty\AdminActionsLog\Api\Data\ActiveSessionInterface;
use Amasty\AdminActionsLog\Api\Data\ActiveSessionInterfaceFactory;
use Magento\Framework\Exception\CouldNotDeleteException;
use Magento\Framework\Exception\CouldNotSaveException;
use Magento\Framework\Exception\NoSuchEntityException;
class Repository implements ActiveSessionRepositoryInterface
{
/**
* @var ActiveSessionInterfaceFactory
*/
private $activeSessionFactory;
/**
* @var ResourceModel\ActiveSession
*/
private $resource;
/**
* @var ResourceModel\CollectionFactory
*/
private $collectionFactory;
/**
* @var array
*/
private $activeSessions = [];
public function __construct(
ActiveSessionInterfaceFactory $activeSessionFactory,
ResourceModel\ActiveSession $resource,
ResourceModel\CollectionFactory $collectionFactory
) {
$this->activeSessionFactory = $activeSessionFactory;
$this->resource = $resource;
$this->collectionFactory = $collectionFactory;
}
public function getById(int $id): ActiveSessionInterface
{
if (!isset($this->activeSessions[$id])) {
/** @var ActiveSessionInterface $activeSession */
$activeSession = $this->activeSessionFactory->create();
$this->resource->load($activeSession, $id);
if (!$activeSession->getId()) {
throw new NoSuchEntityException(__('Active Session with specified ID "%1" not found.', $id));
}
$this->activeSessions[$id] = $activeSession;
}
return $this->activeSessions[$id];
}
public function getBySessionId(string $sessionId): ActiveSessionInterface
{
/** @var ActiveSessionInterface $searchedRecord */
$searchedRecord = $this->collectionFactory->create()
->addFieldToFilter(ActiveSession::SESSION_ID, $sessionId)
->getFirstItem();
return $this->getById((int)$searchedRecord->getId());
}
public function save(ActiveSessionInterface $activeSession): ActiveSessionInterface
{
try {
if ($activeSession->getId()) {
$activeSession = $this->getById((int)$activeSession->getId())->addData($activeSession->getData());
}
$this->resource->save($activeSession);
unset($this->activeSessions[$activeSession->getId()]);
} catch (\Exception $e) {
throw new CouldNotSaveException(__('Unable to save the Active Session. Error: %1', $e->getMessage()));
}
return $activeSession;
}
public function delete(ActiveSessionInterface $activeSession): bool
{
try {
$this->resource->delete($activeSession);
unset($this->activeSessions[$activeSession->getId()]);
} catch (\Exception $e) {
throw new CouldNotDeleteException(__('Unable to delete the Active Session. Error: %1', $e->getMessage()));
}
return true;
}
public function deleteById(int $id): bool
{
return $this->delete($this->getById($id));
}
}
@@ -0,0 +1,64 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Admin Actions Log for Magento 2
*/
namespace Amasty\AdminActionsLog\Model\ActiveSession\ResourceModel;
use Amasty\AdminActionsLog\Model\ActiveSession\ActiveSession as ActiveSessionModel;
use Magento\Framework\Model\ResourceModel\Db\AbstractDb;
class ActiveSession extends AbstractDb
{
public const TABLE_NAME = 'amasty_audit_active_sessions';
protected function _construct()
{
$this->_init(self::TABLE_NAME, ActiveSessionModel::ID);
}
public function updateIfSessionInvalid(int $userId, int $adminSessionInfoId): void
{
if (!$this->isSessionValid($userId, $adminSessionInfoId)) {
$connection = $this->getConnection();
$connection->update(
$this->getMainTable(),
[ActiveSessionModel::ADMIN_SESSION_INFO_ID => $adminSessionInfoId],
$connection->quoteInto(ActiveSessionModel::USER_ID . ' = ?', $userId)
);
}
}
public function getAllSessionIds(): array
{
$connection = $this->getConnection();
$tableName = $this->getMainTable();
$select = $connection->select()
->from(
$tableName,
[ActiveSessionModel::SESSION_ID]
);
return $connection->fetchCol($select);
}
private function isSessionValid(int $userId, int $adminSessionInfoId): bool
{
$connection = $this->getConnection();
$select = $connection->select()->from(
$this->getMainTable(),
[ActiveSessionModel::ADMIN_SESSION_INFO_ID]
)->where(
ActiveSessionModel::USER_ID . ' = ?',
$userId
)->limit(1);
$result = (int)$connection->fetchOne($select);
return $adminSessionInfoId == $result;
}
}
@@ -0,0 +1,24 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Admin Actions Log for Magento 2
*/
namespace Amasty\AdminActionsLog\Model\ActiveSession\ResourceModel;
use Amasty\AdminActionsLog\Model\ActiveSession\ActiveSession as ActiveSessionModel;
use Amasty\AdminActionsLog\Model\ActiveSession\ResourceModel\ActiveSession as ActiveSessionResource;
use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection;
class Collection extends AbstractCollection
{
public function _construct()
{
$this->_init(ActiveSessionModel::class, ActiveSessionResource::class);
$this->_setIdFieldName($this->getResource()->getIdFieldName());
}
}
@@ -0,0 +1,54 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Admin Actions Log for Magento 2
*/
namespace Amasty\AdminActionsLog\Model\Admin;
use Amasty\AdminActionsLog\Model\ConfigProvider;
use Magento\Backend\Model\Auth;
class IsLoggingAllowed
{
/**
* @var ConfigProvider
*/
private $configProvider;
/**
* @var Auth\Session
*/
private $authSession;
/**
* @var bool|null
*/
private $isLoggingEnabled = null;
public function __construct(
ConfigProvider $configProvider,
Auth\Session $authSession
) {
$this->configProvider = $configProvider;
$this->authSession = $authSession;
}
public function execute(): bool
{
if (!$this->authSession->isLoggedIn()) {
return false;
}
if ($this->isLoggingEnabled === null) {
$this->isLoggingEnabled = $this->configProvider->isEnabledLogAllAdmins()
|| in_array($this->authSession->getUser()->getId(), $this->configProvider->getAdminUsers());
}
return $this->isLoggingEnabled;
}
}
@@ -0,0 +1,144 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Admin Actions Log for Magento 2
*/
namespace Amasty\AdminActionsLog\Model\Admin;
use Amasty\Base\Model\GetCustomerIp;
use Amasty\Geoip\Model\Geolocation;
use Amasty\AdminActionsLog\Model\ConfigProvider;
use Magento\Backend\Model\Auth;
use Magento\Framework\DataObject;
use Magento\Framework\DataObjectFactory;
use Magento\Framework\HTTP;
use Magento\Framework\Locale\ListsInterface;
class SessionUserDataProvider
{
/**
* @var HTTP\Header
*/
private $header;
/**
* @var Geolocation
*/
private $geolocation;
/**
* @var Auth\Session
*/
private $authSession;
/**
* @var ListsInterface
*/
private $locateList;
/**
* @var ConfigProvider
*/
private $configProvider;
/**
* @var DataObjectFactory
*/
private $dataObjectFactory;
/**
* @var GetCustomerIp
*/
private $getCustomerIp;
public function __construct(
HTTP\Header $header,
Geolocation $geolocation,
Auth\Session $authSession,
ListsInterface $locateList,
ConfigProvider $configProvider,
DataObjectFactory $dataObjectFactory,
GetCustomerIp $getCustomerIp
) {
$this->header = $header;
$this->geolocation = $geolocation;
$this->authSession = $authSession;
$this->locateList = $locateList;
$this->configProvider = $configProvider;
$this->dataObjectFactory = $dataObjectFactory;
$this->getCustomerIp = $getCustomerIp;
}
public function getIpAddress(): ?string
{
return $this->getCustomerIp->getCurrentIp() ?: null;
}
public function getSessionId(): string
{
return $this->authSession->getSessionId();
}
public function getUserAgent(): string
{
return $this->header->getHttpUserAgent();
}
public function getFullUserName(): ?string
{
$user = $this->authSession->getUser();
return $user !== null
? $user->getFirstName() . ' ' . $user->getLastName()
: null;
}
public function getUserName(): ?string
{
return $this->authSession->getUser()
? $this->authSession->getUser()->getUserName()
: null;
}
public function getUserId(): ?int
{
return $this->authSession->getUser()
? (int)$this->authSession->getUser()->getId()
: null;
}
public function getLocation(): DataObject
{
$location = $this->dataObjectFactory->create();
if ($this->configProvider->isEnabledGeolocation()) {
$locationData = $this->geolocation->locate($this->getIpAddress());
$location->setData([
'country' => $this->locateList->getCountryTranslation($locationData->getCountry()),
'city' => $this->locateList->getCountryTranslation($locationData->getCity())
]);
}
return $location;
}
public function getUserPreparedData(): array
{
$location = $this->getLocation();
return [
'ip' => $this->getIpAddress(),
'user_id' => $this->getUserId(),
'username' => $this->getUserName(),
'full_name' => $this->getFullUserName(),
'location' => sprintf('%s %s', $location->getCountry(), $location->getCity()),
'country_id' => $location->getCountry(),
'session_id' => $this->getSessionId()
];
}
}
@@ -0,0 +1,150 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Admin Actions Log for Magento 2
*/
namespace Amasty\AdminActionsLog\Model\Catalog\Model\Product\Gallery;
use Amasty\AdminActionsLog\Api\Logging\MetadataInterface;
use Amasty\AdminActionsLog\Api\Logging\MetadataInterfaceFactory;
use Amasty\AdminActionsLog\Logging\ActionFactory;
use Magento\Catalog\Api\Data\ProductAttributeMediaGalleryEntryInterface;
use Magento\Catalog\Api\Data\ProductInterface;
use Magento\Framework\Event\Manager as EventManager;
use Magento\Framework\Exception\LocalizedException;
class LogImages
{
/**
* @var ActionFactory
*/
private $actionFactory;
/**
* @var MetadataInterfaceFactory
*/
private $metadataFactory;
/**
* @var EventManager
*/
private $eventManager;
/**
* @var array ['SKU' => [imageId => \Magento\Catalog\Model\Product\Gallery\Entry]]
*/
private $oldImages = [];
/**
* @var array ['SKU' => [imageId => \Magento\Catalog\Model\Product\Gallery\Entry]]
*/
private $deletedImages = [];
public function __construct(
ActionFactory $actionFactory,
MetadataInterfaceFactory $metadataFactory,
EventManager $eventManager
) {
$this->actionFactory = $actionFactory;
$this->metadataFactory = $metadataFactory;
$this->eventManager = $eventManager;
}
public function processGalleryBeforeSave(ProductInterface $product): void
{
if (!$this->validateLogging($product)) {
return;
}
$productSku = $product->getSku();
$this->oldImages[$productSku] = [];
try {
$productGallery = $product->getMediaGalleryEntries();
} catch (LocalizedException $exception) {
return;
}
$mediaGalleryData = $product->getData('media_gallery') ?? [];
$removedImages = [];
if ($mediaGalleryData && isset($mediaGalleryData['images'])) {
$removedImages = array_filter(array_column($mediaGalleryData['images'], 'removed', 'value_id'));
}
$this->deletedImages[$productSku] = [];
foreach ($productGallery as $image) {
if (isset($removedImages[$image['id']])) {
$this->deletedImages[$productSku][$image['id']] = $image;
} elseif (!empty($image['id'])) {
$this->oldImages[$productSku][$image['id']] = $image;
}
}
foreach ($this->oldImages[$productSku] as $image) {
$this->executeLoggingAction($image, MetadataInterface::EVENT_SAVE_BEFORE);
}
foreach ($this->deletedImages[$productSku] as $image) {
$this->eventManager->dispatch('model_delete_before', ['object' => $image]);
}
}
public function processGalleryAfterSave(ProductInterface $product): void
{
if (!$this->validateLogging($product)) {
return;
}
$gallery = [];
$productSku = $product->getSku();
$productGallery = $product->getMediaGalleryEntries() ?? [];
foreach ($productGallery as $image) {
if (!isset($this->deletedImages[$productSku][$image['id']])) {
if (!isset($this->oldImages[$productSku][$image['id']])) {
$image->isObjectNew(true);
$gallery[$image['id']] = $image;
} else {
$oldImage = $this->oldImages[$productSku][$image['id']];
$oldImage->setData($image->getData());
$gallery[$image['id']] = $oldImage;
}
}
}
foreach ($gallery as $image) {
$this->executeLoggingAction($image, MetadataInterface::EVENT_SAVE_AFTER);
}
foreach ($this->deletedImages[$productSku] as $image) {
$this->eventManager->dispatch('model_delete_after', ['object' => $image]);
}
}
private function validateLogging(ProductInterface $product): bool
{
$isValid = true;
$existedImages = $product->getMediaGalleryImages()->getItems();
$mediaGalleryData = $product->getMediaGallery('images') ?? [];
if (count($existedImages) === count($mediaGalleryData) && !array_diff_key($mediaGalleryData, $existedImages)) {
$isValid = false;
}
return $isValid;
}
private function executeLoggingAction(
ProductAttributeMediaGalleryEntryInterface $loggingObject,
string $eventName
): void {
$metadata = $this->metadataFactory->create([
'eventName' => $eventName,
'loggingObject' => $loggingObject
]);
$actionHandler = $this->actionFactory->create($metadata);
$actionHandler->execute();
}
}
+330
View File
@@ -0,0 +1,330 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Admin Actions Log for Magento 2
*/
namespace Amasty\AdminActionsLog\Model;
class ConfigProvider extends \Amasty\Base\Model\ConfigProviderAbstract
{
/**
* @var string
*/
protected $pathPrefix = 'amaudit/';
/**#@+
* Constants defined for xpath of system configuration
*/
public const LOG_ENABLE_VISIT_HISTORY = 'general/log_enable_visit_history';
public const LOG_ALL_ADMINS = 'general/log_all_admins';
public const LOG_ADMIN_USERS = 'general/log_admin_users';
public const ACTIONS_LOG_CLEANING = 'general/auto_cleaning/actions_log_cleaning';
public const ACTIONS_LOG_PERIOD = 'general/auto_cleaning/actions_log_period';
public const LOGIN_ATTEMPTS_LOG_CLEANING = 'general/auto_cleaning/login_attempts_log_cleaning';
public const LOGIN_ATTEMPTS_LOG_PERIOD = 'general/auto_cleaning/login_attempts_log_period';
public const VISIT_HISTORY_LOG_CLEANING = 'general/auto_cleaning/visit_history_log_cleaning';
public const VISIT_HISTORY_LOG_PERIOD = 'general/auto_cleaning/visit_history_log_period';
public const GEOLOCATION_ENABLE = 'general/geolocation_enable';
public const RESTORE_POPUP_MESSAGE = 'general/restore_popup_message';
public const SUCCESSFUL_LOG_MAILING_ENABLED = 'email_notifications/successful_log_mailing_enabled';
public const SUCCESSFUL_LOG_MAILING_IDENTITY = 'email_notifications/successful_log_mailing_identity';
public const SUCCESSFUL_LOG_MAILING_TEMPLATE = 'email_notifications/successful_log_mailing_template';
public const SUCCESSFUL_LOG_MAILING_SEND_TO = 'email_notifications/successful_log_mailing_send_to_mail';
public const UNSUCCESSFUL_LOG_MAILING_ENABLED = 'email_notifications/unsuccessful_log_mailing_enabled';
public const UNSUCCESSFUL_LOG_MAILING_NUM_ATTEMPTS = 'email_notifications/unsuccessful_log_mailing_number_attempts';
public const UNSUCCESSFUL_LOG_MAILING_IDENTITY = 'email_notifications/unsuccessful_log_mailing_identity';
public const UNSUCCESSFUL_LOG_MAILING_TEMPLATE = 'email_notifications/unsuccessful_log_mailing_template';
public const UNSUCCESSFUL_LOG_MAILING_SEND_TO = 'email_notifications/unsuccessful_log_mailing_send_to_mail';
public const SUSPICIOUS_LOG_MAILING_ENABLED = 'email_notifications/suspicious_log_mailing_enabled';
public const SUSPICIOUS_LOG_MAILING_IDENTITY = 'email_notifications/suspicious_log_mailing_identity';
public const SUSPICIOUS_LOG_MAILING_IF_LOGGED_IN = 'email_notifications/suspicious_log_mailing_if_logged_in';
public const SUSPICIOUS_LOG_MAILING_TEMPLATE = 'email_notifications/suspicious_log_mailing_template';
public const SUSPICIOUS_LOG_MAILING_SEND_TO = 'email_notifications/suspicious_log_mailing_send_to_mail';
/**#@-*/
/**
* @param int|null $storeId
*
* @return bool
*/
public function isEnabledLogVisitHistory($storeId = null): bool
{
return $this->isSetFlag(self::LOG_ENABLE_VISIT_HISTORY, $storeId);
}
/**
* @param int|null $storeId
*
* @return bool
*/
public function isEnabledLogAllAdmins($storeId = null): bool
{
return $this->isSetFlag(self::LOG_ALL_ADMINS, $storeId);
}
/**
* @param int|null $storeId
*
* @return array
*/
public function getAdminUsers($storeId = null): array
{
$adminUsers = [];
if ($value = $this->getValue(self::LOG_ADMIN_USERS, $storeId)) {
$adminUsers = explode(',', $value);
}
return $adminUsers;
}
/**
* @param int|null $storeId
*
* @return bool
*/
public function isNeedCleanActionsLog($storeId = null): bool
{
return $this->isSetFlag(self::ACTIONS_LOG_CLEANING, $storeId);
}
/**
* @param int|null $storeId
*
* @return int
*/
public function getActionsLogPeriod($storeId = null): int
{
return (int)$this->getValue(self::ACTIONS_LOG_PERIOD, $storeId);
}
/**
* @param int|null $storeId
*
* @return bool
*/
public function isNeedCleanLoginAttemptsLog($storeId = null): bool
{
return $this->isSetFlag(self::LOGIN_ATTEMPTS_LOG_CLEANING, $storeId);
}
/**
* @param int|null $storeId
*
* @return int
*/
public function getLoginAttemptsLogPeriod($storeId = null): int
{
return (int)$this->getValue(self::LOGIN_ATTEMPTS_LOG_PERIOD, $storeId);
}
/**
* @param int|null $storeId
*
* @return bool
*/
public function isNeedCleanVisitHistoryLog($storeId = null): bool
{
return $this->isSetFlag(self::VISIT_HISTORY_LOG_CLEANING, $storeId);
}
/**
* @param int|null $storeId
*
* @return int
*/
public function getVisitHistoryLogPeriod($storeId = null): int
{
return (int)$this->getValue(self::VISIT_HISTORY_LOG_PERIOD, $storeId);
}
/**
* @param int|null $storeId
*
* @return bool
*/
public function isEnabledGeolocation($storeId = null): bool
{
return $this->isSetFlag(self::GEOLOCATION_ENABLE, $storeId);
}
/**
* @param int|null $storeId
*
* @return string
*/
public function getRestoreSettingsText($storeId = null): string
{
return (string)$this->getValue(self::RESTORE_POPUP_MESSAGE, $storeId);
}
/**
* @param int|null $storeId
*
* @return bool
*/
public function isEnabledEmailSuccessfulLoginsToAdmin($storeId = null): bool
{
return $this->isSetFlag(self::SUCCESSFUL_LOG_MAILING_ENABLED, $storeId);
}
/**
* @param int|null $storeId
*
* @return string
*/
public function getSenderEmailSuccessfulLogins($storeId = null): string
{
return (string)$this->getValue(self::SUCCESSFUL_LOG_MAILING_IDENTITY, $storeId);
}
/**
* @param int|null $storeId
*
* @return string
*/
public function getTemplateEmailSuccessfulLogins($storeId = null): string
{
return (string)$this->getValue(self::SUCCESSFUL_LOG_MAILING_TEMPLATE, $storeId);
}
/**
* @param int|null $storeId
*
* @return array
*/
public function getSendToEmailsSuccessfulLogins($storeId = null): array
{
$emails = [];
if ($value = $this->getValue(self::SUCCESSFUL_LOG_MAILING_SEND_TO, $storeId)) {
$emails = explode(',', $value);
}
return $emails;
}
/**
* @param int|null $storeId
*
* @return bool
*/
public function isEnabledEmailUnsuccessfulLoginsToAdmin($storeId = null): bool
{
return $this->isSetFlag(self::UNSUCCESSFUL_LOG_MAILING_ENABLED, $storeId);
}
/**
* @param int|null $storeId
*
* @return int
*/
public function getNumberUnsuccessfulLoginAttempts($storeId = null): int
{
return (int)$this->getValue(self::UNSUCCESSFUL_LOG_MAILING_NUM_ATTEMPTS, $storeId);
}
/**
* @param int|null $storeId
*
* @return string
*/
public function getSenderEmailUnsuccessfulLogins($storeId = null): string
{
return (string)$this->getValue(self::UNSUCCESSFUL_LOG_MAILING_IDENTITY, $storeId);
}
/**
* @param int|null $storeId
*
* @return string
*/
public function getTemplateEmailUnsuccessfulLogins($storeId = null): string
{
return (string)$this->getValue(self::UNSUCCESSFUL_LOG_MAILING_TEMPLATE, $storeId);
}
/**
* @param int|null $storeId
*
* @return array
*/
public function getSendToEmailsUnsuccessfulLogins($storeId = null): array
{
$emails = [];
if ($value = $this->getValue(self::UNSUCCESSFUL_LOG_MAILING_SEND_TO, $storeId)) {
$emails = explode(',', $value);
}
return $emails;
}
/**
* @param int|null $storeId
*
* @return bool
*/
public function isEnabledEmailSuspiciousLoginsToAdmin($storeId = null): bool
{
return $this->isSetFlag(self::SUSPICIOUS_LOG_MAILING_ENABLED, $storeId);
}
/**
* @param int|null $storeId
*
* @return array
*/
public function getListSuspiciousLoggedInWith($storeId = null): array
{
$loggedIn = [];
if ($value = $this->getValue(self::SUSPICIOUS_LOG_MAILING_IF_LOGGED_IN, $storeId)) {
$loggedIn = explode(',', $value);
}
return $loggedIn;
}
/**
* @param int|null $storeId
*
* @return string
*/
public function getSenderEmailSuspiciousLogins($storeId = null): string
{
return (string)$this->getValue(self::SUSPICIOUS_LOG_MAILING_IDENTITY, $storeId);
}
/**
* @param int|null $storeId
*
* @return string
*/
public function getTemplateEmailSuspiciousLogins($storeId = null): string
{
return (string)$this->getValue(self::SUSPICIOUS_LOG_MAILING_TEMPLATE, $storeId);
}
/**
* @param int|null $storeId
*
* @return array
*/
public function getSendToEmailsSuspiciousLogins($storeId = null): array
{
$emails = [];
if ($value = $this->getValue(self::SUSPICIOUS_LOG_MAILING_SEND_TO, $storeId)) {
$emails = explode(',', $value);
}
return $emails;
}
}
@@ -0,0 +1,66 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Admin Actions Log for Magento 2
*/
namespace Amasty\AdminActionsLog\Model;
use Magento\Framework\Api\Search\FilterGroup;
use Magento\Framework\Api\SearchCriteriaInterface;
use Magento\Framework\Api\SortOrder;
use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection;
trait CriteriaApplierTrait
{
public function applyCriteria(SearchCriteriaInterface $searchCriteria, AbstractCollection $collection)
{
// Add filters from root filter group to the collection
foreach ($searchCriteria->getFilterGroups() as $group) {
$this->addFilterGroupToCollection($group, $collection);
}
if ($sortOrders = $searchCriteria->getSortOrders()) {
$this->addOrderToCollection($sortOrders, $collection);
}
$collection->setCurPage($searchCriteria->getCurrentPage());
$collection->setPageSize($searchCriteria->getPageSize());
}
/**
* Helper function that adds a FilterGroup to the collection.
*
* @param FilterGroup $filterGroup
* @param AbstractCollection $collection
*/
public function addFilterGroupToCollection(FilterGroup $filterGroup, AbstractCollection $collection): void
{
foreach ($filterGroup->getFilters() as $filter) {
$condition = $filter->getConditionType() ?: 'eq';
$collection->addFieldToFilter($filter->getField(), [$condition => $filter->getValue()]);
}
}
/**
* Helper function that adds a SortOrder to the collection.
*
* @param SortOrder[] $sortOrders
* @param AbstractCollection $collection
*/
public function addOrderToCollection($sortOrders, AbstractCollection $collection): void
{
/** @var SortOrder $sortOrder */
foreach ($sortOrders as $sortOrder) {
$field = $sortOrder->getField();
$collection->addOrder(
$field,
($sortOrder->getDirection() == SortOrder::SORT_DESC) ? 'DESC' : 'ASC'
);
}
}
}
+141
View File
@@ -0,0 +1,141 @@
<?php
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Admin Actions Log for Magento 2
*/
namespace Amasty\AdminActionsLog\Model\Di;
use Magento\Framework\Module\Manager;
use Magento\Framework\ObjectManager\ConfigInterface as ObjectManagerMetaProvider;
use Magento\Framework\ObjectManagerInterface;
class Wrapper
{
/**
* @var ObjectManagerInterface
*/
private $objectManagerInterface;
/**
* @var string
*/
private $name;
/**
* @var bool
*/
private $isShared;
/**
* @var bool
*/
private $isProxy;
/**
* @var object
*/
private $subject;
/**
* @var Manager
*/
private $moduleManager;
/**
* @var ObjectManagerMetaProvider
*/
private $diMetaProvider;
public function __construct(
ObjectManagerInterface $objectManagerInterface,
Manager $moduleManager,
ObjectManagerMetaProvider $diMetaProvider,
$name = '',
$isShared = false,
$isProxy = false
) {
$this->objectManagerInterface = $objectManagerInterface;
$this->moduleManager = $moduleManager;
$this->diMetaProvider = $diMetaProvider;
$this->name = $name;
$this->isShared = $isShared;
$this->isProxy = $isProxy;
}
/**
* @param string $name
* @param array arguments
* @return bool|mixed
*/
public function __call($name, $arguments)
{
$result = false;
if ($this->canCreateObject()) {
$object = $this->getSubject();
//phpcs:ignore
$result = call_user_func_array([$object, $name], $arguments);
}
return $result;
}
/**
* @return object
*/
public function getSubject(): object
{
if ($this->isProxy && $this->subject) {
return $this->subject;
}
if ($this->isShared) {
$object = $this->objectManagerInterface->get($this->name);
} else {
$object = $this->objectManagerInterface->create($this->name);
}
if ($this->isProxy) {
$this->subject = $object;
}
return $object;
}
private function isVirtualType(string $class): bool
{
$type = $this->diMetaProvider->getInstanceType($class);
return $type !== $class;
}
private function canCreateObject(): bool
{
$canAutoload = (class_exists($this->name) || interface_exists($this->name))
&& $this->moduleManager->isEnabled($this->getModuleName($this->name));
$canGetObjectByDI = $this->isVirtualType($this->name);
return $this->name && ($canAutoload || $canGetObjectByDI);
}
private function getModuleName(string $class): string
{
$class = ltrim($class, '\\');
$parts = preg_split('@[\\\_]@', $class);
$parts = array_filter($parts);
if (count($parts) < 2) {
throw new \InvalidArgumentException(
(string)__('Provided argument is not in PSR-0 or underscore notation.')
);
}
return sprintf(
'%1s_%2s',
ucfirst($parts[0]),
ucfirst($parts[1])
);
}
}
@@ -0,0 +1,23 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Admin Actions Log for Magento 2
*/
namespace Amasty\AdminActionsLog\Model\DiffFinder;
interface DiffFinderAdapterInterface
{
/**
* Compare 2 strings and return result string with marked differences.
*
* @param string $fromText
* @param string $toText
* @return string
*/
public function render(string $fromText, string $toText): string;
}
@@ -0,0 +1,46 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Admin Actions Log for Magento 2
*/
namespace Amasty\AdminActionsLog\Model\DiffFinder;
use FineDiff\Diff;
use Magento\Framework\ObjectManagerInterface;
class FineDiffAdapter implements DiffFinderAdapterInterface
{
/**
* @var Diff|null
*/
private $diffFinder;
public function __construct(
ObjectManagerInterface $objectManager
) {
//ToDo: Remove after updating library "d4h/finediff"
$currentErrorLevel = error_reporting();
error_reporting($currentErrorLevel & ~E_DEPRECATED);
if (class_exists(Diff::class)) {
$this->diffFinder = $objectManager->create(Diff::class);
}
error_reporting($currentErrorLevel);
}
public function render(string $fromText, string $toText): string
{
if ($this->diffFinder === null) {
throw new \RuntimeException(
'\'d4h/finediff\' library not found. '
. 'Please run \'composer require d4h/finediff\' command to install it.'
);
}
return $this->diffFinder->render($fromText, $toText);
}
}
@@ -0,0 +1,60 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Admin Actions Log for Magento 2
*/
namespace Amasty\AdminActionsLog\Model\LogEntry;
use Amasty\AdminActionsLog\Model\Admin\SessionUserDataProvider;
use Magento\Framework\Stdlib\DateTime\DateTime;
class AdminLogEntryFactory
{
/**
* @var DateTime
*/
private $dateTime;
/**
* @var LogEntryFactory
*/
private $logEntryFactory;
/**
* @var SessionUserDataProvider
*/
private $userDataProvider;
public function __construct(
DateTime $dateTime,
LogEntryFactory $logEntryFactory,
SessionUserDataProvider $userDataProvider
) {
$this->dateTime = $dateTime;
$this->logEntryFactory = $logEntryFactory;
$this->userDataProvider = $userDataProvider;
}
public function create(array $data = [])
{
$data = array_merge(
[
LogEntry::DATE => $this->dateTime->gmtDate(),
LogEntry::USERNAME => $this->userDataProvider->getUserName(),
LogEntry::PARAMETER_NAME => 'id',
LogEntry::STORE_ID => 0,
LogEntry::IP => $this->userDataProvider->getIpAddress(),
],
$data
);
$logEntry = $this->logEntryFactory->create(['data' => $data]);
$logEntry->setHasDataChanges(true);
return $logEntry;
}
}
@@ -0,0 +1,62 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Admin Actions Log for Magento 2
*/
namespace Amasty\AdminActionsLog\Model\LogEntry\Frontend;
use Amasty\AdminActionsLog\Api\LogEntryRepositoryInterface;
use Amasty\AdminActionsLog\Model\DiffFinder\DiffFinderAdapterInterface;
use Amasty\AdminActionsLog\Model\LogEntry\LogDetail;
class LogDetailsFormatter
{
public const TAG_INS = 'ins';
public const TAB_DEL = 'del';
/**
* @var LogEntryRepositoryInterface
*/
private $logEntryRepository;
/**
* @var DiffFinderAdapterInterface
*/
private $diffFinder;
public function __construct(
LogEntryRepositoryInterface $logEntryRepository,
DiffFinderAdapterInterface $diffFinder
) {
$this->logEntryRepository = $logEntryRepository;
$this->diffFinder = $diffFinder;
}
public function format(int $logEntryId): array
{
$logEntry = $this->logEntryRepository->getById($logEntryId);
return array_map(function ($logDetail) {
$diffString = $this->diffFinder->render(
(string)$logDetail->getOldValue(),
(string)$logDetail->getNewValue()
);
return [
LogDetail::NAME => $logDetail->getName(),
LogDetail::OLD_VALUE => $this->removeDiffTags($diffString, self::TAG_INS),
LogDetail::NEW_VALUE => $this->removeDiffTags($diffString, self::TAB_DEL),
];
}, $logEntry->getLogDetails());
}
private function removeDiffTags(string $text, string $tagName): string
{
return (string)preg_replace("/<$tagName>(.*?)<\/$tagName>/s", '', $text);
}
}
@@ -0,0 +1,95 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Admin Actions Log for Magento 2
*/
namespace Amasty\AdminActionsLog\Model\LogEntry;
use Amasty\AdminActionsLog\Api\Data\LogDetailInterface;
use Magento\Framework\Model\AbstractModel;
class LogDetail extends AbstractModel implements LogDetailInterface
{
/**#@+
* Constants defined for keys of data array
*/
public const ID = 'id';
public const LOG_ID = 'log_id';
public const NAME = 'name';
public const OLD_VALUE = 'old_value';
public const NEW_VALUE = 'new_value';
public const MODEL = 'model';
/**#@-*/
public function _construct()
{
parent::_construct();
$this->_init(ResourceModel\LogDetail::class);
$this->setIdFieldName(self::ID);
}
public function getLogId(): ?int
{
return $this->hasData(self::LOG_ID) ? (int)$this->_getData(self::LOG_ID) : null;
}
public function setLogId(int $logId): LogDetailInterface
{
$this->setData(self::LOG_ID, $logId);
return $this;
}
public function getName(): ?string
{
return $this->_getData(self::NAME);
}
public function setName(string $name): LogDetailInterface
{
$this->setData(self::NAME, $name);
return $this;
}
public function getOldValue(): ?string
{
return $this->_getData(self::OLD_VALUE);
}
public function setOldValue(string $oldValue): LogDetailInterface
{
$this->setData(self::OLD_VALUE, $oldValue);
return $this;
}
public function getNewValue(): ?string
{
return $this->_getData(self::NEW_VALUE);
}
public function setNewValue(string $newValue): LogDetailInterface
{
$this->setData(self::NEW_VALUE, $newValue);
return $this;
}
public function getModel(): ?string
{
return $this->_getData(self::MODEL);
}
public function setModel(string $model): LogDetailInterface
{
$this->setData(self::MODEL, $model);
return $this;
}
}
+201
View File
@@ -0,0 +1,201 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Admin Actions Log for Magento 2
*/
namespace Amasty\AdminActionsLog\Model\LogEntry;
use Amasty\AdminActionsLog\Api\Data\LogEntryInterface;
use Magento\Framework\Model\AbstractModel;
class LogEntry extends AbstractModel implements LogEntryInterface
{
/**#@+
* Constants defined for keys of data array
*/
public const ID = 'id';
public const DATE = 'date';
public const USERNAME = 'username';
public const TYPE = 'type';
public const CATEGORY = 'category';
public const CATEGORY_NAME = 'category_name';
public const PARAMETER_NAME = 'parameter_name';
public const ELEMENT_ID = 'element_id';
public const VIEW_ELEMENT_ID = 'view_element_id';
public const ITEM = 'item';
public const IP = 'ip';
public const STORE_ID = 'store_id';
public const ADDITIONAL_DATA = 'additional_data';
public const LOG_DETAILS = 'log_details';
/**#@-*/
public function _construct()
{
parent::_construct();
$this->_init(ResourceModel\LogEntry::class);
$this->setIdFieldName(self::ID);
}
public function getDate(): ?string
{
return $this->_getData(self::DATE);
}
public function setDate(string $date): LogEntryInterface
{
$this->setData(self::DATE, $date);
return $this;
}
public function getUsername(): ?string
{
return $this->_getData(self::USERNAME);
}
public function setUsername(string $username): LogEntryInterface
{
$this->setData(self::USERNAME, $username);
return $this;
}
public function getType(): ?string
{
return $this->_getData(self::TYPE);
}
public function setType(string $type): LogEntryInterface
{
$this->setData(self::TYPE, $type);
return $this;
}
public function getCategory(): ?string
{
return $this->_getData(self::CATEGORY);
}
public function setCategory(string $category): LogEntryInterface
{
$this->setData(self::CATEGORY, $category);
return $this;
}
public function getCategoryName(): ?string
{
return $this->_getData(self::CATEGORY_NAME);
}
public function setCategoryName(string $categoryName): LogEntryInterface
{
$this->setData(self::CATEGORY_NAME, $categoryName);
return $this;
}
public function getParameterName(): ?string
{
return $this->_getData(self::PARAMETER_NAME);
}
public function setParameterName(string $parameterName): LogEntryInterface
{
$this->setData(self::PARAMETER_NAME, $parameterName);
return $this;
}
public function getElementId(): int
{
return (int)$this->_getData(self::ELEMENT_ID);
}
public function setElementId(int $elementId): LogEntryInterface
{
$this->setData(self::ELEMENT_ID, $elementId);
return $this;
}
public function getViewElementId(): ?int
{
return $this->hasData(self::VIEW_ELEMENT_ID)
? (int)$this->_getData(self::VIEW_ELEMENT_ID)
: null;
}
public function setViewElementId(?int $viewElementId): LogEntryInterface
{
$this->setData(self::VIEW_ELEMENT_ID, $viewElementId);
return $this;
}
public function getItem(): ?string
{
return $this->_getData(self::ITEM);
}
public function setItem(string $item): LogEntryInterface
{
$this->setData(self::ITEM, $item);
return $this;
}
public function getIp(): ?string
{
return $this->_getData(self::IP);
}
public function setIp(string $ipAddress): LogEntryInterface
{
$this->setData(self::IP, $ipAddress);
return $this;
}
public function getStoreId(): ?int
{
return $this->hasData(self::STORE_ID) ? (int)$this->_getData(self::STORE_ID) : null;
}
public function setStoreId(int $storeId): LogEntryInterface
{
$this->setData(self::STORE_ID, $storeId);
return $this;
}
public function getAdditionalData()
{
return $this->_getData(self::ADDITIONAL_DATA);
}
public function setAdditionalData($additionalData): LogEntryInterface
{
$this->setData(self::ADDITIONAL_DATA, $additionalData);
return $this;
}
public function getLogDetails(): array
{
return (array)$this->_getData(self::LOG_DETAILS);
}
public function setLogDetails(array $logDetails): LogEntryInterface
{
$this->setData(self::LOG_DETAILS, $logDetails);
return $this;
}
}
@@ -0,0 +1,21 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Admin Actions Log for Magento 2
*/
namespace Amasty\AdminActionsLog\Model\LogEntry;
use Amasty\AdminActionsLog\Api\Data\LogEntrySearchResultsInterface;
use Magento\Framework\Api\SearchResults;
/**
* Service Data Object with Log Entry search results.
*/
class LogEntrySearchResults extends SearchResults implements LogEntrySearchResultsInterface
{
}
@@ -0,0 +1,261 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Admin Actions Log for Magento 2
*/
namespace Amasty\AdminActionsLog\Model\LogEntry;
use Amasty\AdminActionsLog\Api\Data\LogEntryInterface;
use Amasty\AdminActionsLog\Api\Data\LogEntryInterfaceFactory;
use Amasty\AdminActionsLog\Api\Data\LogEntrySearchResultsInterface;
use Amasty\AdminActionsLog\Api\Data\LogEntrySearchResultsInterfaceFactory;
use Amasty\AdminActionsLog\Api\LogEntryRepositoryInterface;
use Amasty\AdminActionsLog\Model\LogEntry\LogDetail as LogDetailModel;
use Amasty\AdminActionsLog\Model\LogEntry\ResourceModel\LogDetail as LogDetailResource;
use Amasty\AdminActionsLog\Model\LogEntry\ResourceModel\LogDetailCollectionFactory;
use Amasty\Base\Model\Serializer;
use Magento\Framework\Api\Search\FilterGroup;
use Magento\Framework\Api\SearchCriteriaInterface;
use Magento\Framework\Api\SortOrder;
use Magento\Framework\Exception\CouldNotDeleteException;
use Magento\Framework\Exception\CouldNotSaveException;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\Stdlib\DateTime\DateTime;
class Repository implements LogEntryRepositoryInterface
{
/**
* @var LogEntrySearchResultsInterfaceFactory
*/
private $searchResultsFactory;
/**
* @var LogEntryInterfaceFactory
*/
private $logEntryFactory;
/**
* @var ResourceModel\LogEntry
*/
private $logEntryResource;
/**
* @var ResourceModel\CollectionFactory
*/
private $logEntryCollectionFactory;
/**
* @var LogDetailResource
*/
private $logDetailResource;
/**
* @var LogDetailCollectionFactory
*/
private $logDetailCollectionFactory;
/**
* @var DateTime
*/
private $dateTime;
/**
* @var Serializer
*/
private $serializer;
/**
* @var array
*/
private $logEntries = [];
public function __construct(
LogEntrySearchResultsInterfaceFactory $searchResultsFactory,
LogEntryInterfaceFactory $logEntryFactory,
ResourceModel\LogEntry $logEntryResource,
ResourceModel\CollectionFactory $logEntryCollectionFactory,
LogDetailResource $logDetailResource,
LogDetailCollectionFactory $logDetailCollectionFactory,
DateTime $dateTime,
Serializer $serializer
) {
$this->searchResultsFactory = $searchResultsFactory;
$this->logEntryFactory = $logEntryFactory;
$this->logEntryResource = $logEntryResource;
$this->logEntryCollectionFactory = $logEntryCollectionFactory;
$this->logDetailResource = $logDetailResource;
$this->logDetailCollectionFactory = $logDetailCollectionFactory;
$this->dateTime = $dateTime;
$this->serializer = $serializer;
}
public function getById(int $id): LogEntryInterface
{
if (!isset($this->logEntries[$id])) {
/** @var LogEntryInterface $logEntry */
$logEntry = $this->logEntryFactory->create();
$this->logEntryResource->load($logEntry, $id);
if (!$logEntry->getId()) {
throw new NoSuchEntityException(__('Log Entry with specified ID "%1" not found.', $id));
}
$logEntry->setLogDetails($this->getLogDetails((int)$logEntry->getId()));
$logEntry->setAdditionalData($this->serializer->unserialize($logEntry->getAdditionalData()));
$this->logEntries[$id] = $logEntry;
}
return $this->logEntries[$id];
}
public function save(LogEntryInterface $logEntry): LogEntryInterface
{
try {
if ($logEntry->getId()) {
$logEntry = $this->getById((int)$logEntry->getId())->addData($logEntry->getData());
}
if ($logEntry->getAdditionalData()) {
$logEntry->setAdditionalData($this->serializer->serialize($logEntry->getAdditionalData()));
}
$this->logEntryResource->save($logEntry);
/** @var LogDetailModel $logDetail */
foreach ($logEntry->getLogDetails() as $logDetail) {
$logDetail->setLogId((int)$logEntry->getId());
$this->logDetailResource->save($logDetail);
}
unset($this->logEntries[$logEntry->getId()]);
} catch (\Exception $e) {
throw new CouldNotSaveException(__('Unable to save the Log Entry. Error: %1', $e->getMessage()));
}
return $logEntry;
}
public function delete(LogEntryInterface $logEntry): bool
{
try {
$this->logEntryResource->delete($logEntry);
unset($this->logEntries[$logEntry->getId()]);
} catch (\Exception $e) {
throw new CouldNotDeleteException(__('Unable to delete the Log Entry. Error: %1', $e->getMessage()));
}
return true;
}
public function deleteById(int $id): bool
{
return $this->delete($this->getById($id));
}
public function getList(SearchCriteriaInterface $searchCriteria): LogEntrySearchResultsInterface
{
$searchResults = $this->searchResultsFactory->create();
$searchResults->setSearchCriteria($searchCriteria);
/** @var ResourceModel\Collection $logEntryCollection */
$logEntryCollection = $this->logEntryCollectionFactory->create();
// Add filters from root filter group to the collection
foreach ($searchCriteria->getFilterGroups() as $group) {
$this->addFilterGroupToCollection($group, $logEntryCollection);
}
$searchResults->setTotalCount($logEntryCollection->getSize());
$sortOrders = $searchCriteria->getSortOrders();
if ($sortOrders) {
$this->addOrderToCollection($sortOrders, $logEntryCollection);
}
$logEntryCollection->setCurPage($searchCriteria->getCurrentPage());
$logEntryCollection->setPageSize($searchCriteria->getPageSize());
$logEntries = [];
/** @var LogEntryInterface $logEntry */
foreach ($logEntryCollection->getItems() as $logEntry) {
$logEntries[] = $this->getById((int)$logEntry->getId());
}
$searchResults->setItems($logEntries);
return $searchResults;
}
public function clean(?int $period = null): void
{
$connection = $this->logEntryResource->getConnection();
$tableName = $this->logEntryResource->getMainTable();
if ($period === null) {
$connection->delete($tableName);
} else {
$time = '-' . $period . ' days';
$connection->delete(
$tableName,
[LogEntry::DATE . ' < ?' => $this->dateTime->gmtDate('Y-m-d H:i:s', $time)]
);
}
}
public function cleanByStoreIds(?array $storeIds = []): void
{
$connection = $this->logEntryResource->getConnection();
$tableName = $this->logEntryResource->getMainTable();
$connection->delete(
$tableName,
[LogEntry::STORE_ID . ' IN (?)' => $storeIds]
);
}
private function getLogDetails(int $logEntryId): array
{
/** @var ResourceModel\LogDetailCollection $collection */
$collection = $this->logDetailCollectionFactory->create();
$collection->addFieldToFilter(LogDetailModel::LOG_ID, $logEntryId);
return $collection->getItems();
}
/**
* Helper function that adds a FilterGroup to the collection.
*
* @param FilterGroup $filterGroup
* @param ResourceModel\Collection $logEntryCollection
*
* @return void
*/
private function addFilterGroupToCollection(
FilterGroup $filterGroup,
ResourceModel\Collection $logEntryCollection
): void {
foreach ($filterGroup->getFilters() as $filter) {
$condition = $filter->getConditionType() ? $filter->getConditionType() : 'eq';
$logEntryCollection->addFieldToFilter($filter->getField(), [$condition => $filter->getValue()]);
}
}
/**
* Helper function that adds a SortOrder to the collection.
*
* @param SortOrder[] $sortOrders
* @param ResourceModel\Collection $logEntryCollection
*
* @return void
*/
private function addOrderToCollection(
array $sortOrders,
ResourceModel\Collection $logEntryCollection
): void {
foreach ($sortOrders as $sortOrder) {
$field = $sortOrder->getField();
$logEntryCollection->addOrder(
$field,
($sortOrder->getDirection() == SortOrder::SORT_DESC) ? 'DESC' : 'ASC'
);
}
}
}
@@ -0,0 +1,24 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Admin Actions Log for Magento 2
*/
namespace Amasty\AdminActionsLog\Model\LogEntry\ResourceModel;
use Amasty\AdminActionsLog\Model\LogEntry\LogEntry as LogEntryModel;
use Amasty\AdminActionsLog\Model\LogEntry\ResourceModel\LogEntry as LogEntryResource;
use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection;
class Collection extends AbstractCollection
{
public function _construct()
{
$this->_init(LogEntryModel::class, LogEntryResource::class);
$this->_setIdFieldName($this->getResource()->getIdFieldName());
}
}
@@ -0,0 +1,44 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Admin Actions Log for Magento 2
*/
namespace Amasty\AdminActionsLog\Model\LogEntry\ResourceModel\Grid;
use Amasty\AdminActionsLog\Model\LogEntry\ResourceModel\LogEntry as LogEntryResource;
use Magento\Framework\View\Element\UiComponent\DataProvider\Document;
use Magento\Framework\View\Element\UiComponent\DataProvider\SearchResult;
class Collection extends SearchResult
{
public const ADMIN_TABLE_ALIAS = 'amasty_admin_user';
public const FULL_NAME_EXPR = "CONCAT(amasty_admin_user.firstname, ' ' ,amasty_admin_user.lastname)";
protected function _construct()
{
$this->_init(Document::class, LogEntryResource::class);
$this->setMainTable(LogEntryResource::TABLE_NAME);
$this->addFilterToMap('full_name', new \Zend_Db_Expr(self::FULL_NAME_EXPR));
$this->addFilterToMap('username', 'main_table.username');
}
protected function _initSelect()
{
parent::_initSelect();
$this->getSelect()->joinLeft(
[self::ADMIN_TABLE_ALIAS => $this->getTable('admin_user')],
'main_table.username = ' . self::ADMIN_TABLE_ALIAS . '.username',
[
'full_name' => new \Zend_Db_Expr(self::FULL_NAME_EXPR),
'email' => self::ADMIN_TABLE_ALIAS . '.email',
]
);
return $this;
}
}
@@ -0,0 +1,24 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Admin Actions Log for Magento 2
*/
namespace Amasty\AdminActionsLog\Model\LogEntry\ResourceModel;
use Amasty\AdminActionsLog\Model\LogEntry\LogDetail as LogDetailModel;
use Magento\Framework\Model\ResourceModel\Db\AbstractDb;
class LogDetail extends AbstractDb
{
public const TABLE_NAME = 'amasty_audit_log_details';
protected function _construct()
{
$this->_init(self::TABLE_NAME, LogDetailModel::ID);
}
}
@@ -0,0 +1,24 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Admin Actions Log for Magento 2
*/
namespace Amasty\AdminActionsLog\Model\LogEntry\ResourceModel;
use Amasty\AdminActionsLog\Model\LogEntry\LogDetail as LogDetailModel;
use Amasty\AdminActionsLog\Model\LogEntry\ResourceModel\LogDetail as LogDetailResource;
use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection;
class LogDetailCollection extends AbstractCollection
{
public function _construct()
{
$this->_init(LogDetailModel::class, LogDetailResource::class);
$this->_setIdFieldName($this->getResource()->getIdFieldName());
}
}
@@ -0,0 +1,24 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Admin Actions Log for Magento 2
*/
namespace Amasty\AdminActionsLog\Model\LogEntry\ResourceModel;
use Amasty\AdminActionsLog\Model\LogEntry\LogEntry as LogEntryModel;
use Magento\Framework\Model\ResourceModel\Db\AbstractDb;
class LogEntry extends AbstractDb
{
public const TABLE_NAME = 'amasty_audit_log_entry';
protected function _construct()
{
$this->_init(self::TABLE_NAME, LogEntryModel::ID);
}
}
@@ -0,0 +1,118 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Admin Actions Log for Magento 2
*/
namespace Amasty\AdminActionsLog\Model\LoginAttempt;
use Amasty\AdminActionsLog\Api\Data\LoginAttemptInterface;
use Magento\Framework\Model\AbstractModel;
class LoginAttempt extends AbstractModel implements LoginAttemptInterface
{
/**#@+
* Constants defined for keys of data array
*/
public const ID = 'id';
public const DATE = 'date';
public const USERNAME = 'username';
public const FULL_NAME = 'full_name';
public const IP = 'ip';
public const STATUS = 'status';
public const LOCATION = 'location';
public const COUNTRY_ID = 'country_id';
public const USER_AGENT = 'user_agent';
/**#@-*/
public function _construct()
{
parent::_construct();
$this->_init(ResourceModel\LoginAttempt::class);
$this->setIdFieldName(self::ID);
}
public function getDate(): ?string
{
return $this->_getData(self::DATE);
}
public function setDate(string $date): LoginAttemptInterface
{
return $this->setData(self::DATE, $date);
}
public function getUsername(): ?string
{
return $this->_getData(self::USERNAME);
}
public function setUsername(string $username): LoginAttemptInterface
{
return $this->setData(self::USERNAME, $username);
}
public function getFullName(): ?string
{
return $this->_getData(self::FULL_NAME);
}
public function setFullName(string $fullName): LoginAttemptInterface
{
return $this->setData(self::FULL_NAME, $fullName);
}
public function getIp(): ?string
{
return $this->_getData(self::IP);
}
public function setIp(string $ip): LoginAttemptInterface
{
return $this->setData(self::IP, $ip);
}
public function getStatus(): ?int
{
return $this->hasData(self::STATUS) ? (int)$this->_getData(self::STATUS) : null;
}
public function setStatus(int $status): LoginAttemptInterface
{
return $this->setData(self::STATUS, $status);
}
public function getLocation(): ?string
{
return $this->_getData(self::LOCATION);
}
public function setLocation(string $location): LoginAttemptInterface
{
return $this->setData(self::LOCATION, $location);
}
public function getCountryId(): ?string
{
return $this->_getData(self::COUNTRY_ID);
}
public function setCountryId(string $countryId): LoginAttemptInterface
{
return $this->setData(self::COUNTRY_ID, $countryId);
}
public function getUserAgent(): ?string
{
return $this->_getData(self::USER_AGENT);
}
public function setUserAgent(string $userAgent): LoginAttemptInterface
{
return $this->setData(self::USER_AGENT, $userAgent);
}
}
@@ -0,0 +1,102 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Admin Actions Log for Magento 2
*/
namespace Amasty\AdminActionsLog\Model\LoginAttempt;
use Amasty\AdminActionsLog\Api\Data\LoginAttemptInterfaceFactory;
use Amasty\AdminActionsLog\Api\LoginAttemptManagerInterface;
use Amasty\AdminActionsLog\Api\LoginAttemptRepositoryInterface;
use Amasty\AdminActionsLog\Model\Admin\SessionUserDataProvider;
use Amasty\AdminActionsLog\Model\ConfigProvider;
use Amasty\AdminActionsLog\Model\LoginAttempt\Notification\Processor;
use Magento\Framework\Stdlib\DateTime\DateTime;
use Magento\User\Api\Data\UserInterfaceFactory;
class LoginAttemptManager implements LoginAttemptManagerInterface
{
/**
* @var SessionUserDataProvider
*/
private $sessionUserDataProvider;
/**
* @var LoginAttemptInterfaceFactory
*/
private $loginAttemptFactory;
/**
* @var LoginAttemptRepositoryInterface
*/
private $loginAttemptRepository;
/**
* @var UserInterfaceFactory
*/
private $userFactory;
/**
* @var Processor
*/
private $notificationProcessor;
/**
* @var ConfigProvider
*/
private $configProvider;
/**
* @var DateTime
*/
private $dateTime;
public function __construct(
SessionUserDataProvider $sessionUserDataProvider,
LoginAttemptInterfaceFactory $loginAttemptFactory,
LoginAttemptRepositoryInterface $loginAttemptRepository,
UserInterfaceFactory $userFactory,
Processor $notificationProcessor,
ConfigProvider $configProvider,
DateTime $dateTime
) {
$this->sessionUserDataProvider = $sessionUserDataProvider;
$this->loginAttemptFactory = $loginAttemptFactory;
$this->loginAttemptRepository = $loginAttemptRepository;
$this->userFactory = $userFactory;
$this->notificationProcessor = $notificationProcessor;
$this->configProvider = $configProvider;
$this->dateTime = $dateTime;
}
public function saveAttempt(?string $username, int $status): void
{
$userData = $this->sessionUserDataProvider->getUserPreparedData();
$loginAttempt = $this->loginAttemptFactory->create(['data' => $userData]);
$loginAttempt->setDate($this->dateTime->date());
$loginAttempt->setStatus($status);
$loginAttempt->setUserAgent($this->sessionUserDataProvider->getUserAgent());
if ($username && !$this->sessionUserDataProvider->getUserName()) {
$loginAttempt->setUsername($username)->setFullName($username);
$user = $this->userFactory->create()->loadByUsername($username);
if ($user->getId()) {
$loginAttempt->setUsername($user->getUserName());
$loginAttempt->setFullName($user->getFirstName() . ' ' . $user->getLastName());
}
}
$this->loginAttemptRepository->save($loginAttempt);
$this->notificationProcessor->execute($loginAttempt);
}
public function clear(int $period = null): void
{
$this->loginAttemptRepository->clean($period);
}
}
@@ -0,0 +1,21 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Admin Actions Log for Magento 2
*/
namespace Amasty\AdminActionsLog\Model\LoginAttempt;
use Amasty\AdminActionsLog\Api\Data\LoginAttemptSearchResultsInterface;
use Magento\Framework\Api\SearchResults;
/**
* Service Data Object with Log Entry search results.
*/
class LoginAttemptSearchResults extends SearchResults implements LoginAttemptSearchResultsInterface
{
}
@@ -0,0 +1,36 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Admin Actions Log for Magento 2
*/
namespace Amasty\AdminActionsLog\Model\LoginAttempt\Notification;
use Amasty\AdminActionsLog\Api\Data\LoginAttemptInterface;
use Amasty\AdminActionsLog\Model\LoginAttempt\Notification\Type\AttemptNotificatorInterface;
class Processor
{
/**
* @var AttemptNotificatorInterface[]
*/
private $notifierTypes;
public function __construct(array $notifierTypes = [])
{
$this->notifierTypes = $notifierTypes;
}
public function execute(LoginAttemptInterface $loginAttempt)
{
$attemptStatus = $loginAttempt->getStatus();
if ($attemptStatus !== null && isset($this->notifierTypes[$attemptStatus])) {
$this->notifierTypes[$attemptStatus]->execute($loginAttempt);
}
}
}
@@ -0,0 +1,20 @@
<?php
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Admin Actions Log for Magento 2
*/
namespace Amasty\AdminActionsLog\Model\LoginAttempt\Notification\Type;
use Amasty\AdminActionsLog\Api\Data\LoginAttemptInterface;
interface AttemptNotificatorInterface
{
/**
* Performs Login Attempt notification.
*
* @param LoginAttemptInterface $loginAttempt
*/
public function execute(LoginAttemptInterface $loginAttempt): void;
}
@@ -0,0 +1,115 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Admin Actions Log for Magento 2
*/
namespace Amasty\AdminActionsLog\Model\LoginAttempt\Notification\Type;
use Amasty\AdminActionsLog\Api\Data\LoginAttemptInterface;
use Amasty\AdminActionsLog\Api\Logging\ObjectDataStorageInterface;
use Amasty\AdminActionsLog\Model\ConfigProvider;
use Amasty\AdminActionsLog\Model\LoginAttempt\LoginAttempt;
use Amasty\AdminActionsLog\Model\LoginAttempt\ResourceModel\CollectionFactory as AttemptCollectionFactory;
use Amasty\AdminActionsLog\Model\OptionSource\LoginAttemptStatus;
use Amasty\AdminActionsLog\Utils\EmailSender;
use Magento\Framework\App\Area;
use Magento\Framework\Stdlib\DateTime\DateTime;
class Failed implements AttemptNotificatorInterface
{
public const STORAGE_KEY = 'failed_notified_at';
/**
* @var AttemptCollectionFactory
*/
private $attemptCollectionFactory;
/**
* @var ObjectDataStorageInterface
*/
private $dataStorage;
/**
* @var ConfigProvider
*/
private $configProvider;
/**
* @var EmailSender
*/
private $emailSender;
/**
* @var DateTime
*/
private $dateTime;
/**
* @var int
*/
private $failedRangeDuration;
/**
* @var int
*/
private $minFailedCount;
public function __construct(
AttemptCollectionFactory $attemptCollectionFactory,
ObjectDataStorageInterface $dataStorage,
ConfigProvider $configProvider,
EmailSender $emailSender,
DateTime $dateTime,
int $failedRangeDuration = 3600,
int $minFailedCount = 5
) {
$this->attemptCollectionFactory = $attemptCollectionFactory;
$this->dataStorage = $dataStorage;
$this->configProvider = $configProvider;
$this->emailSender = $emailSender;
$this->dateTime = $dateTime;
$this->failedRangeDuration = $failedRangeDuration;
$this->minFailedCount = $minFailedCount;
}
public function execute(LoginAttemptInterface $loginAttempt): void
{
$isEnabled = $this->configProvider->isEnabledEmailUnsuccessfulLoginsToAdmin();
$lastNotificationTimestamp = $this->dataStorage->get(self::STORAGE_KEY)['timestamp'] ?? 1;
$failedAttemptsCount = $this->getFailedAttemptsCount($lastNotificationTimestamp);
$minFailedAttemptsCount = $this->configProvider->getNumberUnsuccessfulLoginAttempts() ?: $this->minFailedCount;
if ($isEnabled && $failedAttemptsCount >= $minFailedAttemptsCount) {
$this->emailSender->sendEmail(
$this->configProvider->getSendToEmailsUnsuccessfulLogins(),
$this->configProvider->getTemplateEmailUnsuccessfulLogins(),
$this->configProvider->getSenderEmailUnsuccessfulLogins(),
['unsuccessful_login_count' => $failedAttemptsCount],
Area::AREA_ADMINHTML
);
$this->dataStorage->set(self::STORAGE_KEY, ['timestamp' => $this->dateTime->gmtTimestamp()]);
}
}
private function getFailedAttemptsCount(int $lastNotificationTimestamp): int
{
$currentTimestamp = $this->dateTime->gmtTimestamp();
if ($this->failedRangeDuration > $currentTimestamp - $lastNotificationTimestamp) {
return 0;
}
$attemptCollection = $this->attemptCollectionFactory->create();
$attemptCollection->addFieldToFilter(LoginAttempt::STATUS, LoginAttemptStatus::FAILED);
$attemptCollection->addFieldToFilter(
LoginAttempt::DATE,
['gteq' => $this->dateTime->gmtDate(null, $lastNotificationTimestamp)]
);
return $attemptCollection->count();
}
}
@@ -0,0 +1,86 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Admin Actions Log for Magento 2
*/
namespace Amasty\AdminActionsLog\Model\LoginAttempt\Notification\Type;
use Amasty\AdminActionsLog\Api\Data\LoginAttemptInterface;
use Amasty\AdminActionsLog\Model\ConfigProvider;
use Amasty\AdminActionsLog\Model\LoginAttempt\SuspiciousDetection\Detector;
use Amasty\AdminActionsLog\Utils\EmailSender;
use Magento\Framework\App\Area;
class Succeed implements AttemptNotificatorInterface
{
/**
* @var Detector
*/
private $suspiciousDetector;
/**
* @var EmailSender
*/
private $emailSender;
/**
* @var ConfigProvider
*/
private $configProvider;
public function __construct(
Detector $suspiciousDetector,
EmailSender $emailSender,
ConfigProvider $configProvider
) {
$this->suspiciousDetector = $suspiciousDetector;
$this->emailSender = $emailSender;
$this->configProvider = $configProvider;
}
public function execute(LoginAttemptInterface $loginAttempt): void
{
if ($this->isSuspiciousLogin($loginAttempt)) {
$isEnabled = $this->configProvider->isEnabledEmailSuspiciousLoginsToAdmin();
$recipients = $this->configProvider->getSendToEmailsSuspiciousLogins();
$template = $this->configProvider->getTemplateEmailSuspiciousLogins();
$sender = $this->configProvider->getSenderEmailSuspiciousLogins();
} else {
$isEnabled = $this->configProvider->isEnabledEmailSuccessfulLoginsToAdmin();
$recipients = $this->configProvider->getSendToEmailsSuccessfulLogins();
$template = $this->configProvider->getTemplateEmailSuccessfulLogins();
$sender = $this->configProvider->getSenderEmailSuccessfulLogins();
}
if ($isEnabled) {
$this->emailSender->sendEmail(
$recipients,
$template,
$sender,
[
'username' => $loginAttempt->getUsername(),
'full_name' => $loginAttempt->getFullName(),
'ip' => $loginAttempt->getIp(),
'country_id' => $loginAttempt->getCountryId()
],
Area::AREA_ADMINHTML
);
}
}
private function isSuspiciousLogin(LoginAttemptInterface $loginAttempt): bool
{
foreach ($this->configProvider->getListSuspiciousLoggedInWith() as $detectionType) {
if ($this->suspiciousDetector->isSuspicious($detectionType, $loginAttempt)) {
return true;
}
}
return false;
}
}
@@ -0,0 +1,203 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Admin Actions Log for Magento 2
*/
namespace Amasty\AdminActionsLog\Model\LoginAttempt;
use Amasty\AdminActionsLog\Api\Data\LoginAttemptSearchResultsInterface;
use Amasty\AdminActionsLog\Api\Data\LoginAttemptSearchResultsInterfaceFactory;
use Amasty\AdminActionsLog\Api\LoginAttemptRepositoryInterface;
use Amasty\AdminActionsLog\Api\Data\LoginAttemptInterface;
use Amasty\AdminActionsLog\Api\Data\LoginAttemptInterfaceFactory;
use Magento\Framework\Api\Search\FilterGroup;
use Magento\Framework\Api\SearchCriteriaInterface;
use Magento\Framework\Api\SortOrder;
use Magento\Framework\Exception\CouldNotDeleteException;
use Magento\Framework\Exception\CouldNotSaveException;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\Stdlib\DateTime\DateTime;
class Repository implements LoginAttemptRepositoryInterface
{
/**
* @var LoginAttemptSearchResultsInterfaceFactory
*/
private $searchResultsFactory;
/**
* @var LoginAttemptInterfaceFactory
*/
private $loginAttemptFactory;
/**
* @var ResourceModel\LoginAttempt
*/
private $resource;
/**
* @var ResourceModel\CollectionFactory
*/
private $collectionFactory;
/**
* @var DateTime
*/
private $dateTime;
/**
* @var array
*/
private $loginAttempts = [];
public function __construct(
LoginAttemptSearchResultsInterfaceFactory $searchResultsFactory,
LoginAttemptInterfaceFactory $loginAttemptFactory,
ResourceModel\LoginAttempt $resource,
ResourceModel\CollectionFactory $collectionFactory,
DateTime $dateTime
) {
$this->loginAttemptFactory = $loginAttemptFactory;
$this->resource = $resource;
$this->collectionFactory = $collectionFactory;
$this->searchResultsFactory = $searchResultsFactory;
$this->dateTime = $dateTime;
}
public function getById(int $id): LoginAttemptInterface
{
if (!isset($this->loginAttempts[$id])) {
/** @var LoginAttemptInterface $loginAttempt */
$loginAttempt = $this->loginAttemptFactory->create();
$this->resource->load($loginAttempt, $id);
if (!$loginAttempt->getId()) {
throw new NoSuchEntityException(__('Login Attempt with specified ID "%1" not found.', $id));
}
$this->loginAttempts[$id] = $loginAttempt;
}
return $this->loginAttempts[$id];
}
public function save(LoginAttemptInterface $loginAttempt): LoginAttemptInterface
{
try {
if ($loginAttempt->getId()) {
$loginAttempt = $this->getById((int)$loginAttempt->getId())->addData($loginAttempt->getData());
}
$this->resource->save($loginAttempt);
unset($this->loginAttempts[$loginAttempt->getId()]);
} catch (\Exception $e) {
throw new CouldNotSaveException(__('Unable to save the Login Attempt. Error: %1', $e->getMessage()));
}
return $loginAttempt;
}
public function delete(LoginAttemptInterface $loginAttempt): bool
{
try {
$this->resource->delete($loginAttempt);
unset($this->loginAttempts[$loginAttempt->getId()]);
} catch (\Exception $e) {
throw new CouldNotDeleteException(__('Unable to delete the Login Attempt. Error: %1', $e->getMessage()));
}
return true;
}
public function deleteById(int $id): bool
{
return $this->delete($this->getById($id));
}
public function getList(SearchCriteriaInterface $searchCriteria): LoginAttemptSearchResultsInterface
{
$searchResults = $this->searchResultsFactory->create();
$searchResults->setSearchCriteria($searchCriteria);
/** @var ResourceModel\Collection $loginAttemptCollection */
$loginAttemptCollection = $this->collectionFactory->create();
// Add filters from root filter group to the collection
foreach ($searchCriteria->getFilterGroups() as $group) {
$this->addFilterGroupToCollection($group, $loginAttemptCollection);
}
$searchResults->setTotalCount($loginAttemptCollection->getSize());
$sortOrders = $searchCriteria->getSortOrders();
if ($sortOrders) {
$this->addOrderToCollection($sortOrders, $loginAttemptCollection);
}
$loginAttemptCollection->setCurPage($searchCriteria->getCurrentPage());
$loginAttemptCollection->setPageSize($searchCriteria->getPageSize());
$loginAttempts = [];
/** @var LoginAttemptInterface $loginAttempt */
foreach ($loginAttemptCollection->getItems() as $loginAttempt) {
$loginAttempts[] = $this->getById((int)$loginAttempt->getId());
}
$searchResults->setItems($loginAttempts);
return $searchResults;
}
public function clean(?int $period = null): void
{
$connection = $this->resource->getConnection();
$tableName = $this->resource->getMainTable();
if ($period === null) {
$connection->truncateTable($tableName);
} else {
$time = '-' . $period . ' days';
$connection->delete(
$tableName,
[LoginAttempt::DATE . ' < ?' => $this->dateTime->gmtDate('Y-m-d H:i:s', $time)]
);
}
}
/**
* Helper function that adds a FilterGroup to the collection.
*
* @param FilterGroup $filterGroup
* @param ResourceModel\Collection $logEntryCollection
*
* @return void
*/
private function addFilterGroupToCollection(
FilterGroup $filterGroup,
ResourceModel\Collection $logEntryCollection
): void {
foreach ($filterGroup->getFilters() as $filter) {
$condition = $filter->getConditionType() ? $filter->getConditionType() : 'eq';
$logEntryCollection->addFieldToFilter($filter->getField(), [$condition => $filter->getValue()]);
}
}
/**
* Helper function that adds a SortOrder to the collection.
*
* @param SortOrder[] $sortOrders
* @param ResourceModel\Collection $logEntryCollection
*
* @return void
*/
private function addOrderToCollection(
array $sortOrders,
ResourceModel\Collection $logEntryCollection
): void {
foreach ($sortOrders as $sortOrder) {
$field = $sortOrder->getField();
$logEntryCollection->addOrder(
$field,
($sortOrder->getDirection() == SortOrder::SORT_DESC) ? 'DESC' : 'ASC'
);
}
}
}
@@ -0,0 +1,24 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Admin Actions Log for Magento 2
*/
namespace Amasty\AdminActionsLog\Model\LoginAttempt\ResourceModel;
use Amasty\AdminActionsLog\Model\LoginAttempt\LoginAttempt as LoginAttemptModel;
use Amasty\AdminActionsLog\Model\LoginAttempt\ResourceModel\LoginAttempt as LoginAttemptResource;
use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection;
class Collection extends AbstractCollection
{
public function _construct()
{
$this->_init(LoginAttemptModel::class, LoginAttemptResource::class);
$this->_setIdFieldName($this->getResource()->getIdFieldName());
}
}
@@ -0,0 +1,30 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Admin Actions Log for Magento 2
*/
namespace Amasty\AdminActionsLog\Model\LoginAttempt\ResourceModel\Grid;
use Magento\Framework\View\Element\UiComponent\DataProvider\SearchResult;
class Collection extends SearchResult
{
/**
* @return \Magento\Framework\Api\Search\DocumentInterface[]
*/
public function getItems()
{
$this->_setIsLoaded(false);
$this->_items = [];
$searchCriteria = $this->getSearchCriteria();
$this->setPageSize($searchCriteria->getPageSize());
$this->setCurPage($searchCriteria->getCurrentPage());
return parent::getItems();
}
}
@@ -0,0 +1,24 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Admin Actions Log for Magento 2
*/
namespace Amasty\AdminActionsLog\Model\LoginAttempt\ResourceModel;
use \Amasty\AdminActionsLog\Model\LoginAttempt\LoginAttempt as LoginAttemptModel;
use Magento\Framework\Model\ResourceModel\Db\AbstractDb;
class LoginAttempt extends AbstractDb
{
public const TABLE_NAME = 'amasty_audit_login_attempts';
protected function _construct()
{
$this->_init(self::TABLE_NAME, LoginAttemptModel::ID);
}
}
@@ -0,0 +1,33 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Admin Actions Log for Magento 2
*/
namespace Amasty\AdminActionsLog\Model\LoginAttempt\SuspiciousDetection;
use Amasty\AdminActionsLog\Api\Data\LoginAttemptInterface;
class Detector
{
/**
* @var Type\DetectorInterface[]
*/
private $detectionTypes;
public function __construct(array $detectionTypes = [])
{
$this->detectionTypes = $detectionTypes;
}
public function isSuspicious(string $type, LoginAttemptInterface $loginAttempt): bool
{
return isset($this->detectionTypes[$type])
? $this->detectionTypes[$type]->isSuspiciousAttempt($loginAttempt)
: false;
}
}
@@ -0,0 +1,64 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Admin Actions Log for Magento 2
*/
namespace Amasty\AdminActionsLog\Model\LoginAttempt\SuspiciousDetection\Type;
use Amasty\AdminActionsLog\Api\Data\LoginAttemptInterface;
use Amasty\AdminActionsLog\Api\Logging\ObjectDataStorageInterface;
use Amasty\AdminActionsLog\Model\LoginAttempt\LoginAttempt;
use Amasty\AdminActionsLog\Model\LoginAttempt\ResourceModel\CollectionFactory;
use Amasty\AdminActionsLog\Model\OptionSource\LoginAttemptStatus;
abstract class AbstractDetection implements DetectorInterface
{
/**
* @var CollectionFactory
*/
private $loginAttemptCollectionFactory;
/**
* @var ObjectDataStorageInterface
*/
private $dataStorage;
public function __construct(
CollectionFactory $loginAttemptCollectionFactory,
ObjectDataStorageInterface $dataStorage
) {
$this->loginAttemptCollectionFactory = $loginAttemptCollectionFactory;
$this->dataStorage = $dataStorage;
}
abstract public function isSuspiciousAttempt(LoginAttemptInterface $loginAttempt): bool;
public function getLastSucceedAttempt(LoginAttemptInterface $loginAttempt): LoginAttemptInterface
{
$storageKey = spl_object_id($loginAttempt) . '.none';
if ($this->dataStorage->isExists($storageKey)) {
$lastLoginAttempt = $this->dataStorage->get($storageKey);
return array_shift($lastLoginAttempt);
}
$loginAttemptCollection = $this->loginAttemptCollectionFactory->create();
$lastLoginAttempt = $loginAttemptCollection->addFieldToFilter(
LoginAttempt::USERNAME,
$loginAttempt->getUsername()
)->addFieldToFilter(LoginAttempt::STATUS, LoginAttemptStatus::SUCCESS)
->addFieldToFilter($loginAttemptCollection->getIdFieldName(), ['neq' => $loginAttempt->getId()])
->setOrder($loginAttemptCollection->getIdFieldName(), $loginAttemptCollection::SORT_ORDER_DESC)
->setPageSize(1)
->getFirstItem();
$this->dataStorage->set($storageKey, [$lastLoginAttempt]);
return $lastLoginAttempt;
}
}
@@ -0,0 +1,15 @@
<?php
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Admin Actions Log for Magento 2
*/
namespace Amasty\AdminActionsLog\Model\LoginAttempt\SuspiciousDetection\Type;
use Amasty\AdminActionsLog\Api\Data\LoginAttemptInterface;
interface DetectorInterface
{
public function isSuspiciousAttempt(LoginAttemptInterface $loginAttempt): bool;
}
@@ -0,0 +1,27 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Admin Actions Log for Magento 2
*/
namespace Amasty\AdminActionsLog\Model\LoginAttempt\SuspiciousDetection\Type;
use Amasty\AdminActionsLog\Api\Data\LoginAttemptInterface;
class NewDevice extends AbstractDetection
{
public function isSuspiciousAttempt(LoginAttemptInterface $loginAttempt): bool
{
$lastAttempt = $this->getLastSucceedAttempt($loginAttempt);
if ($lastAttempt->getId() && !empty($lastAttempt->getUserAgent())) {
return $loginAttempt->getUserAgent() !== $lastAttempt->getUserAgent();
}
return false;
}
}
@@ -0,0 +1,27 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Admin Actions Log for Magento 2
*/
namespace Amasty\AdminActionsLog\Model\LoginAttempt\SuspiciousDetection\Type;
use Amasty\AdminActionsLog\Api\Data\LoginAttemptInterface;
class NewIp extends AbstractDetection
{
public function isSuspiciousAttempt(LoginAttemptInterface $loginAttempt): bool
{
$lastAttempt = $this->getLastSucceedAttempt($loginAttempt);
if ($lastAttempt->getId() && !empty($lastAttempt->getIp())) {
return $loginAttempt->getIp() !== $lastAttempt->getIp();
}
return false;
}
}
@@ -0,0 +1,27 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Admin Actions Log for Magento 2
*/
namespace Amasty\AdminActionsLog\Model\LoginAttempt\SuspiciousDetection\Type;
use Amasty\AdminActionsLog\Api\Data\LoginAttemptInterface;
class NewLocation extends AbstractDetection
{
public function isSuspiciousAttempt(LoginAttemptInterface $loginAttempt): bool
{
$lastAttempt = $this->getLastSucceedAttempt($loginAttempt);
if ($lastAttempt->getId() && !empty($lastAttempt->getLocation())) {
return $loginAttempt->getLocation() !== $lastAttempt->getLocation();
}
return false;
}
}
@@ -0,0 +1,52 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Admin Actions Log for Magento 2
*/
namespace Amasty\AdminActionsLog\Model\OptionSource;
class LogEntryTypes implements \Magento\Framework\Data\OptionSourceInterface
{
public const TYPE_NEW = 'new';
public const TYPE_EDIT = 'edit';
public const TYPE_DELETE = 'delete';
public const TYPE_CACHE = 'cache';
public const TYPE_EXPORT = 'export';
public const TYPE_RESTORE = 'restore';
/**
* @return array
*/
public function toOptionArray(): array
{
$optionArray = [];
foreach ($this->toArray() as $value => $label) {
$optionArray[] = ['value' => $value, 'label' => $label];
}
return $optionArray;
}
/**
* Get options in "key-value" format
*
* @return array
*/
public function toArray(): array
{
return [
self::TYPE_NEW => __('New'),
self::TYPE_EDIT => __('Edit'),
self::TYPE_DELETE => __('Delete'),
self::TYPE_CACHE => __('Cache'),
self::TYPE_EXPORT => __('Export'),
self::TYPE_RESTORE => __('Restore'),
];
}
}
@@ -0,0 +1,46 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Admin Actions Log for Magento 2
*/
namespace Amasty\AdminActionsLog\Model\OptionSource;
class LoggedInWith implements \Magento\Framework\Data\OptionSourceInterface
{
public const NEW_DEVICE = 'new_device';
public const NEW_IP = 'new_ip';
public const NEW_LOCATION = 'new_location';
/**
* @return array
*/
public function toOptionArray(): array
{
$optionArray = [];
foreach ($this->toArray() as $value => $label) {
$optionArray[] = ['value' => $value, 'label' => $label];
}
return $optionArray;
}
/**
* Get options in "key-value" format
*
* @return array
*/
public function toArray(): array
{
return [
self::NEW_DEVICE => __('From New Device'),
self::NEW_IP => __('With New IP Address'),
self::NEW_LOCATION => __('From New Location')
];
}
}
@@ -0,0 +1,40 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Admin Actions Log for Magento 2
*/
namespace Amasty\AdminActionsLog\Model\OptionSource;
use Magento\Framework\Data\OptionSourceInterface;
class LoginAttemptStatus implements OptionSourceInterface
{
public const FAILED = 0;
public const SUCCESS = 1;
public const LOGOUT = 2;
public function toOptionArray(): array
{
$result = [];
foreach ($this->toArray() as $value => $label) {
$result[] = ['label' => $label, 'value' => $value];
}
return $result;
}
public function toArray(): array
{
return [
self::FAILED => __('Failed'),
self::SUCCESS => __('Success'),
self::LOGOUT => __('Logout')
];
}
}
@@ -0,0 +1,61 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Admin Actions Log for Magento 2
*/
namespace Amasty\AdminActionsLog\Model\OptionSource;
use Magento\User\Model\ResourceModel\User\CollectionFactory;
class Users implements \Magento\Framework\Data\OptionSourceInterface
{
/**
* @var CollectionFactory
*/
private $adminCollectionFactory;
public function __construct(
CollectionFactory $adminCollectionFactory
) {
$this->adminCollectionFactory = $adminCollectionFactory;
}
/**
* @return array
*/
public function toOptionArray(): array
{
$optionArray = [];
foreach ($this->toArray() as $value => $label) {
$optionArray[] = ['value' => $value, 'label' => $label];
}
return $optionArray;
}
/**
* Get options in "key-value" format
*
* @return array
*/
public function toArray(): array
{
$result = [];
$adminCollection = $this->adminCollectionFactory->create();
$adminCollection->addFieldToFilter('main_table.is_active', 1)
->addFieldToSelect(['user_id', 'firstname', 'lastname', 'username']);
foreach ($adminCollection->getData() as $admin) {
$result[$admin['user_id']] = $admin['firstname'] . ' ' . $admin['lastname']
. ' (' . $admin['username'] . ')';
}
return $result;
}
}
@@ -0,0 +1,36 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Admin Actions Log for Magento 2
*/
namespace Amasty\AdminActionsLog\Model\VisitHistoryEntry\Detail;
use Amasty\AdminActionsLog\Model\VisitHistoryEntry\DetailLoaderInterface;
use Amasty\AdminActionsLog\Model\VisitHistoryEntry\ResourceModel\VisitHistoryDetailCollectionFactory;
use Amasty\AdminActionsLog\Model\VisitHistoryEntry\VisitHistoryDetail;
class FullDetailLoader implements DetailLoaderInterface
{
/**
* @var VisitHistoryDetailCollectionFactory
*/
private $detailCollectionFactory;
public function __construct(VisitHistoryDetailCollectionFactory $detailCollectionFactory)
{
$this->detailCollectionFactory = $detailCollectionFactory;
}
public function loadDetails(int $visitHistoryId): array
{
$collection = $this->detailCollectionFactory->create();
$collection->addFieldToFilter(VisitHistoryDetail::VISIT_ID, $visitHistoryId);
return $collection->getItems();
}
}
@@ -0,0 +1,38 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Admin Actions Log for Magento 2
*/
namespace Amasty\AdminActionsLog\Model\VisitHistoryEntry\Detail;
use Amasty\AdminActionsLog\Model\VisitHistoryEntry\DetailLoaderInterface;
use Amasty\AdminActionsLog\Model\VisitHistoryEntry\ResourceModel\VisitHistoryDetailCollectionFactory;
use Amasty\AdminActionsLog\Model\VisitHistoryEntry\VisitHistoryDetail;
class LastDetailLoader implements DetailLoaderInterface
{
/**
* @var VisitHistoryDetailCollectionFactory
*/
private $detailCollectionFactory;
public function __construct(VisitHistoryDetailCollectionFactory $detailCollectionFactory)
{
$this->detailCollectionFactory = $detailCollectionFactory;
}
public function loadDetails(int $visitHistoryId): array
{
$collection = $this->detailCollectionFactory->create();
$collection->addFieldToFilter(VisitHistoryDetail::VISIT_ID, $visitHistoryId);
$collection->setOrder($collection->getIdFieldName(), $collection::SORT_ORDER_DESC);
$collection->setPageSize(1);
return $collection->getItems();
}
}
@@ -0,0 +1,21 @@
<?php
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Admin Actions Log for Magento 2
*/
namespace Amasty\AdminActionsLog\Model\VisitHistoryEntry;
use Amasty\AdminActionsLog\Api\Data\VisitHistoryDetailInterface;
interface DetailLoaderInterface
{
/**
* Load associated VisitHistoryDetails via VisitHistory ID.
*
* @param int $visitHistoryId
* @return VisitHistoryDetailInterface[]
*/
public function loadDetails(int $visitHistoryId): array;
}
@@ -0,0 +1,65 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Admin Actions Log for Magento 2
*/
namespace Amasty\AdminActionsLog\Model\VisitHistoryEntry;
use Amasty\AdminActionsLog\Api\Data\VisitHistoryEntryInterface;
use Amasty\AdminActionsLog\Api\Data\VisitHistoryEntrySearchResultsInterface;
use Amasty\AdminActionsLog\Api\Data\VisitHistoryEntrySearchResultsInterfaceFactory;
use Amasty\AdminActionsLog\Api\VisitHistoryEntryFinderInterface;
use Amasty\AdminActionsLog\Api\VisitHistoryEntryRepositoryInterface;
use Amasty\AdminActionsLog\Model\CriteriaApplierTrait;
use Amasty\AdminActionsLog\Model\VisitHistoryEntry\ResourceModel\CollectionFactory;
use Magento\Framework\Api\SearchCriteriaInterface;
class Finder implements VisitHistoryEntryFinderInterface
{
use CriteriaApplierTrait;
/**
* @var CollectionFactory
*/
private $collectionFactory;
/**
* @var VisitHistoryEntryRepositoryInterface
*/
private $historyEntryRepository;
/**
* @var VisitHistoryEntrySearchResultsInterfaceFactory
*/
private $searchResultsFactory;
public function __construct(
CollectionFactory $collectionFactory,
VisitHistoryEntryRepositoryInterface $historyEntryRepository,
VisitHistoryEntrySearchResultsInterfaceFactory $searchResultsFactory
) {
$this->collectionFactory = $collectionFactory;
$this->historyEntryRepository = $historyEntryRepository;
$this->searchResultsFactory = $searchResultsFactory;
}
public function getList(SearchCriteriaInterface $searchCriteria): VisitHistoryEntrySearchResultsInterface
{
$searchResults = $this->searchResultsFactory->create();
$searchResults->setSearchCriteria($searchCriteria);
$visitHistoryCollection = $this->collectionFactory->create();
$this->applyCriteria($searchCriteria, $visitHistoryCollection);
$searchResults->setTotalCount($visitHistoryCollection->getSize());
$historyItems = array_map(function (VisitHistoryEntryInterface $visitHistory) {
return $this->historyEntryRepository->getById($visitHistory->getId());
}, $visitHistoryCollection->getItems());
$searchResults->setItems($historyItems);
return $searchResults;
}
}
@@ -0,0 +1,185 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Admin Actions Log for Magento 2
*/
namespace Amasty\AdminActionsLog\Model\VisitHistoryEntry;
use Amasty\AdminActionsLog\Api\Data\VisitHistoryDetailInterface;
use Amasty\AdminActionsLog\Api\Data\VisitHistoryEntryInterface;
use Amasty\AdminActionsLog\Api\Data\VisitHistoryEntryInterfaceFactory;
use Amasty\AdminActionsLog\Api\VisitHistoryEntryRepositoryInterface;
use Amasty\AdminActionsLog\Model\VisitHistoryEntry\ResourceModel\VisitHistoryDetail as VisitHistoryDetailResource;
use Amasty\AdminActionsLog\Model\VisitHistoryEntry\VisitHistoryDetail as VisitHistoryDetailModel;
use Amasty\AdminActionsLog\Model\VisitHistoryEntry\VisitHistoryEntry as VisitHistoryEntryModel;
use Magento\Framework\Exception\CouldNotDeleteException;
use Magento\Framework\Exception\CouldNotSaveException;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\Stdlib\DateTime\DateTime;
class Repository implements VisitHistoryEntryRepositoryInterface
{
/**
* @var VisitHistoryEntryInterfaceFactory
*/
private $visitHistoryEntryFactory;
/**
* @var ResourceModel\VisitHistoryEntry
*/
private $visitHistoryEntryResource;
/**
* @var ResourceModel\CollectionFactory
*/
private $visitHistoryEntryCollectionFactory;
/**
* @var VisitHistoryDetailResource
*/
private $visitHistoryDetailResource;
/**
* @var DetailLoaderInterface
*/
private $detailLoader;
/**
* @var DateTime
*/
private $dateTime;
/**
* @var array
*/
private $visitHistoryEntries = [];
/**
* @var array
*/
private $visitHistoryEntriesBySessionId = [];
public function __construct(
VisitHistoryEntryInterfaceFactory $visitHistoryEntryFactory,
ResourceModel\VisitHistoryEntry $visitHistoryEntryResource,
ResourceModel\CollectionFactory $visitHistoryEntryCollectionFactory,
VisitHistoryDetailResource $visitHistoryDetailResource,
DetailLoaderInterface $detailLoader,
DateTime $dateTime
) {
$this->visitHistoryEntryFactory = $visitHistoryEntryFactory;
$this->visitHistoryEntryResource = $visitHistoryEntryResource;
$this->visitHistoryEntryCollectionFactory = $visitHistoryEntryCollectionFactory;
$this->visitHistoryDetailResource = $visitHistoryDetailResource;
$this->detailLoader = $detailLoader;
$this->dateTime = $dateTime;
}
public function getById(int $id): VisitHistoryEntryInterface
{
if (!isset($this->visitHistoryEntries[$id])) {
/** @var VisitHistoryEntryInterface $visitHistoryEntry */
$visitHistoryEntry = $this->visitHistoryEntryFactory->create();
$this->visitHistoryEntryResource->load($visitHistoryEntry, $id);
if (!$visitHistoryEntry->getId()) {
throw new NoSuchEntityException(__('Visit History Entry with specified ID "%1" not found.', $id));
}
$visitHistoryEntry->setVisitHistoryDetails($this->detailLoader->loadDetails($id));
$this->visitHistoryEntries[$id] = $visitHistoryEntry;
}
return $this->visitHistoryEntries[$id];
}
public function getBySessionId(string $sessionId): VisitHistoryEntryInterface
{
if (!isset($this->visitHistoryEntriesBySessionId[$sessionId])) {
$historyEntryId = $this->resolveHistoryIdBySessionId($sessionId);
$this->visitHistoryEntriesBySessionId[$sessionId] = $this->getById($historyEntryId);
}
return $this->visitHistoryEntriesBySessionId[$sessionId];
}
public function save(VisitHistoryEntryInterface $visitHistoryEntry): VisitHistoryEntryInterface
{
try {
if ($visitHistoryEntry->getId()) {
$visitHistoryEntry = $this->getById((int)$visitHistoryEntry->getId())
->addData($visitHistoryEntry->getData());
}
$this->visitHistoryEntryResource->save($visitHistoryEntry);
/** @var VisitHistoryDetailModel $visitHistoryDetail */
foreach ($visitHistoryEntry->getVisitHistoryDetails() as $visitHistoryDetail) {
$visitHistoryDetail->setVisitId((int)$visitHistoryEntry->getId());
$visitHistoryDetail->setSessionId((string)$visitHistoryEntry->getSessionId());
$this->visitHistoryDetailResource->save($visitHistoryDetail);
}
unset(
$this->visitHistoryEntries[$visitHistoryEntry->getId()],
$this->visitHistoryEntriesBySessionId[$visitHistoryEntry->getSessionId()]
);
} catch (\Exception $e) {
throw new CouldNotSaveException(__('Unable to save the Visit History. Error: %1', $e->getMessage()));
}
return $visitHistoryEntry;
}
public function delete(VisitHistoryEntryInterface $visitHistoryEntry): bool
{
try {
$this->visitHistoryEntryResource->delete($visitHistoryEntry);
unset(
$this->visitHistoryEntries[$visitHistoryEntry->getId()],
$this->visitHistoryEntriesBySessionId[$visitHistoryEntry->getSessionId()]
);
} catch (\Exception $e) {
throw new CouldNotDeleteException(__('Unable to delete the Visit History. Error: %1', $e->getMessage()));
}
return true;
}
public function deleteById(int $id): bool
{
return $this->delete($this->getById($id));
}
public function clean(?int $period = null): void
{
$connection = $this->visitHistoryEntryResource->getConnection();
$tableName = $this->visitHistoryEntryResource->getMainTable();
if ($period === null) {
$connection->delete($tableName);
} else {
$time = '-' . $period . ' days';
$connection->delete(
$tableName,
[VisitHistoryEntryModel::SESSION_START . ' < ?' =>
$this->dateTime->gmtDate('Y-m-d H:i:s', $time)
]
);
}
}
private function resolveHistoryIdBySessionId(string $sessionId): int
{
$historyEntryCollection = $this->visitHistoryEntryCollectionFactory->create();
$historyEntryCollection->addFieldToFilter(VisitHistoryEntryModel::SESSION_ID, $sessionId);
$historyEntryCollection->setPageSize(1);
/** @var VisitHistoryDetailInterface $historyEntry */
$historyEntry = $historyEntryCollection->getFirstItem();
return (int)$historyEntry->getId();
}
}
@@ -0,0 +1,24 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Admin Actions Log for Magento 2
*/
namespace Amasty\AdminActionsLog\Model\VisitHistoryEntry\ResourceModel;
use Amasty\AdminActionsLog\Model\VisitHistoryEntry\ResourceModel\VisitHistoryEntry as VisitHistoryEntryResource;
use Amasty\AdminActionsLog\Model\VisitHistoryEntry\VisitHistoryEntry as VisitHistoryEntryModel;
use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection;
class Collection extends AbstractCollection
{
public function _construct()
{
$this->_init(VisitHistoryEntryModel::class, VisitHistoryEntryResource::class);
$this->_setIdFieldName($this->getResource()->getIdFieldName());
}
}
@@ -0,0 +1,24 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Admin Actions Log for Magento 2
*/
namespace Amasty\AdminActionsLog\Model\VisitHistoryEntry\ResourceModel;
use Amasty\AdminActionsLog\Model\VisitHistoryEntry\VisitHistoryDetail as VisitHistoryDetailModel;
use Magento\Framework\Model\ResourceModel\Db\AbstractDb;
class VisitHistoryDetail extends AbstractDb
{
public const TABLE_NAME = 'amasty_audit_visit_details';
protected function _construct()
{
$this->_init(self::TABLE_NAME, VisitHistoryDetailModel::ID);
}
}
@@ -0,0 +1,24 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Admin Actions Log for Magento 2
*/
namespace Amasty\AdminActionsLog\Model\VisitHistoryEntry\ResourceModel;
use Amasty\AdminActionsLog\Model\VisitHistoryEntry\ResourceModel\VisitHistoryDetail as VisitHistoryDetailResource;
use Amasty\AdminActionsLog\Model\VisitHistoryEntry\VisitHistoryDetail as VisitHistoryDetailModel;
use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection;
class VisitHistoryDetailCollection extends AbstractCollection
{
public function _construct()
{
$this->_init(VisitHistoryDetailModel::class, VisitHistoryDetailResource::class);
$this->_setIdFieldName($this->getResource()->getIdFieldName());
}
}
@@ -0,0 +1,24 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Admin Actions Log for Magento 2
*/
namespace Amasty\AdminActionsLog\Model\VisitHistoryEntry\ResourceModel;
use Amasty\AdminActionsLog\Model\VisitHistoryEntry\VisitHistoryEntry as VisitHistoryEntryModel;
use Magento\Framework\Model\ResourceModel\Db\AbstractDb;
class VisitHistoryEntry extends AbstractDb
{
public const TABLE_NAME = 'amasty_audit_visit_entry';
protected function _construct()
{
$this->_init(self::TABLE_NAME, VisitHistoryEntryModel::ID);
}
}
@@ -0,0 +1,91 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Admin Actions Log for Magento 2
*/
namespace Amasty\AdminActionsLog\Model\VisitHistoryEntry;
use Amasty\AdminActionsLog\Api\Data\VisitHistoryDetailInterface;
use Magento\Framework\Model\AbstractModel;
class VisitHistoryDetail extends AbstractModel implements VisitHistoryDetailInterface
{
public const ID = 'id';
public const VISIT_ID = 'visit_id';
public const PAGE_NAME = 'page_name';
public const PAGE_URL = 'page_url';
public const STAY_DURATION = 'stay_duration';
public const SESSION_ID = 'session_id';
public function _construct()
{
parent::_construct();
$this->_init(ResourceModel\VisitHistoryDetail::class);
$this->setIdFieldName(self::ID);
}
public function getVisitId(): ?int
{
return $this->hasData(self::VISIT_ID) ? (int)$this->_getData(self::VISIT_ID) : null;
}
public function setVisitId(int $visitId): VisitHistoryDetailInterface
{
$this->setData(self::VISIT_ID, $visitId);
return $this;
}
public function getPageName(): ?string
{
return $this->_getData(self::PAGE_NAME);
}
public function setPageName(string $pageName): VisitHistoryDetailInterface
{
$this->setData(self::PAGE_NAME, $pageName);
return $this;
}
public function getPageUrl(): ?string
{
return $this->_getData(self::PAGE_URL);
}
public function setPageUrl(string $pageUrl): VisitHistoryDetailInterface
{
$this->setData(self::PAGE_URL, $pageUrl);
return $this;
}
public function getStayDuration(): ?int
{
return $this->hasData(self::STAY_DURATION) ? (int)$this->_getData(self::STAY_DURATION) : null;
}
public function setStayDuration(int $stayDuration): VisitHistoryDetailInterface
{
$this->setData(self::STAY_DURATION, $stayDuration);
return $this;
}
public function getSessionId(): ?string
{
return $this->_getData(self::SESSION_ID);
}
public function setSessionId(string $sessionId): VisitHistoryDetailInterface
{
$this->setData(self::SESSION_ID, $sessionId);
return $this;
}
}
@@ -0,0 +1,128 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Admin Actions Log for Magento 2
*/
namespace Amasty\AdminActionsLog\Model\VisitHistoryEntry;
use Amasty\AdminActionsLog\Api\Data\VisitHistoryEntryInterface;
use Magento\Framework\Model\AbstractModel;
class VisitHistoryEntry extends AbstractModel implements VisitHistoryEntryInterface
{
public const ID = 'id';
public const USERNAME = 'username';
public const FULL_NAME = 'full_name';
public const SESSION_START = 'session_start';
public const SESSION_END = 'session_end';
public const IP = 'ip';
public const LOCATION = 'location';
public const SESSION_ID = 'session_id';
public const VISIT_HISTORY_DETAILS = 'visit_history_details';
public function _construct()
{
parent::_construct();
$this->_init(ResourceModel\VisitHistoryEntry::class);
$this->setIdFieldName(self::ID);
}
public function getUsername(): ?string
{
return $this->_getData(self::USERNAME);
}
public function setUsername(string $username): VisitHistoryEntryInterface
{
$this->setData(self::USERNAME, $username);
return $this;
}
public function getFullName(): ?string
{
return $this->_getData(self::FULL_NAME);
}
public function setFullName(string $fullName): VisitHistoryEntryInterface
{
return $this->setData(self::FULL_NAME, $fullName);
}
public function getSessionStart(): ?string
{
return $this->_getData(self::SESSION_START);
}
public function setSessionStart(string $sessionStart): VisitHistoryEntryInterface
{
$this->setData(self::SESSION_START, $sessionStart);
return $this;
}
public function getSessionEnd(): ?string
{
return $this->_getData(self::SESSION_END);
}
public function setSessionEnd(string $sessionEnd): VisitHistoryEntryInterface
{
$this->setData(self::SESSION_END, $sessionEnd);
return $this;
}
public function getIp(): ?string
{
return $this->_getData(self::IP);
}
public function setIp(string $ip): VisitHistoryEntryInterface
{
$this->setData(self::IP, $ip);
return $this;
}
public function getLocation(): ?string
{
return $this->_getData(self::LOCATION);
}
public function setLocation(string $location): VisitHistoryEntryInterface
{
$this->setData(self::LOCATION, $location);
return $this;
}
public function getSessionId(): ?string
{
return $this->_getData(self::SESSION_ID);
}
public function setSessionId(string $sessionId): VisitHistoryEntryInterface
{
$this->setData(self::SESSION_ID, $sessionId);
return $this;
}
public function getVisitHistoryDetails(): array
{
return (array)$this->_getData(self::VISIT_HISTORY_DETAILS);
}
public function setVisitHistoryDetails(array $visitHistoryDetails): VisitHistoryEntryInterface
{
$this->setData(self::VISIT_HISTORY_DETAILS, $visitHistoryDetails);
return $this;
}
}
@@ -0,0 +1,21 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Admin Actions Log for Magento 2
*/
namespace Amasty\AdminActionsLog\Model\VisitHistoryEntry;
use Amasty\AdminActionsLog\Api\Data\VisitHistoryEntrySearchResultsInterface;
use Magento\Framework\Api\SearchResults;
/**
* Service Data Object with Visit History Entry search results.
*/
class VisitHistoryEntrySearchResults extends SearchResults implements VisitHistoryEntrySearchResultsInterface
{
}
@@ -0,0 +1,77 @@
<?php
declare(strict_types=1);
/**
* @author Amasty Team
* @copyright Copyright (c) Amasty (https://www.amasty.com)
* @package Admin Actions Log for Magento 2
*/
namespace Amasty\AdminActionsLog\Model\VisitHistoryEntry;
use Amasty\AdminActionsLog\Api\Data\VisitHistoryEntryInterface;
use Amasty\AdminActionsLog\Api\Data\VisitHistoryEntryInterfaceFactory;
use Amasty\AdminActionsLog\Api\VisitHistoryEntryRepositoryInterface;
use Amasty\AdminActionsLog\Api\VisitHistoryManagerInterface;
use Amasty\AdminActionsLog\Model\Admin\SessionUserDataProvider;
use Magento\Framework\Stdlib\DateTime\DateTime;
class VisitHistoryManager implements VisitHistoryManagerInterface
{
/**
* @var SessionUserDataProvider
*/
private $sessionUserDataProvider;
/**
* @var VisitHistoryEntryInterfaceFactory
*/
private $visitHistoryEntryFactory;
/**
* @var VisitHistoryEntryRepositoryInterface
*/
private $visitHistoryEntryRepository;
/**
* @var DateTime
*/
private $dateTime;
public function __construct(
SessionUserDataProvider $sessionUserDataProvider,
VisitHistoryEntryInterfaceFactory $visitHistoryEntryFactory,
VisitHistoryEntryRepositoryInterface $visitHistoryEntryRepository,
DateTime $dateTime
) {
$this->sessionUserDataProvider = $sessionUserDataProvider;
$this->visitHistoryEntryFactory = $visitHistoryEntryFactory;
$this->visitHistoryEntryRepository = $visitHistoryEntryRepository;
$this->dateTime = $dateTime;
}
public function startVisit(): void
{
$userData = $this->sessionUserDataProvider->getUserPreparedData();
/** @var $visitHistoryEntryModel VisitHistoryEntryInterface */
$visitHistoryEntryModel = $this->visitHistoryEntryFactory->create(['data' => $userData]);
$visitHistoryEntryModel->setSessionStart($this->dateTime->date());
$this->visitHistoryEntryRepository->save($visitHistoryEntryModel);
}
public function endVisit(string $sessionId = null): void
{
$sessionId = $sessionId ?: $this->sessionUserDataProvider->getSessionId();
/** @var $visitHistoryEntryModel VisitHistoryEntryInterface */
$visitHistoryEntryModel = $this->visitHistoryEntryRepository->getBySessionId($sessionId);
$visitHistoryEntryModel->setSessionEnd($this->dateTime->date());
$this->visitHistoryEntryRepository->save($visitHistoryEntryModel);
}
public function clear(int $period = null): void
{
$this->visitHistoryEntryRepository->clean($period);
}
}