102 lines
2.7 KiB
PHP
102 lines
2.7 KiB
PHP
<?php
|
|
|
|
/**
|
|
* Send OTP Email Library
|
|
* Generates and sends a one-time password via email for two-factor authentication
|
|
*/
|
|
class SendOtpEmail
|
|
{
|
|
private $user;
|
|
private $otpCode;
|
|
private $sendResult = false;
|
|
|
|
public function __construct($user)
|
|
{
|
|
$this->user = $user;
|
|
$this->handle();
|
|
}
|
|
|
|
/**
|
|
* Get the result of the email send operation
|
|
* @return bool True if email was sent successfully
|
|
*/
|
|
public function getSendResult()
|
|
{
|
|
return $this->sendResult;
|
|
}
|
|
|
|
/**
|
|
* Get the generated OTP code (for testing purposes)
|
|
* @return string The OTP code
|
|
*/
|
|
public function getOtpCode()
|
|
{
|
|
return $this->otpCode;
|
|
}
|
|
|
|
/**
|
|
* Main handler for OTP email process
|
|
*/
|
|
private function handle()
|
|
{
|
|
$this->generateOTP();
|
|
$this->sendOTPEmail();
|
|
}
|
|
|
|
/**
|
|
* Generate a new OTP code
|
|
*/
|
|
private function generateOTP()
|
|
{
|
|
// Generate OTP valid for 10 minutes
|
|
$this->otpCode = \UserOtp_model::generateOTP($this->user->id, 10);
|
|
}
|
|
|
|
/**
|
|
* Send the OTP code via email
|
|
*/
|
|
private function sendOTPEmail()
|
|
{
|
|
$email = \Config\Services::email();
|
|
|
|
// Build email configuration directly from environment variables
|
|
$config = [
|
|
'protocol' => str_replace(',', '', $_ENV['PROTOCOL'] ?? 'smtp'),
|
|
'SMTPHost' => str_replace(',', '', $_ENV['SMTP_HOST'] ?? ''),
|
|
'SMTPUser' => str_replace(',', '', $_ENV['SMTP_USER'] ?? ''),
|
|
'SMTPPass' => str_replace(',', '', $_ENV['SMTP_PASS'] ?? ''),
|
|
'SMTPPort' => (int) str_replace(',', '', $_ENV['SMTP_PORT'] ?? 25),
|
|
'SMTPCrypto' => 'tls',
|
|
'SMTPTimeout' => 30,
|
|
'charset' => 'UTF-8',
|
|
'mailType' => 'html',
|
|
'newline' => "\r\n",
|
|
'CRLF' => "\r\n",
|
|
'wordWrap' => true,
|
|
];
|
|
|
|
$email->initialize($config);
|
|
|
|
$data = [
|
|
'username' => $this->user->username,
|
|
'firstname' => $this->user->firstname,
|
|
'middlename' => $this->user->middlename,
|
|
'lastname' => $this->user->lastname,
|
|
'otp_code' => $this->otpCode
|
|
];
|
|
|
|
$html = view('emails/twofactor_otp_email', ['user' => $data]);
|
|
|
|
$email->setFrom('noreply@dbois.nl', 'DBOIS');
|
|
$email->setTo($this->user->email);
|
|
$email->setSubject('DBOIS Tweefactorauthenticatie - Verificatiecode');
|
|
$email->setMessage($html);
|
|
|
|
$this->sendResult = $email->send();
|
|
|
|
if (!$this->sendResult) {
|
|
log_message('error', 'Failed to send 2FA OTP email to ' . $this->user->email . ': ' . $email->printDebugger());
|
|
}
|
|
}
|
|
}
|