Last active
November 23, 2022 19:45
-
-
Save james2doyle/53c29871f92136767ed464931f82c8bc to your computer and use it in GitHub Desktop.
Console command to generate a valid session cookie for a authenticated user in a Laravel app
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
declare(strict_types=1); | |
use App\Models\User; | |
use Illuminate\Support\Facades\Artisan; | |
use Symfony\Component\HttpFoundation\Cookie; | |
use Illuminate\Cookie\CookieValuePrefix; | |
Artisan::command('user-cookie', function (): void { | |
/** @var User */ | |
$user = User::where('email', 'user@laravel.com')->firstOrFail(); | |
/** @var \Illuminate\Auth\SessionGuard */ | |
$guard = auth()->guard('web'); | |
$guard->getSession()->start(); | |
$guard->login($user); | |
// persist this session so the id is valid | |
$guard->getSession()->save(); | |
$name = $guard->getSession()->getName(); | |
$data = $guard->getSession()->getId(); | |
$config = config('session'); | |
$expires = now()->add('minutes', env('SESSION_LIFETIME'))->timestamp; | |
/** @var \Illuminate\Encryption\Encrypter */ | |
$encrypter = $guard->getSession()->getEncrypter(); | |
// assumes that the cookies are encrypted | |
$value = $encrypter->encrypt( | |
CookieValuePrefix::create($name, $encrypter->getKey()) . $data, | |
false // do not serialize | |
); | |
$cookie = new Cookie( | |
$name, $value, $expires, | |
$config['path'], $config['domain'], $config['secure'], false, false, $config['same_site'] ?? null | |
); | |
/** | |
* @psalm-suppress InvalidScope | |
*/ | |
$this->comment(sprintf('%s', $cookie)); | |
})->purpose('Display a valid cookie for a user'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment