Skip to content

Instantly share code, notes, and snippets.

@wayanjimmy
Last active January 4, 2024 09:32
Show Gist options
  • Save wayanjimmy/afa85e211e2cdd6bacf5daa849bac749 to your computer and use it in GitHub Desktop.
Save wayanjimmy/afa85e211e2cdd6bacf5daa849bac749 to your computer and use it in GitHub Desktop.
Extend Laravel SessionGuard
<?php
namespace App\Providers;
use App\Extensions\SessionAnonymousGuard;
use Illuminate\Auth\SessionGuard;
use Illuminate\Contracts\Auth\Access\Gate as GateContract;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
class AuthServiceProvider extends ServiceProvider
{
/**
* The policy mappings for the application.
*
* @var array
*/
protected $policies = [
'App\Model' => 'App\Policies\ModelPolicy',
];
/**
* Register any application authentication / authorization services.
*
* @param \Illuminate\Contracts\Auth\Access\Gate $gate
* @return void
*/
public function boot(GateContract $gate)
{
$this->registerGuardExtension();
$this->registerPolicies($gate);
}
protected function registerGuardExtension()
{
$this->app['auth']->extend('session.anonymous', function ($app, $name, array $config) {
$provider = $this->app['auth']->createUserProvider($config['provider']);
$guard = new SessionAnonymousGuard($name, $provider, $app['session.store']);
// When using the remember me functionality of the authentication services we
// will need to be set the encryption instance of the guard, which allows
// secure, encrypted cookie values to get generated for those cookies.
if (method_exists($guard, 'setCookieJar')) {
$guard->setCookieJar($this->app['cookie']);
}
if (method_exists($guard, 'setDispatcher')) {
$guard->setDispatcher($this->app['events']);
}
if (method_exists($guard, 'setRequest')) {
$guard->setRequest($this->app->refresh('request', $guard, 'setRequest'));
}
return $guard;
});
}
}
<?php
namespace App\Extensions;
use Illuminate\Auth\SessionGuard;
class SessionAnonymousGuard extends SessionGuard
{
public function user()
{
$result = parent::user();
if (! is_null($result)) {
return $result;
}
return $this->provider->createModel()->first();
}
public function check()
{
return $this->provider->createModel()->first()->id != 1;
}
}
@sarahman
Copy link

Thanks for this; I've got that very much helpful for my problem!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment