ldc-web/app/Providers/EventServiceProvider.php
2022-09-21 11:17:58 +00:00

97 lines
3.2 KiB
PHP

<?php
namespace App\Providers;
use Aacotroneo\Saml2\Events\Saml2LoginEvent;
use App\Models\User;
use Illuminate\Auth\Events\Registered;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Session;
class EventServiceProvider extends ServiceProvider
{
/**
* The event listener mappings for the application.
*
* @var array
*/
protected $listen = [
Registered::class => [
],
];
/**
* Register any events for your application.
*
* @return void
*/
public function boot()
{
parent::boot();
Event::listen('Aacotroneo\Saml2\Events\Saml2LoginEvent', function (Saml2LoginEvent $event) {
$messageId = $event->getSaml2Auth()->getLastMessageId();
if (class_exists('Memcached')) {
$cache = new \Memcached();
$cache->addServer(
config('cache.stores.memcached.servers.0.host'),
config('cache.stores.memcached.servers.0.port')
);
$fromCache = $cache->get(config('cache.prefix') . "_saml_message_id_" . $messageId);
if (!in_array($cache->getResultCode(), [\Memcached::RES_SUCCESS, \Memcached::RES_NOTFOUND])) {
throw new \Exception(
\sprintf(
"SAML MESSAGE ID HANDLER - Memcached Error : %d - %s",
$cache->getResultCode(),
"https://www.php.net/manual/en/memcached.getresultcode.php"
)
);
}
if ($fromCache) {
logger()->error(
'SAML MESSAGE ID HANDLER',
[
'error' => 'Message ID : ' . $messageId . " replayed !"
]
);
abort(403);
} else {
// Cache for 8h.
$cache->set(config('cache.prefix') . "_saml_message_id_" . $messageId, $messageId, 28800);
if ($cache->getResultCode() === \Memcached::RES_NOTSTORED) {
throw new \Exception('SAML MESSAGE ID HANDLER - Memcached Error : NOT STORED');
}
}
} else {
throw new \Exception("SAML MESSAGE ID HANDLER - Memcached is missing");
} //end if
$user = $event->getSaml2User();
$email = $user->getNameId();
$lUser = User::where('email', '=', $email)->first();
if (!$lUser) {
abort(redirect()->route('unauthorized'));
}
session(['sessionIndex' => $user->getSessionIndex()]);
session(['tmpUserOTP' => $lUser]);
abort(redirect()->route('auth.verify'));
});
// phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.FoundInExtendedClass
Event::listen('Aacotroneo\Saml2\Events\Saml2LogoutEvent', function ($event) {
Auth::logout();
Session::save();
});
}
}