Skip to content
Advertisement

How to restrict a user to only see their own profile

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 AppHttpMiddleware;

use AppUser;
use Closure;

class UserProfile
{
    /**
     * Handle an incoming request.
     *
     * @param  IlluminateHttpRequest  $request
     * @param  Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        // $request->user()->id
        // Auth::user()->id

        return $next($request);

    }
}

Advertisement

Answer

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 IlluminateSupportFacadesAuth;

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.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement