Skip to content

Instantly share code, notes, and snippets.

@HichemTab-tech
Created August 4, 2023 21:06
Show Gist options
  • Save HichemTab-tech/edcabe7e9a95a3d88b14d4448c67ea98 to your computer and use it in GitHub Desktop.
Save HichemTab-tech/edcabe7e9a95a3d88b14d4448c67ea98 to your computer and use it in GitHub Desktop.
This middleware is used to verify the current password of the authenticated user before making an action you have to simply add a params to the reqyest named `currentPassword`.
<?php
namespace App\Http\Middleware;
use Closure;
use Exception;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\ValidationException;
class VerifyPassword
{
/**
* Handle an incoming request.
*
* @param Request $request
* @param Closure(Request): (Response|RedirectResponse) $next
* @return Response|RedirectResponse|JsonResponse
* @throws Exception
*/
public function handle(Request $request, Closure $next): Response|RedirectResponse|JsonResponse
{
$user = Auth::user();
if ($user == null) {
throw new Exception('User not found');
}
$password = $request->input('currentPassword', "");
// Perform password verification against the user's actual stored password
if (!Hash::check($password, $user->password)) {
throw ValidationException::withMessages([
'currentPassword' => ['The provided password does not match your current password.'],
]);
}
return $next($request);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment