Reputation: 25
I have a view (resources/view/front/auth/profile.blade.php
) and my route in file web.php is:
Route::get('/profile/{user}','UserController@edit')
->name('profile')
->middleware('profilecheck');
My problem is that when a user logs in and gets redirected to their own profile page (http://exmaple.com/profile/2
), he/she can change the URL to http://exmaple.com/profile/3
and see other users' profile.
I want to use a middleware to check authenticated users id with URL parameter {user}
. The $user->id
will passed to the {user}
, but I have no idea how.
Middleware UserProfile.php
:
<?php
namespace App\Http\Middleware;
use App\User;
use Closure;
class UserProfile
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
// $request->user()->id
// Auth::user()->id
return $next($request);
}
}
Upvotes: 1
Views: 2977
Reputation: 14271
You can protect the route simply by removing the user id from the URL, but getting it through the authentication session instead.
So, your route signature should goes from:
Route::get('/profile/{user}', 'UserController@edit')->name('profile');
To this:
Route::get('/profile', 'UserController@edit')->name('profile');
So, in your controller, instead of getting the user id from the request:
public function edit(Request $request)
{
$user = User::findOrFail($request->id);
// ...
}
You could get the logged-in User
through the Auth
facade:
use Illuminate\Support\Facades\Auth;
public function edit(Request $request)
{
$user = Auth::user();
// ...
}
or just the auth()
helper:
public function edit(Request $request)
{
$user = auth()->user();
// ...
}
This way, you are masking the URL to avoid a malicious user of doing things that he/she shouldn't.
Upvotes: 6
Reputation: 375
// Controller
public function index()
{
if (Auth::check() && Auth::user()->role->id == 2) {
return view('author.setting.settings');
} else {
Toastr::info('you are not authorized to access', 'Info');
return redirect()->route('login');
}
}
// Route
Route::group(['as'=>'user.','prefix'=>'user','namespace'=>'Author','middleware'=>['auth','user']], function (){
Route::get('/setting','SettingsController@index')->name('settings.settings');
});
Upvotes: 0
Reputation: 546
You need to do something like this.
Your route
Route::get('/profile', [
'uses' => 'UserController@profile',
'middleware' => 'profilecheck'
]);
Your middleware
class CheckUserMiddleware
{
public function handle($request, Closure $next)
{
if(!auth()->user()) {
return redirect()->route('login');
}
return $next($request);
}
}
Upvotes: 0