Confer Session Storage - php

Very simple question that I can't find the answer for. I'm using Confer in my Laravel app and wish to alter the html that is stored in the session storage for each new message. I've made a few formatting changes to conversation messages in views\conversation.blade.php as well as views\confer.blade.php, but when a user submits a new message, that message is pushed with the original formatting. I can't for the life of me find where the html formatting is passed into the session so it can be pushed to the client.
Confer's SessionController.php
namespace DJB\Confer\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Http\Requests;
use Illuminate\Http\Request;
use Session;
use Response;
class SessionController extends Controller {
/**
* Store the conversation list HTML in the session so that it can be retained over page loads
*
* #param Request $request
* #return Response
*/
public function store(Request $request)
{
Session::put('confer_conversations', $request->input('html'));
return Response::json(['success' => true]); // required to persist the session
}
/**
* Update the requested conversations that have yet to blossom with a message
*
* This needs to persist over page loads otherwise recipient(s) will not be
* subscribed to the channel to receive any messages.
*
* #param Request $request
* #return Response
*/
public function update(Request $request)
{
if (Session::has('confer_requested_conversations'))
{
Session::push('confer_requested_conversations', (int)$request->input('conversation_id'));
} else {
Session::put('confer_requested_conversations', [(int)$request->input('conversation_id')]);
}
return Response::json(['success' => true]); // required to persist the session
}
/**
* Clear the open chat list and requested list
*
* #return Response
*/
public function destroy()
{
Session::forget('confer_conversations');
Session::forget('confer_requested_conversations');
return redirect()->back();
}
}
MessageWasSent
namespace DJB\Confer\Commands;
use Illuminate\Console\Command;
use Illuminate\Queue\InteractsWithQueue;
use DJB\Confer\Message;
use DJB\Confer\Confer;
use Push;
class MessageWasSent extends Command {
use InteractsWithQueue;
protected $message;
protected $confer;
public function __construct(Message $message)
{
$this->message = $message;
$this->confer = new Confer();
}
/**
* Handle the command.
*/
public function handle()
{
$conversation = $this->message->conversation;
$conversation->touch();
if ($conversation->isGlobal())
{
Push::trigger($this->confer->global, 'NewMessageWasPosted', $this->message->getEventData('global'));
} else {
Push::trigger($this->message->conversation->getChannel(), 'NewMessageWasPosted', $this->message->getEventData());
Push::trigger($this->message->conversation->getChannel(), 'UserStoppedTyping', ['user' => $this->message->sender->id]);
}
}
}
namespace DJB\Confer\Events;
class MessageWasSent {
public function __construct()
{
}
public function handle()
{
}
}

Related

Laravel API - Showing individual file through o2m relationship

So I have two models User and File, these are connected with a one-to-many relationship.
I have sorted the API routes and controllers to index all users, show specific user and index all files uploaded by that specific user. I do not know how to write the logic that will allow this route 127.0.0.1:8001/api/2/files/1 to show the first file uploaded by the 2nd user. So/2(seconduser)/files(shows all)/1(shows only 1 file)
This is my API code:
Route::group(["prefix" => "/"], function () {
Route::get("", [Users::class, "index"]); //show all users
Route::group(["prefix" => "{user}"], function () {
Route::get("", [Users::class, "show"]); //show specific user
Route::group(["prefix" => "/files"], function () {
Route::get("", [Files::class, "index"]); //show all files
Route::group(["prefix" => "{file}"], function () {
Route::get("", [Files::class, "show"]); //trying to show specific file
});
});
});
});
Files Controller
<?php
namespace App\Http\Controllers\API;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\User;
use App\Models\File;
class Files extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index(User $user)
{
return $user->files;
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show(User $user, File $file)
{
}
}
Users Controller
<?php
namespace App\Http\Controllers\API;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\User;
class Users extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
return User::all();
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show(User $user)
{
return $user;
}
}
So here's what a typical route declaration would look like. Note the user ID is not relevant to the file request, so the files endpoint is made separate from the users endpoint.
Route::get("/users", [Users::class, "index"]);
Route::get("/users/{user}", [Users::class, "show"]);
Route::get("/users/{user}/files", [Files::class, "index"]);
Route::get("/files/{file}", [Files::class, "show"]);
And then in your controller methods, you're simply returning a list or a single item, mostly as in your original code. Note if you're returning API data, you should explicitly return JSON.
<?php
namespace App\Http\Controllers\API;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\User;
use App\Models\File;
class Files extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\JsonResponse
*/
public function index(User $user)
{
return response()->json($user->files);
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\JsonResponse
*/
public function show(File $file)
{
return response()->json($file);
// or perhaps something like this?
return response()
->download($file->path, $file->name, ["Content-Type" => $file->type]);
}
}
<?php
namespace App\Http\Controllers\API;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\User;
class Users extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\JsonResponse
*/
public function index()
{
return response()->json(User::all());
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\JsonResponse
*/
public function show(User $user)
{
return response()->json($user);
}
}

Class App\Listeners\Request does not exist

I'm trying to make an Ip logger for all successful logins on laravel using event listeners, This is my listener for Login.
<?php
namespace App\Listeners;
use Illuminate\Auth\Events\Login;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
class LogSuccessfulLogin
{
/**
* Create the event listener.
*
* #return void
*/
public function __construct(Request $request)
{
$this->request = $request;
}
/**
* Handle the event.
*#author Rahul R
* #param Login $event
* #return void
*/
public function handle(Login $event)
{
$user = $event->user;
$user->last_login_at = date('Y-m-d H:i:s');
$user->last_login_ip=$this->request->ip();
$user-save();
}
}
And this is my loginController
namespace App\Http\Controllers\pages;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Models\UserLoginModel;
use App\User;
use Illuminate\Support\Facades\Auth;
use Zizaco\Entrust\EntrustFacade as Entrust;
class LoginController extends Controller
{
/**
* User Authentication Table - `users`
* #author Rahul
*
* #method POST
* #param Request | $request
* #return array | $error_message
* #return redirect | login | dashboard
*/
protected function auth(Request $request) {
$user = new User;
$user->email_address = $request->get('email_address');
$user->password = $request->get('password');
$userCredentials['email_address'] = $user->email_address;
$userCredentials['password'] = $user->password;
/* Making Authentication Request */
if(Auth::attempt($userCredentials))
{
/* If Auth true */
if (Entrust::hasRole('admin')) {
return redirect('admin/dashboard');
} else {
return redirect('dashboard');
}
} else {
/* If Auth false */
return redirect("login")->with('failed_login', 'Invalid email address or password.');
}
return redirect('login');
}
}
Where am I doing wrong
I tried adding App\Listeners\Request to the logincontroller but it generates a conflict
So what is the end result I need to get the IP of Successful logins and write it to the database.
In your LogSuccessfulLogin class file add this statement :
use \Illuminate\Http\Request;
because you use Request class in your constructor, php thinks it's in App\Listeners.

How to do auth without database in Laravel 5.6?

I have to make default login in Laravel with: php artisan make:auth and I want to add 1 more authentication with API. In this auth API I don't need database for login.
Is there any solution for this case?
I want to make custom provider and guard it but I am stuck at AlumniAuthProvider.php on App\Auth:
<?php
namespace App\Auth;
use Illuminate\Contracts\Auth\User as UserContract;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Contracts\Auth\UserProvider;
use App\Auth\User;
class AlumniAuthProvider implements UserProvider {
public function alumni()
{
}
public function retrieveById($identifier)
{
}
public function retrieveByToken($identifier, $token)
{
}
public function updateRememberToken(Authenticatable $user, $token)
{
}
public function retrieveByCredentials(array $credentials)
{
}
public function validateCredentials(Authenticatable $user, array $credentials)
{
}
}
and Alumni.php on App\Auth:
<?php
namespace App\Auth;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Http\Request;
class Alumni implements Authenticatable
{
public function getAuthIdentifierName()
{
}
/**
* Get the unique identifier for the user.
*
* #return mixed
*/
public function getAuthIdentifier()
{
}
/**
* Get the password for the user.
*
* #return string
*/
public function getAuthPassword()
{
}
/**
* Get the token value for the "remember me" session.
*
* #return string
*/
public function getRememberToken()
{
}
/**
* Set the token value for the "remember me" session.
*
* #param string $value
* #return void
*/
public function setRememberToken($value)
{
}
/**
* Get the column name for the "remember me" token.
*
* #return string
*/
public function getRememberTokenName()
{
}
}
How could I make this custom API login?
In my opinion this code, which I made, is for second auth, or am I wrong? Maybe is there any other way to solve this problem?
I think doing api login without database is a bad idea because everytime the user will login through another system the api call will took place and thats will create more traffic when your system will be live. Better way is to make api call for the first time and store data in the database and afterwards call data from the database when user re-logins.

Laravel - Event causing 404 error

I am in the process of making realtime notifications and stumbled in this weird error. I have in my model a boot method which triggers an event called SendNotificationData (no listener). It handles when there is a new notification made.
Trial Controller
<?php
namespace App\Http\Controllers\Notification;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Models\Notification;
class NotificationController extends Controller
{
/**
* Trigger event to display notifications. This displays 404 error page
*
* #return none
*/
public function displayNotification()
{
$notification = new Notification();
$notification->EmployeeID = "EMP-00001";
$notification->NotificationText = "There is a new notification";
$notification->NotificationStatus = "unread";
$notification->NotificationType = "trial";
$notification->save();
}
}
Notification model boot method:
/**
* Handle booting of model.
*
* #var string
*/
public static function boot()
{
static::created(function ($data) {
event(new SendNotificationData($data));
});
parent::boot();
}
This is my SendNotificationData event:
namespace App\Events;
use App\Events\Event;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
class SendNotificationData extends Event implements ShouldBroadcast
{
use SerializesModels;
public $new_notification_data;
/**
* Create a new event instance.
*
* #param $notification_data
* #return void
*/
public function __construct($new_notification_data)
{
$this->new_notification_data = $new_notification_data;
}
/**
* Get the channels the event should be broadcast on.
*
* #return array
*/
public function broadcastOn()
{
return ['new-notification'];
}
/**
* Customize event name.
*
* #return array
*/
public function broadcastAs()
{
return 'private-send-new-notification';
}
}
On Javascript
var newNotificationChannel = pusher.subscribe('new-notification');
newNotificationChannel.bind("private-send-new-notification", function(data) {
addNotification(data);
}); //This gives me no error in the console and the 404 error still shows up even if i remove this..
function addNotification(data)
{
console.log(data);
$('.notification-link').closest('li').append('This is a sample notification!!!');
}
Now, If I try to test adding some random notification in my controller, the event fires. However, it shows me the 404 error page. When I removed the ShouldBroadcast interface or remove the contents of the constructor, the error no longer shows up. I am confused what would be causing such an error when my other events are working fine. I might have missed something so please guide me.
I can't believe it, it was caused by the $incrementing variable in the model being set to false instead of true. If only laravel would show me the proper error stack trace.

Custom Request class does not exist, yet it does?

I'm trying to figure out why my custom request class cannot be called by one of my methods.
I created my class with, php artisan make:request ValidateUserSecretRequest.
This created my custom request file in the Http/Requests folder as expected.
However, ValidateUserSecretRequest called within my Auth\LoginController.php, , I get Class App\Http\Controllers\Auth\ValidateUserSecretRequest does not exist.
Here's the controller, with unnecessary methods removed:
namespace App\Http\Controllers\Auth;
use Cache;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use App\Http\Requests\ValidateSecretUserRequest;
use App\Http\Controllers\Controller;
class LoginController extends Controller
{
use AuthenticatesUsers;
public function __construct()
{
$this->middleware('guest')->except('logout');
}
public function postValidateToken(ValidateUserSecretRequest $request)
{
// get user id and create cache key
$userId = $request->session()->pull('2fa:user:id');
$key = $userId . ':' . $request->totp;
// use cache to store token to blacklist
Cache::add($key, true, 4);
// login and redirect user
Auth::loginUsingId($userId);
return redirect()->intended($this->redirectTo);
}
And my custom request class:
namespace App\Http\Requests;
use Cache;
use Crypt;
use Google2FA;
use App\User;
use App\Http\Requests\Request;
use Illuminate\Validation\Factory as ValidatonFactory;
use Illuminate\Foundation\Http\FormRequest;
class ValidateUserSecretRequest extends FormRequest
{
/**
*
* #var \App\User
*/
private $user;
/**
* Create a new FormRequest instance.
*
* #param \Illuminate\Validation\Factory $factory
* #return void
*/
public function __construct(ValidatonFactory $factory)
{
$factory->extend(
'valid_token',
function ($attribute, $value, $parameters, $validator) {
$secret = Crypt::decrypt($this->user->google2fa_secret);
return Google2FA::verifyKey($secret, $value);
},
'Not a valid token'
);
$factory->extend(
'used_token',
function ($attribute, $value, $parameters, $validator) {
$key = $this->user->id . ':' . $value;
return !Cache::has($key);
},
'Cannot reuse token'
);
}
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
try {
$this->user = User::findOrFail(
session('2fa:user:id')
);
} catch (Exception $exc) {
return false;
}
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'totp' => 'bail|required|digits:6|valid_token|used_token',
];
}
}
I've tried:
composer dump-autoload
composer update
scratching my head multiple times
recreating the custom request with artisan with a different name, same problem
What the hell is going on here?
You have written "use App\Http\Requests\ValidateSecretUserRequest;" while you are using "ValidateUserSecretRequest" class, There is a typo.
Error in use App\Http\Requests\ValidateSecretUserRequest; You can check it again.
You get Class App\Http\Controllers\Auth\ValidateUserSecretRequest does not exist since it doesn't really exists. App\Http\Controllers\Auth\ prefix in the error means that it uses current namespace.
Look at ValidateUserSecretRequest - you should swap User and Secret to write correct class name.
You have the class name wrong
You have it as
App\Http\Requests\ValidateSecretUserRequest;
but actually it is ValidateUserSecretRequest

Categories