laravel broadcast channel is not calling after changing auth endpoint - laravel

i am developing teacher and student chat system in laravel and vuejs using pusher. So as i read from documentation that laravel by default do the user authentication for private and presence channel so both my model are different one is student and other one is teacher both are not extend from Authenticatable so what i did is change the authendpoint and make a new route and return the pusher ath:key i,m successfully doing that but now the problem is after returning auth response Echo.private is not calling my channel
This is my Channel.php file code
Broadcast::channel('student-messages.{id}', function($id) {
return true;
},['guards'=>['web']]);
This is my chat app file code
window.Echo.private(`student-messages.${this.student.id}`)
.listen('NewMessage',(e)=>{
console.log(e);
});
This is my route in web.php
Route::post('/custom/endpoint/auth',function (Request $request){
$pusher = new Pusher\Pusher(env('PUSHER_APP_KEY'),env('PUSHER_APP_SECRET'), env('PUSHER_APP_ID'));
return $pusher->socket_auth($request->request->get('channel_name'),$request->request->get('socket_id'));
});

Related

How does Laravel Model Broadcasting deal with private channel auth? And some other questions about broadcasting in Laravel

I'm working on a simple chat web app using Laravel.
I've decided to use the Model broadcasting routine here.
But I don't know how model broadcasting authorize users.
I know the standard method is like:
Broadcast::channel('orders.{orderId}', function ($user, $orderId) {
return $user->id === Order::findOrNew($orderId)->user_id;
});
While model broadcasting also broadcasts on private channels, the docs doesn't describe if developers need to set up authorization callbacks.
So, do I need to create a private channel authorization callback like:
Broadcast::channel('App.User.{userId}', function ($user, $userId) {
return $user->id === userId;
});
And the second question: can I create different private channels authorization callbacks for different auth guards like:
Broadcast::channel('channel.{memberId}', function ($member, $memberId) {
// ...
}, ['guards' => ['member']]);
Broadcast::channel('channel.{adminId}', function ($admin, $adminId) {
// ...
}, ['guards' => ['admin']]);
The last question: does the broadcasting in Laravel support client-to-client broadcasting? Because I need to limit who can send messages to specific channels, if the client-to-client behavior exists it may effect the privacy of users in my app.
My native language is not English. Sorry if my words are not clear.

Laravel Websockets - Private Channel

I am fiddling with Laravel websockets for the first time.
Currently i am just using plain JS WebSocket client (not Laravel Echo).
They way i see it, laravel echo provides an 'authEndpoint' for private and presence channels.
This allows you to create Broadcast::channel() callback that looks like this
Broadcast::channel('App.User.{id}', function ($user, $id) {
return (int) $user->id === (int) $id;
});
What puzzles me now, is that when i make a websocket connection with the WebSocket native client and i dont provide the auth endpoint, i can just subscribe to my private channel, and thus bypass all auth completely?
Is this correct or am i missing something?
My goal is to have private channels that reject access is the auth endpoint was not provided.
What does your broadcast routing look like? Any middleware?
From Laravel:
Broadcast::channel('channel', function () {
// ...
}, ['guards' => ['web', 'admin']]);

how to check if user is authenticated with passport (get user from token using laravel-passport)

I am using Passport to log in users to a Laravel API endpoint, users get authenticated using their social accounts (google, facebook) using laravel-socialite package.
the workflow of logging users in and out works perfectly (generating tokens...Etc). The problem is I have a controller that should return data based on whether there is a user logged in or not.
I do intercept the Bearer token from the HTTP request but I couldn't get the user using the token (I would use DB facade to select the user based on the token but I am actually looking whether there is a more clean way already implemented in Passport)
I also don't want to use auth:api middleware as the controller should work and return data even if no user is logged in.
this is the api route:
Route::get("/articles/{tag?}", "ArticleController#get_tagged");
this is the logic I want the controller to have
public function get_tagged($tag = "", Request $request)
{
if ($request->header("Authorization"))
// return data related to the user
else
// return general data
}
Assuming that you set your api guard to passport, you can simply call if (Auth::guard('api')->check()) to check for an authenticated user:
public function get_tagged($tag = "", Request $request)
{
if (Auth::guard('api')->check()) {
// Here you have access to $request->user() method that
// contains the model of the currently authenticated user.
//
// Note that this method should only work if you call it
// after an Auth::check(), because the user is set in the
// request object by the auth component after a successful
// authentication check/retrival
return response()->json($request->user());
}
// alternative method
if (($user = Auth::user()) !== null) {
// Here you have your authenticated user model
return response()->json($user);
}
// return general data
return response('Unauthenticated user');
}
This would trigger the Laravel authentication checks in the same way as auth:api guard, but won't redirect the user away. In fact, the redirection is done by the Authenticate middleware (stored in vendor/laravel/framework/src/Illuminate/Auth/Middleware/Authenticate.php) upon the failure of the authentication checking.
Beware that if you don't specify the guard to use, Laravel will use the default guard setting in the config/auth.php file (usually set to web on a fresh Laravel installation).
If you prefer to stick with the Auth facade/class you can as well use Auth::guard('api')->user() instead or the request object.
thanks to #mdexp answer
In my case I can resolve my problem with using
if (Auth::guard('api')->check()) {
$user = Auth::guard('api')->user();
}
In my controller.

API endpoint in Laravel hook

Is it possible to establish an API endpoint in a laravel voyager hook?
All the documentation I can find shows how to set up a listener for a web request, but these endpoints will not take a post.
Just create the post route in your api routes file.
Example:
// routes/api.php
<?php
Route::post('/webhooks', 'WebhooksController');
// app/Http/Controllers/Api/WebhooksController
public function __invoke(Request $request)
{
// handle webhook
}
Then posting data to yourapp.test/api/webhooks should work.

Authentication check for non auth url in laravel passport api

i am using passport authentication for my Laravel 5.4 API.here i have a api for company details and it is a non auth api.i need to check logined user liked this company using auth in this url ...how i can do this.
This is my route
Route::get('/company/{company}','Api\V1\CompanyController#show');
Route::group(['middleware' => 'auth:api','prefix'=>'v1'], function(){
//auth urls
}
and this is my controller
class CompanyController extends Controller
{
public function show(Company $company,Request $request)
{
$data = array();
$flag = 0;
$data['status'] = 1;
$data['message'] = 'success';
$data['baseUrl'] = url('/');
$data['is_login'] = Auth::check();
Here is_login always return false,if i added autherization token in headers of api.
What is your default guard set as?
Auth::check() is Auth::guard(null)->check() which uses the current default guard.
If you want to check for an api you probably want to use the api guard just like your auth middleware is using when you use auth:api.
Auth::guard('api')->check() tells it to explicitly use the api guard instead of what the default is, which could be anything since we don't know what you have set.
When the auth middleware is ran it actually will set the default guard for you depending upon what guards are passed to it and which one it can resolve a user from. Which is why you can just call Auth::user() and get the correct user from the correct guard, because the middleware sets the current to the one that resolved the user. (When calling routes that have this middleware)

Resources