PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, November 15, 2022

[FIXED] How to restrict a user to only see their own profile

 November 15, 2022     laravel, laravel-6, php     No comments   

Issue

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

    }
}

Solution

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.



Answered By - Kenny Horna
Answer Checked By - David Goodson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing