Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- namespace App\Services\Email;
- use Exception;
- use App\Services\Session;
- use App\Services\Logger;
- use App\Services\SecurityService;
- /**
- * Email Rate Limiter
- *
- * Handles rate limiting for email sending to prevent abuse.
- *
- * @package App\Services\Email
- */
- class EmailRateLimiter
- {
- /**
- * @var Logger Logger service
- */
- private Logger $logger;
- /**
- * @var SecurityService Security service
- */
- private SecurityService $securityService;
- /**
- * @var int Maximum emails per hour
- */
- private int $maxEmailsPerHour;
- /**
- * @var string Email log key in session
- */
- private string $emailLogKey = 'email_sent_log';
- /**
- * EmailRateLimiter constructor
- *
- * @param int $maxEmailsPerHour Maximum emails per hour
- */
- public function __construct(int $maxEmailsPerHour = 10)
- {
- $this->logger = new Logger();
- $this->securityService = new SecurityService();
- $this->maxEmailsPerHour = $maxEmailsPerHour;
- }
- /**
- * Check rate limit for email sending
- *
- * @return bool True if under the rate limit
- */
- public function checkRateLimit(): bool
- {
- try {
- $session = new Session();
- $session->start();
- // Get email log from session
- $emailLog = $session->get($this->emailLogKey, []);
- // Clean up old entries (older than 1 hour)
- $now = time();
- $emailLog = array_filter($emailLog, function ($timestamp) use ($now) {
- return ($now - $timestamp) < 3600; // Keep emails from the last hour
- });
- // Count emails sent in the last hour
- $emailCount = count($emailLog);
- // Check if we're over the limit
- if ($emailCount >= $this->maxEmailsPerHour) {
- return false;
- }
- return true;
- } catch (Exception $e) {
- // Log the error
- $this->logger->error('Rate limit check failed', [
- 'error' => $e->getMessage()
- ]);
- // If there's an error checking rate limit, be cautious and allow the email
- return true;
- }
- }
- /**
- * Log an email sending attempt
- *
- * @param string|array $to Recipient(s)
- * @param string $subject Email subject
- * @return void
- */
- public function logEmailAttempt(string|array $to, string $subject): void
- {
- try {
- $session = new Session();
- $session->start();
- // Get email log from session
- $emailLog = $session->get($this->emailLogKey, []);
- // Add current timestamp
- $emailLog[] = time();
- // Update session
- $session->set($this->emailLogKey, $emailLog);
- // Log for security monitoring
- $recipient = is_array($to) ? implode(', ', array_keys($to)) : $to;
- $this->securityService->logSecurityEvent(
- 'email_sent',
- [
- 'to' => $recipient,
- 'subject' => $subject
- ],
- 'info'
- );
- } catch (Exception $e) {
- // Log the error
- $this->logger->error('Failed to log email attempt', [
- 'error' => $e->getMessage()
- ]);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement