skip to Main Content

I created a URL to edit logged in user data here is my route:

Route::get('/admin/create/user', [UserController::class, 'createUser'])->name('create.user');
Route::post('/admin/store/user', [UserController::class, 'storeUser'])->name('store.user');
Route::get('/admin/edit/user/{user_id}', [UserController::class, 'editUser'])->name('edit.user');

When a user clicks the edit button they get this URL.

http://127.0.0.1:8000/admin/edit/user/160

If that user put 162 they can see another user’s data!
How can I encrypt the user id, so that no one can see other user’s data?

Here is my Controller’s code:

namespace AppHttpControllersAdmin;

use AppHttpControllersController;
use AppMailUserActivatedEmail;
use AppMailUserBlockedEmail;
use IlluminateHttpRequest;
use AppModelsRole;
use AppModelsUser;
use AppModelsDivision;
use AppModelsDistrict;
use AppModelsBloodGroup;
use AppModelsSscBoard;
use AppModelsOccupation;
use IlluminateSupportCarbon;
use IlluminateSupportFacadesAuth;
use IlluminateSupportFacadesDB;
use IlluminateSupportFacadesHash;
use IlluminateSupportFacadesMail;
use InterventionImageFacadesImage;
use XenonLaravelBDSmsFacadesSMS;
use XenonLaravelBDSmsProviderAjuraTech;
use XenonLaravelBDSmsSender;


class UserController extends Controller
{

    public function storeUser(Request $request) {
        $request->validate([
            'role_id' => 'required',
            'name' => 'required',
            'email' => 'required', 'string', 'email', 'max:255', 'unique:users',
        ]);

        $image = $request->file('profile_photo');

        if ($image) {
            $name_gen = uniqid() . '.' . $image->getClientOriginalExtension();
            Image::make($image)->save('backend/images/users/'.$name_gen);
            $save_url = 'backend/images/users/' . $name_gen;

            User::insert([
                'role_id' => $request->role_id,
                'name' => $request->name,
                'email' => $request->email,
                'phone' => $request->phone,
                'gender' => $request->gender,
                'occupation' => $request->occupation,
                'blood_group_id' => $request->blood_group_id,
                'ssc_year' => $request->ssc_year,
                'ssc_board_id' => $request->ssc_board_id,
                'ssc_role' => $request->ssc_role,
                'ssc_registration_no' => $request->ssc_registration_no,
                'present_division_id' => $request->present_division_id,
                'present_district_id' => $request->present_district_id,
                'present_address' => $request->present_address,
                'permanent_division_id' => $request->permanent_division_id,
                'permanent_district_id' => $request->permanent_district_id,
                'permanent_address' => $request->permanent_address,
                'description' => $request->description,
                'facebok' => $request->facebok,
                'password' => Hash::make($request->password),
                'profile_photo' => $save_url,
                'created_at' => Carbon::now(),
            ]);
        } else {
            User::insert([
                'role_id' => $request->role_id,
                'name' => $request->name,
                'email' => $request->email,
                'phone' => $request->phone,
                'gender' => $request->gender,
                'occupation' => $request->occupation,
                'blood_group_id' => $request->blood_group_id,
                'ssc_year' => $request->ssc_year,
                'ssc_board_id' => $request->ssc_board_id,
                'ssc_role' => $request->ssc_role,
                'ssc_registration_no' => $request->ssc_registration_no,
                'present_division_id' => $request->present_division_id,
                'present_district_id' => $request->present_district_id,
                'present_address' => $request->present_address,
                'permanent_division_id' => $request->permanent_division_id,
                'permanent_district_id' => $request->permanent_district_id,
                'permanent_address' => $request->permanent_address,
                'description' => $request->description,
                'facebok' => $request->facebok,
                'password' => Hash::make($request->password),
                'created_at' => Carbon::now(),
            ]);
        }

        $notification = [
            'message' => 'User Created Successfully',
            'alert-type' => 'success'
        ];

        return redirect()->route('all.users')->with($notification);
    }

    public function editUser($user_id) {
        $roles = Role::all();
        $alldivisions = Division::get();
        $alldistricts = District::get();
        $allpdivisions = Division::get();
        $allpdistricts = District::get();
        $bgroups = BloodGroup::get();
        $sscboards = SscBoard::get();
        $ocupations = Occupation::get();
        $editUser = User::findOrFail($user_id);

        return view('admin.users.edit', compact('roles','editUser', 'ocupations', 'alldivisions', 'alldistricts', 'allpdivisions', 'allpdistricts', 'bgroups', 'sscboards'));
    }

    public function updateUser(Request $request) {
        $user_id = $request->id;

        $image = $request->file('profile_photo');
        $oldimage = $request->oldimage;

        $userToEdit = User::findOrFail($user_id);

        

        if($image){
            $name_gen=uniqid().'.'.$image->getClientOriginalExtension();
            Image::make($image)->save('backend/images/users/'.$name_gen);
            $save_url = 'backend/images/users/'.$name_gen;
            if($oldimage){
                unlink($oldimage);
            }

            $user = User::findOrFail($user_id);
            $user->role_id = $request->role_id;
            $user->name = $request->name;
            $user->email = $request->email;
            $user->phone = $request->phone;
            $user->gender = $request->gender;
            $user->occupation = $request->occupation;
            $user->blood_group_id = $request->blood_group_id;
            $user->ssc_year= $request->ssc_year;
            $user->ssc_board_id= $request->ssc_board_id;
            $user->ssc_role= $request->ssc_role;
            $user->ssc_registration_no= $request->ssc_registration_no;
            $user->present_division_id = $request->present_division_id;
            $user->present_district_id = $request->present_district_id;
            $user->present_address = $request->present_address;
            $user->permanent_division_id = $request->permanent_division_id;
            $user->permanent_district_id = $request->permanent_district_id;
            $user->permanent_address = $request->permanent_address;
            $user->description = $request->description;
            $user->facebok = $request->facebok;

            $user->profile_photo = $save_url;


            //$user->save();
            $this->authorize('save', $userToEdit);

        }else{
            $user = User::findOrFail($user_id);
            $user->role_id = $request->role_id;
            $user->name = $request->name;
            $user->email = $request->email;
            $user->phone = $request->phone;
            $user->gender = $request->gender;
            $user->occupation = $request->occupation;
            $user->blood_group_id = $request->blood_group_id;
            $user->ssc_year= $request->ssc_year;
            $user->ssc_board_id= $request->ssc_board_id;
            $user->ssc_role= $request->ssc_role;
            $user->ssc_registration_no= $request->ssc_registration_no;
            $user->present_division_id = $request->present_division_id;
            $user->present_district_id = $request->present_district_id;
            $user->present_address = $request->present_address;
            $user->permanent_division_id = $request->permanent_division_id;
            $user->permanent_district_id = $request->permanent_district_id;
            $user->permanent_address = $request->permanent_address;
            $user->description = $request->description;
            $user->facebok = $request->facebok;
            $user->profile_photo =$oldimage;

            //$user->save();

            $this->authorize('save', $userToEdit);

        }
        $notification = [
            'message' => 'User Updated Successfully',
            'alert-type' => 'success'
        ];

        return redirect()->back()->with($notification);
    }
}

3

Answers


  1. Instead of Encryption, You should restrict the data accessibility. Meaning, You only have to allow User A to access his/her data. If the user tries to access someone else’s data, You should restrict the access.

    Create a Middleware to cross-check current user

    class CurrentUserOnly
    {
        public function handle(Request $request, Closure $next): Response
        {
            $currentUserId = Auth::user()->getId();
            $requestedUserId = $request->get("user_id");
    
            // Check the requestedUserId is identical to current user's Id
            if ($currentUserId !== $requestedUserId){
               // Access denied, Handle error
            }
     
            return $next($request);
        }
    }
    

    Add the Middleware to Routes

    Route::get('/admin/edit/user/{user_id}', [UserController::class, 'editUser'])
         ->middleware(CurrentUserOnly::class);
         ->name('edit.user');
    

    Add your Auth middleware before CurrentUserOnly middleware to avoid getting Auth::user() as NULL in unauthenticated situations.

    Login or Signup to reply.
  2. While I suggest reading into authorization, and Laravel Gates/Policies, for a simple a quick solution you can use the abort function. This function will throw an exception that will stop the request from proceeding further.

    public function updateUser(Request $request) {
      abort_if(auth()->id() != $request->route('user_id'), 401);
      
      ...
    }
    
    Login or Signup to reply.
  3. You don’t need to pass the user ID to URL , Just do it like this:

    public function editUser() {
        $roles = Role::all();
        $alldivisions = Division::get();
        $alldistricts = District::get();
        $allpdivisions = Division::get();
        $allpdistricts = District::get();
        $bgroups = BloodGroup::get();
        $sscboards = SscBoard::get();
        $ocupations = Occupation::get();
        $editUser = User::findOrFail(Auth()->user()->id);
    
        return view('admin.users.edit', compact('roles','editUser', 'ocupations', 'alldivisions', 'alldistricts', 'allpdivisions', 'allpdistricts', 'bgroups', 'sscboards'));
    }
    

    and for route :

    http://127.0.0.1:8000/admin/edit/user
    

    And if you want to edit other user by your self or any other account you should manage the routes and access level in your project by using Middleware or some packages like Spatie.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search