Home > front end >  How can I block a Controller function from being used if ids do not match?
How can I block a Controller function from being used if ids do not match?

Time:03-06

I have two tables in my database: 'users' and 'bookings'. In the bookings table, a column exists that contains the id (foreign key) of the user that created the booking. My goal is to be able to cross-check this id (in the bookings table) with that of the id of the person who is logged in. (Perhaps using Auth::user();, please confirm) Essentially only allowing them to update bookings that they have created, but not bookings belonging to other users. (So a one to many relationship).
Is there any way to encapsulate the function in the Controller I am using with a check to verify the id? Here is my eventController.php:

    public function store(Request $request)
    {
        $booking = Booking::create([
            'title' => $request->title,
            'resourceId' => $request->resourceIds,
            'created_by' => $request->createdby,
            'start_date' => $request->start,
            'end_date' => $request->end,
        ]);
        return response()->json($booking);
    }

The reason why I am trying to figure out a method to encapsulate this is that I would prefer not to compare values in public JS, where security issues are posed.

CodePudding user response:

Yes, you can confirm, for example:

if(Auth::id() == $booking->user_id){
 return true;
}

CodePudding user response:

I will assume that you are using Passport for authentication and your api.php routes since you are consuming your endpoint from JS. IMO, the best choices here are:

  1. Route model binding.

You can restrict the method by checking the model bound to the route only for the creator (explicit binding). If binding fails, a 404 will be thrown unless you customize your missing model behavior.

api.php

Route::patch('/bookings/{booking:id}', [BookingController::class, 'update']);

RouteServiceProvider.php (boot() method)

$this->bind('booking', function ($value) {
     return Booking::where('created_by', auth('api')->user()->id)->findOrFail($value);
});
  1. Within your controller by throwing an exception
public function update(Request $request, $id)
{
   $booking = Booking::where('created_by', auth('api')->user()->id)->findOrFail($id);
   ...
}

Or in case you are using implicit binding model in your route

public function update(Request $request, $booking )
{
   if ($booking->created_by != auth('api')->user()->id) {
      abort(404, "You don't own this booking!");
   }
   ...
}
  • Related