Created
October 4, 2023 12:58
-
-
Save finagin/b2292d4db8a2411f5861ebf5c2e35f5d to your computer and use it in GitHub Desktop.
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 | |
use Illuminate\Contracts\Auth\Authenticatable; | |
use Illuminate\Support\Facades\Auth; | |
use Illuminate\Support\Facades\Gate; | |
Auth::macro('shadow', function ($user = null) { | |
$ability = 'shadowLogin'; | |
$key = 'shadow.user.id'; | |
switch (true) { | |
case is_callable($user): | |
Gate::define($ability, $user); | |
return null; | |
case $user instanceof Authenticatable: | |
if (Gate::allows($ability)) { | |
session()->flush(); | |
session()->put($key, auth()->id()); | |
auth()->login($user); | |
} | |
return null; | |
case $user === false: | |
if ($id = session()->pull($key)) { | |
session()->flush(); | |
auth()->loginUsingId($id); | |
} | |
return null; | |
default: | |
return Users::find( | |
session()->get($key) | |
); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment