Skip to content

Instantly share code, notes, and snippets.

@Malezha
Created August 25, 2015 20:23
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Malezha/a9bdfbddee15bfd624d4 to your computer and use it in GitHub Desktop.
Save Malezha/a9bdfbddee15bfd624d4 to your computer and use it in GitHub Desktop.
Verifying access to channel
<?php
namespace App\Http\Controllers\Admin\API;
use App\Http\Controllers\Controller;
use App\Models\Channel;
use Illuminate\Http\Request;
class Centrifuge extends Controller
{
/**
* Check for access to the channel for authorized user
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\JsonResponse|\Symfony\Component\HttpFoundation\Response
*/
public function postAuth(Request $request)
{
// On request is sent cookies
// Checking authorization
if (auth()->check()) {
$client = $request->get('client');
$channels = $request->get('channels');
// If $channels isn't array make it
$channels = is_array($channels) ? $channels : [$channels];
// Getting the user ID
$userId = auth()->user()->id;
$response = [];
// Receiving channels with users who can subscribe to the channel
$channelModels = Channel::with('users')->whereIn('name', $channels)->get();
foreach ($channels as $channel) {
// Getting key array, which matches the channel name requested
$key = $channelModels->search(function ($item, $key) use ($channel) {
return $item->name == $channel;
});
// If the key is false, so the requested channel does not exist
if ($key !== false) {
$channelModel = $channelModels[$key];
// Info currently empty
$info = json_encode([]);
// Check for access to the channel from user
if ($channelModel->userHasAccess($userId)) {
// Result positive, generating signature
$response[$channel] = [
'sign' => $this->generateChannelSign($client, $channel, $info),
'info' => $info,
];
} else {
// Access denied
$response[$channel] = [
'status' => 403,
];
}
} else {
// Channel not found
$response[$channel] = [
'status' => 404,
];
}
}
return response()->json($response);
} else {
return response('Unauthorized', 401);
}
}
/**
* @param string $client
* @param string $channel
* @param string $info
* @return string
*/
private function generateChannelSign($client, $channel, $info = '')
{
$ctx = hash_init('sha256', HASH_HMAC, config('broadcasting.connections.centrifuge.projectSecret'));
hash_update($ctx, (string) $client);
hash_update($ctx, (string) $channel);
hash_update($ctx, (string) $info);
return hash_final($ctx);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment