Reputation: 369
I have a problem. I need to prevent a logged in user can edit / view etc. information of another user changing the id in the url.
For example:
The URL is something like myapp/users/32/edit, but to change the id, can edit the information of other users
I tried to create a middleware, but not achieve expected results. I created the following:
L
<?php
namespace App\Http\Middleware;
use Closure;
use Auth;
class UserSecutiry
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if ($request->user()->id == Auth::id()) {
return $next($request);
}
return redirect()->to('/');
}
}
But $request->user->id returns me logged user id, so the middleware does not work and can manipulate any user information changing the id.
How I can accomplish this task. I hope your help. Greetings from Chile
Upvotes: 0
Views: 1360
Reputation: 10912
Here we go:
$request->route()->id
Your route should look like this:
Route::get('/test/{id}', [
'middleware' => \Upping\Http\Middleware\ExtendSessionMiddleware::class,
function ($id) {
dd('some');
}
]);
Doesn't work for global middleware.
Upvotes: 1
Reputation: 14747
If $request->user()->id
returns the user's ID specified via URL then your code should work.
URL id | Auth::id() | Condition
-------------------------------
1 | 3 | false
2 | 3 | false
3 | 3 | true
4 | 3 | false
If $request->user->id
returns the logged user. Then do something like this:
public function handle($request, Closure $next)
{
// find the user who will be edited
$id = $request->route('id');
$userToEdit = \User::find($id);
if ($userToEdit->getId() === Auth::id()) {
return $next($request);
}
return redirect()->to('/');
}
I assumed that your route has a placeholder for the user id,:
Route::get('users/{id}/edit');
Upvotes: 0