I need to make a change to the retrieveUser() function within Illuminate/Broadcasting/Broadcasters/Broadcaster.php.
The change works if I edit the class directly, but I have heard that you are not supposed to do that because it is difficult to track changes to the source code and because it will get overwritten when upgrading Laravel or when pushing to production.
So if I wanted to write my own modified retrieveUser() function for the Broadcaster class (it happens to be an abstract class which implements BroadcasterContract), then where and how would I do that?
Original function:
/**
* Retrieve the authenticated user using the configured guard (if any).
*
* @param \Illuminate\Http\Request $request
* @param string $channel
* @return mixed
*/
protected function retrieveUser($request, $channel)
{
$options = $this->retrieveChannelOptions($channel);
$guards = $options['guards'] ?? null;
if (is_null($guards)) {
return $request->user();
}
foreach (Arr::wrap($guards) as $guard) {
if ($user = $request->user($guard)) {
return $user;
}
}
}
New function:
protected function retrieveUser($request, $channel)
{
$options = $this->retrieveChannelOptions($channel);
$guards = $options['guards'] ?? null;
if (is_null($guards)) {
$token = $request->header('Token');
$id = Crypt::decrypt($token);
$user = User::find($id);
return $user;
}
foreach (Arr::wrap($guards) as $guard) {
if ($user = $request->user($guard)) {
return $user;
}
}
}
UPDATE
As @ggdx pointed out in the comments, I can override the class by doing class yourClass extends Illuminate\Broadcasting\Broadcasters\Broadcaster
However, I still don't know where to put this new class within the Laravel framework. I tried creating the new class in the /app route, but that did not work.
I'm not completely sure what you are trying to accomplish. But I think making a custom driver for a guard will do what you want. Looking at the docs https://laravel.com/docs/5.8/authentication#adding-custom-guards
You can do this in the boot method of your AuthServiceProvider.
Auth::viaRequest('custom-token', function ($request) {
return User::find(Crypt::decrypt($request->header('Token')));
});
Also, make sure to select it as the driver for your guard in your auth.php config file.