Broadcast channels not being registered in Laravel - laravel

I've been stuck with Broadcasting on private channel in authentication part. What I have done is, I made custom authEndpoint in Echo server
"authEndpoint": "/broadcastAuth",
Controller:
public function broadcastAuth(Request $request){
$channel = $this->normalizeChannelName($request->channel_name);
$broadcaster = new CustomBroadcaster();
$channelAuth = $broadcaster->verifyUserCanAccessChannel($request, $channel);
if($channelAuth){
return true;
}
return response()->json([
'message' => 'Not allowed'
], 403);
}
I have made a custom broadcaster class that extends Illuminate\Broadcasting\Broadcasters\Broadcaster
so that I can override verifyUserCanAccessChannel method
My verifyUserCanAccessChannel method:
public function verifyUserCanAccessChannel($request, $channel)
{
Log::info($this->channels);
foreach ($this->channels as $pattern => $callback) {
if (! $this->channelNameMatchesPattern($channel, $pattern)) {
continue;
}
$parameters = $this->extractAuthParameters($pattern, $channel, $callback);
$handler = $this->normalizeChannelHandlerToCallable($callback);
if ($result = $handler($request->user(), ...$parameters)) {
return $this->validAuthenticationResponse($request, $result);
}
}
throw new AccessDeniedHttpException;
}
Here I have logged $this->channels to get the registered channels from routes/channel.php
But the result is empty.
Here is my BroadcastServiceProvider:
public function boot()
{
require base_path('routes/channels.php');
}
Here is my channel.php:
Broadcast::channel('App.User.{id}', function ($user, $id) {
return (int) $user->id === (int) $id;
});
Broadcast::channel('post-comment.{id}', function ($user, $id){
\Illuminate\Support\Facades\Log::info($user);
return true;
});
And I have uncommented both in config/app.php
Illuminate\Broadcasting\BroadcastServiceProvider::class,
App\Providers\BroadcastServiceProvider::class,
What could be the mistake here. Please help me figure this out.
Thank you in advance.

Related

Laravel Broadcast send message to multiple user. Can we send message to particular user

Channel.PHP
These is my Channels.php File.
Broadcast::channel('privatechat.{id}', function ($user, $id) {
return (int) $user->id === (int) $id;
});
ChatComponent.vue
There is my ChatCompnent.vue file
Echo.private('privatechat.'+props.user.id)
.listen('SendMessage', (e) => {
messages.value.push({
message: e.message.message,
user: e.user
// reciver_id: props.userid
});
})
Events/SendMessage.php
There is my Events File
public function broadcastOn()
{
// dd($this->message->rec_id);
// $newiadid = $this->message->rec_id;
// dd($newiadid);
return new PrivateChannel('privatechat.'.$this->message->rec_id);
}
ChatController.php
There is my Controller File
public function messagesStore(Request $request) {
$user = Auth::user();
$reccid = $request->rec_id;
$messages = $user->messages()->create([
'message' => $request->message,
'rec_id' => $request->rec_id
]);
broadcast(new SendMessage($user, $messages))->toOthers();
return 'message sent';
}

Laravel 7: custom guard authentication does not work as expected

I have a multiauth project. I have the default authentication and a custom guard. At the login controller, when I make the login attempt, it authenticates as expected. However, when it gets to the homepage, the custom guard is not logged in anymore.
Users that use the custom guard already log in through an external API, so i don't want them on my users table. I just need a couple of fields to show them some content.
LoginController.php (Up to the return, attempt method returns TRUE)
...irrelevant code...
Auth::guard('ivao')->attempt(array('vid' => $user_array->vid, 'name' => $user_array->name, 'surname' => $user_array->surname), true);
Cookie::queue(Cookie::forever($this->cookie_name, $_COOKIE['ivao_token']));
Cookie::queue(Cookie::forever('vid', $user_array->vid));
return redirect('/');
...irrelevant code...
CustomProvider.php
class CustomUserProvider extends ServiceProvider implements UserProvider
{
public function retrieveById($identifier)
{
}
public function retrieveByToken($identifier, $token)
{
if(Cookie::get('rememberToken') == $token)
{
$user = new ApiUser();
$user->vid = Cookie::get('vid');
$user->name = Cookie::get('name');
$user->surname = Cookie::get('surname');
return $user;
}
else return NULL;
}
public function updateRememberToken(UserContract $user, $token)
{
if(Cookie::get('rememberToken') == $token)
{
Cookie::queue(Cookie::forever('vid', $user->vid));
Cookie::queue(Cookie::forever('name', $user->name));
Cookie::queue(Cookie::forever('surname', $user->surname));
Cookie::queue(Cookie::forever('rememberToken'), $token);
return TRUE;
}
else return FALSE;
}
public function retrieveByCredentials(array $credentials)
{
$user = new ApiUser();
$user->vid = $credentials['vid'];
$user->name = $credentials['name'];
$user->surname = $credentials['surname'];
return $user;
}
public function validateCredentials(UserContract $user, array $credentials)
{
return TRUE; //already validated at the API
}
}
Homepage Controller (Here both check methods return FALSE)
class PagesController extends Controller
{
public function index($folder= '', $page= 'inicio')
{
if( !(Auth::check() || Auth::guard('ivao')->check()) ) return redirect('/login');
...irrelevant code...
Please let me know if you need further information. Hope someone can help. I'm stuck. Thanks.

How add new parameter to check in login Laravel

In LoginController I override the credentials method, like this:
protected function credentials(Request $request)
{
$credentials = $request->only($this->username(), 'password');
$credentials['status'] = User::STATUS_ACTIVE;
return $credentials;
}
And this work pretty fine. But when a try to add a parameter which is not a column of the Users table I don't know how to check there. Some like this:
protected function credentials(Request $request)
{
$credentials = $request->only($this->username(), 'password');
$credentials['status'] = User::STATUS_ACTIVE;
$credentials['customer-status'] = Customer::STATUS_ACTIVE;
return $credentials;
}
Where can I check if the value is correct? I tried to make an event listener to attempt login, but it doesn't work. My idea is to make an Eloquent query to return an account of customers activities. If more then one, customer-status for this user is true.
If anyone is interested in knowing how I solved it, the explanation is as follows:
Based on this code I found in github: https://gist.github.com/joseluisq/fb84779ea54eaebf54a9d8367117463e
In LoginController.php I override 2 methods(login and sendFailedLoginResponse):
public function login(Request $request)
{
$this->validateLogin($request);
if ($this->hasTooManyLoginAttempts($request)) {
$this->fireLockoutEvent($request);
return $this->sendLockoutResponse($request);
}
$this->incrementLoginAttempts($request);
$user = User::where('email', $request->email)->first();
if (!$user) {
return $this->sendFailedLoginResponse($request);
}
$customers = Customer::join('users_customers', 'users_customers.customer_id', 'customers.id')
->where([
['users_customers.user_id', '=', $user->id],
['customers.status', '=', Customer::STATUS_ACTIVE]
])
->count();
if ($customers === 0) {
return $this->sendFailedLoginResponse($request, 'auth.inactive');
}
if ($this->attemptLogin($request)) {
return $this->sendLoginResponse($request);
}
return $this->sendFailedLoginResponse($request);
}
protected function sendFailedLoginResponse(Request $request, $trans = 'auth.failed')
{
$errors = ['email' => trans($trans)];
if ($request->expectsJson()) {
return response()->json($errors, 422);
}
return redirect()
->back()
->withErrors($errors);
}
Remember yourself to define message on auth.php and set uses needed.
Ps.: I don't use $credentials['customer-status'] = Customer::STATUS_ACTIVE;,
as I thought I would.

laravel notifications not storing into my database plus error

i couldn't store the notification into my notification table inside my database,
i was trying to make notification every time there is a new Post how can i make this work.
Error:
Notification:
use Queueable;
public $post;
public function __construct()
{
}
public function via($notifiable)
{
return ['database'];
}
public function toDatabase($notifiable)
{
return [
'title' => $this->post->title,
];
}
public function toArray($notifiable)
{
return [
];
}
}
Post Controller:
public function store(Request $request)
{
$this->validate($request, [
'title'=>'required|max:100',
'body' =>'required',
]);
$title = $request['title'];
$body = $request['body'];
$post = Post::create($request->only('title', 'body'));
Auth::user()->notify(new NotifyPost($post));
return redirect()->route('posts.index')
->with('flash_message', 'Article,
'. $post->title.' created');
}
You need to inject the post within the construct, or else it never gets resolved.
protected $post;
public function __construct(Post $post)
{
$this->post = $post;
}

Switching user in laravel 5.4

I am switching users in laravel and I succeeded in that as well but the thing is when I redirect the user to the dashboard after successful login it redirects to login form instead I don't know what am I doing wrong. Here is the code I am using.
public function user_reauthenticate(Request $request) {
$input = Input::all();
$data = User::where('email', $input['email'])->first();
if ($data) {
if (Hash::check($input['password'], $data->password)) {
Session::put('email', $input['email']);
$newuser = Student::find($input['new_user']);
session(['orig_user' => $data->id]);
Auth::login($newuser);
return Redirect::back();
} else {
$response = 'Wrong Credentials';
}
} else {
$response = 'User does not exist';
}
}
Can anyone help me find out the issue?
Edited
You can log in with
Auth::loginUsingId(1);
New edited
// If you have the guard student and multiple auth
$auth = auth()->guard('student');
$objAuth = $auth->loginUsingId($input['new_user']);
//Single Auth
$objAuth = Auth::loginUsingId($input['new_user']);
Add this to your top of the file:- use Illuminate\Foundation\Auth\AuthenticatesUsers;
Afterwards add a if function like below in your already completed code:-
public function user_reauthenticate(Request $request)
{
use AuthenticatesUsers;
$input = Input::all();
$data = User::where('email', $input['email'])->first();
if ($data) {
if (Hash::check($input['password'], $data->password))
{
Session::put('email', $input['email']);
$newuser = Student::find($input['new_user']);
session(['orig_user' => $data->id]);
Auth::login($newuser);
if ($this->attemptLogin($request))
{
return $this->sendLoginResponse($request);
}
}
else
{
$response = 'Wrong Credentials';
}
}
else
{
$response = 'User does not exist';
}
}
After this method override this method as follows:-
protected function authenticated(Request $request, $user)
{
return redirect()->route('dashboard');
}
Check whether your dashboard route is named dashboard or if not name it.

Resources