49 lines
1.6 KiB
PHP
49 lines
1.6 KiB
PHP
<?php
|
|
|
|
namespace App\Support\Auth;
|
|
|
|
use App\Mail\Admin\AdminLoginAlertMail;
|
|
use App\Models\Setting;
|
|
use App\Models\User;
|
|
use App\Support\AutoEmailGate;
|
|
use Illuminate\Support\Facades\Log;
|
|
use Illuminate\Support\Facades\Mail;
|
|
|
|
class AdminLoginAlert
|
|
{
|
|
public const SETTING_FIELD = 'admin_login_alert_emails';
|
|
public const DEFAULT_RECIPIENTS = ['web@tgs.com.vn'];
|
|
|
|
/**
|
|
* @return list<string>
|
|
*/
|
|
public static function recipients(): array
|
|
{
|
|
$settings = (array) (json_decode(Setting::where('key', 'email_settings')->value('value') ?? '', true) ?? []);
|
|
|
|
return array_key_exists(self::SETTING_FIELD, $settings)
|
|
? array_values(array_filter((array) $settings[self::SETTING_FIELD]))
|
|
: self::DEFAULT_RECIPIENTS;
|
|
}
|
|
|
|
public static function send(User $admin, string $ip, ?string $userAgent): void
|
|
{
|
|
$recipients = self::recipients();
|
|
if ($recipients === [] || ! AutoEmailGate::allows('admin_login_alert')) {
|
|
return;
|
|
}
|
|
|
|
try {
|
|
Mail::to($recipients)->queue(new AdminLoginAlertMail([
|
|
'admin_name' => (string) ($admin->fullname ?: $admin->username),
|
|
'admin_username' => (string) ($admin->username ?? $admin->email),
|
|
'login_time' => now()->format('d/m/Y H:i:s'),
|
|
'client_ip' => $ip,
|
|
'user_agent' => (string) ($userAgent ?: 'Không xác định'),
|
|
]));
|
|
} catch (\Throwable $e) {
|
|
Log::warning('Không gửi được email thông báo đăng nhập admin', ['admin_id' => $admin->id, 'error' => $e->getMessage()]);
|
|
}
|
|
}
|
|
}
|