Well, my first solution didn't work, so I modified AdminLoginController.php as @ventura suggested. This code modification prevents users (with profile ID's 5 & 13) from login on the specified schedule, but what I didn't get to make work are:
- The error message the user gets when not allowed to login
- The logout redirection that should reload the admin login page
// Add the restricted profiles array and the time-based restriction methods
protected $restrictedProfiles = [5, 13]; // Adjust the profile IDs as needed
protected function canEmployeeLogin($employee)
{
$originalTimezone = date_default_timezone_get();
$shopTimezone = Configuration::get('PS_TIMEZONE');
if (!in_array($shopTimezone, timezone_identifiers_list())) {
PrestaShopLogger::addLog("Invalid timezone set in PrestaShop configuration: {$shopTimezone}.", 3, null, 'Configuration', null);
return false;
}
date_default_timezone_set($shopTimezone);
$currentHour = date('G');
$currentDay = date('N');
$canLogin = $this->isLoginTime($currentDay, $currentHour);
date_default_timezone_set($originalTimezone);
return $canLogin;
}
protected function isLoginTime($currentDay, $currentHour)
{
$defaultWeekdayHours = ['start' => 9, 'end' => 21];
$loginHours = [
1 => $defaultWeekdayHours, // Monday
2 => $defaultWeekdayHours, // Tuesday
3 => $defaultWeekdayHours, // Wednesday
4 => $defaultWeekdayHours, // Thursday
5 => $defaultWeekdayHours, // Friday
6 => ['start' => 10, 'end' => 20], // Saturday
7 => ['start' => 0, 'end' => 0], // Sunday
];
return $currentHour >= $loginHours[$currentDay]['start'] && $currentHour < $loginHours[$currentDay]['end'];
}
public function processLogin()
{
// ... (previous code for field validity checks)
if (!count($this->errors)) {
// ... (any existing code right before the employee validation)
// Time-based restriction logic starts here
// Find employee
$this->context->employee = new Employee();
$is_employee_loaded = $this->context->employee->getByEmail($email, $passwd);
if ($is_employee_loaded && in_array($this->context->employee->id_profile, $this->restrictedProfiles)) {
if (!$this->canEmployeeLogin($this->context->employee)) {
// Log the failed login attempt for administrative purposes
PrestaShopLogger::addLog(
"Employee with ID {$this->context->employee->id} attempted to log in outside the working hours.",
1,
null,
'Employee',
$this->context->employee->id
);
// Add an error to prevent login
$this->errors[] = $this->trans(
'You cannot log in at this time.',
array(),
'Admin.Login.Notification'
);
// Log out the employee immediately to prevent session from continuing
$this->context->employee->logout();
// No need to redirect as the logout method should take care of this
return;
}
}
// Time-based restriction logic ends here
// ... (rest of the login process, if no errors)
}
// ... (any other code that should run regardless of whether there are errors or not)
}