How to Hide Required Parameters Laravel Route - laravel

So I have a booking system. Basically it has this route
localhost:8080/itpr/booking/details/{$bookingId}
Where $bookingId = is the id in the booking_table.
My question, is there a way to hide the $bookingId from my routes from the the user? I don't want other users to be able to access to other booking transaction just by changing the $bookingId in the URL.

The easiest way to achieve this is by submiting your post request via AJAX. But if you are not comfortable using ajax request. You can create a policy that allows only the owner of those booking to make change: see code below.
php artisan make:policy BookingPolicy --model=Booking
Register the policy in your AuthServiceProvider: use App\Policies\BookingPolicy;
protected $policies = [
Booking::class => BookingPolicy::class,
];
Now inside your BookingPolicy then define policy for any method that you want to restrict users from. For example let make sure onl the authenticated user(owner) can update his booking. In this scenario we are assuming that you have user_id column in your Booking table and you have relationship between these 2 tables
public function update(?User $user, Booking $booking)
{
return $user->id === $booking->user_id;
}
Now in your BookingController you can call implement the authorizing actions(can or cant)
public function update(Request $request, $id) {
if ($user->can('update', $booking)) {
// Executes the "create" method on the relevant policy...
}
}
Hopefully this will help :)

have you considered using $table->uuid('id'); for PK? So that the users are not going to guess other bookings easily.

Add a check in your route if the booking ID is one that belongs to the user trying to access the ID. If not, redirect.
Otherwise, provide a dashboard like route showing the user bookings. then make an asynchronous call on the click using your userID/bookingID send that data to a template with a route that is something like your booking/details

Please Check Laravel Policy and define rules to check if the booking id is associated with the current user or not and . which can help you to secure the booking detail from unauthorized user.

Related

How to restrict users to use application

I am using laravel framework to develop api’s ,it’s an existing application .there is a requirement if more than 5users registered from 6th user onwards i have to restrict them to use application until they approved by manager or they paid for registration fee then only the user will allow to use the application.
Can anyone give me the idea how to acheive this scenario or suggest me any package in laravel
Solution:
You can add 'status' field in your table. Now when your api is registering a user, you can check the No. of users in the database. If more than or equals to 5, you can set the status to 0. Now show the manager list of user with status 0 and when the status changes you can use the application.
Make sure to add condition where status = 1 when user is getting logged in.
I hope it helps!
Well, you can just put a isApproved column to indicate if the user is already approved or just like the email_verified_at that accepts timestamp as a value then create a middleware where you can check if the user is approved or not. then add a method to the user model to check if the user is approve :
User model
class User extends Authenticatable
{
public function isApproved()
{
// check if the account_approved_at column is not null.
return ! is_null($this->account_approved_at);
}
}
Middleware
class EnsureUserIsApproved
{
public function handle(Request $request, Closure $next)
{
if(! $request->user()->isApproved()) {
// can also use abort(403) instead of redirect
return redirect('route-where-you-want-the-user-to-redirect')
}
return $next($request);
}
}
You can check this for more information about middleware

Laravel passport - Allow user to act as/login as other user

I'm working on an application where some users should have access to other user accounts. For example: In a family, the mother and all 3 kids have an account. Now the mother should have access to all of the kids accounts.
Is there a possibility to setup something like this in Laravel using Passport? I thought about a "permission" database table with two columns (parent_account, child_account). Parent accounts could then switch between accounts where they have the permission.
Perfect would be something like a middleware where I can set Auth::actAs($child);and after that every Auth::user() call would be the child until I switch back to the "normal" account.
Additional information: I'm using Laravel to provide an API for my React Frontend Application. I tried the Auth::loginUsingId function, but when I use it I get logged out and I get the Method Illuminate\Auth\RequestGuard::loginUsingId does not exist. Exception.
I am using Laravel Version 6.9.0
I found a solution to my problem.
I added a middleware that contains this piece of code:
public function handle($request, Closure $next)
{
$activeChild = Auth::user()->activeChild; // id of child user
if ($activeChild) {
Auth::setUser($activeChild);
}
return $next($request);
}
After that I added this middleware to all routes:
Route::group(['middleware' => ['actAsUser']], function () {
// some routes
});

Laravel check if user belongs to certain company before login

I'm developing an application to help companies manage its products.
First, the company should register itself to the app with an active admin user. The new registered company is not active by default.
I want to check if the user company active before logging in.
For example:
I want to register Nike to the app . the registered user is admin#nike.com
if I want to login with "admin#nike.com", it should not be possible till Nike company become active.
Database structure is like this:
Company:
com_id
com_name
com_isActive
User:
user_id
user_name
email
password
user_isAdmin
user_com_id
Any suggestions how to fix it?
Probably you have relation in your User model. Something like
public function company()
{
return $this->belongsTo(Company::class);
}
In your LoginController (if you want it only there) or in some middleware you can check request()->user()->company()->is_active and do whatever you need. RedirectIfAuthenticated middleware is a variant if you don't want to make new middleware
1.First add column to the company table called isActive and adminEmail
2.Make a new Validation Rule called CheckCompanyStatus by this command
php artisan make:rule CheckCompanyStatus
3.Inside this rule put the following logic inside passes()
$data = \Company::where('adminEmail',$value)->first();
if($data->isActive == true) {
return true;
} else {
return false;
}
Go to LoginController and override the function validateLogin() and put this logic
protected function validateLogin(Request $request)
{
$this->validate(['email'=>new \CheckCompany, 'password'=>
'required]);
}
Make sure to add adminEmail and isActive in your company registration form as well
and use all the classes at the top
Let me know if u have any errors

how to restrict user from accessing another user's pages by inputing id in url laravel

I have a web app i'm working on.Users can create patients, which have a unique id. Problem I have is that when another user logs in, he can easily access patients not assigned to him by simply inputing their id in the url. Please how do i solve this? Heres a sample of my route for the
user to view his patient:
Route::get('patients/{patient}/view', 'Portal\PatientController#viewPatient');
and in the Patientcontroller:
public function viewPatient($patient){
$patient = Patient::where('id', $patient)->first();
return view ('portal.patient',compact('patient'));
}
Please what am I doing wrong?
You can use policies for that:
Policies are classes that organize authorization logic around a particular model or resource. For example, if your application is a blog, you may have a Post model and a corresponding PostPolicy to authorize user actions such as creating or updating posts.
Or gates:
Gates are Closures that determine if a user is authorized to perform a given action
I'd use policies, but you also can manually check if a user can view a page with something like:
if (auth()->id() !== $patient) {
return redirect('/')->with('message', 'You can not view this page');
}
You could also keep GET to access to this page without inputing the id. For example, if you want to obtain patients only from the current user logged in :
web.php :
Route::get('patients/view', 'Portal\PatientController#viewPatient');
Patientcontroller :
public function viewPatient(){
$id = auth()->id();
$patient = Patient::where('id', $id)->first();
return view ('portal.patient',compact('patient'));
}
Keep in mind that this will work only with an authenticated user.
If your database table structure is like this
Patients
--------
id //Unique ID of Patient
user_id //User that created
patient
Then you can do the check in controller like.
public function viewPatient($patient)
{
$patient_check = Patient::where('id', $patient)->where('user_id','=',Auth::user()->id)->first();
if($patient_check == null || count($patient_check) == 0)
{
return "You cannot view this patient";
}
else
{
return view ('portal.patient',compact('patient'));
}
}
This is simple and yet does the work.

Laravel How to store extra data/value in session Laravel

I'm using default auth() in laravel login (email & password)
Now i try to take input from the user in text field like (Age or City)
Now i want to store (Age/City) in my session.
Help me
You can use session() helper:
session('age', 18); // saves age into session
$age = session('age')`; // gets age from session
Update
If you want to save Age and City after user registration, you should store this data in a DB, not in a session. You can add some fileds in create method of app\Http\Controllers\Auth\AuthController.php
You can use
Session::put('key', 'value');
To get key from Session use
Session::get('key');
You can use the session() helper function as #Alexey Mezenin answer.
Laravel Session Documentation
Ok let me enlighten you. if you want to store it in session do it this way.
session('country', $user->country); // save
$country = session('country')`; // retrieve
But that is not the way we do in Laravel like frameworks, it uses models
once the user is authenticated each time when we refresh the page, application looks for the database users table whether the user exists in the table. the authenticated user model is a user model too. so through it we can extract any column. first thing is add extra fields to the User class(Model) $fillable array.
so it would look something like this.
User.php
protected $fillable = ['username', 'password', 'remember_token', 'country'];
so after simply logging in with user name and password in anywhere just use Request class or Auth facade. Facades are not too recommended so here for your good as a new one i would just say how to use Request. Suppose you want to retrieve your Authenticated user country inside TestController.php here is how it could be used in the methods.
TestController.php
use Illuminate\Http\Request;
public function testMethod(Request $request)
{
$someCountry = $request->user()->country; //gets the logged in user country
dd($someCountry); //dd is die and dump, could be used for debugging purposes like var_dump() method
}
Using Request
public function ControllerName (Request $request){
$request->session()->put('session_age', $age);
}
Get session_age
$get_session_age = $request->session()->get('session_age');
Using Session
public function ControllerName (){
Session::put('age',$age);
}
Get the session
$session_age = Session::get('age');
Don't forget to define Session or Request in your controller!!!
use App\Http\Requests;
use Session;
To work with session in your controller you need to include session first in your controller
use Session;
After that for store data in session. There is several ways to do it. I prefer this one (in controller)
session()->put('key',$value);
To display session data in your View you can do it like this
#if(Session::has('key'))
I'v got session data
#else
I don't have session data
#endif
To get session data in your Controller you can do it like this
session()->get('key')
//or
session()->get('key','defaul_value_if_session_dont_exist')
When you are done with your data in session you can delete it like this (in controller)
session()->forget('key');
All this basic usage of session is well documented in official Laravel documentation here.
Hope it helps you

Resources