i want to useAuth::logoutOtherDevices($currentPassword)
in laravel 8 to logout user from other devices after changing password. As per documentation ia have uncomment the line\Illuminate\Session\Middleware\AuthenticateSession::class,
. But unfortunately, it's not working. It saysMethod Illuminate\Auth\RequestGuard::viaRemember does not exist.
Can anyone please help me to sort it out how can i add logout from other devices functionality with the help ofAuth::logoutOtherDevices($currentPassword)
or any manual method ?
Here is my code:
$rules = [
'currentpass' => 'required',
'newpass' => 'required|min:6',
'confnewpass' => 'required|same:newpass|min:6'
];
$messages = [
'currentpass.required' => 'Please enter your current password.',
'newpass.required' => 'Please provide a new password.',
'newpass.min' => 'Password must contain minimum 6 characters.',
'confnewpass.required' => 'Please provide your new password again to confirm.',
'confnewpass.same' => 'Both new passwords must be same.',
'confnewpass.min' => 'Password must contain minimum 6 characters.'
];
$this->validate($request, $rules, $messages);
$currentPass = $request->input('currentpass');
$newPass = $request->input('newpass');
try {
$user = User::findOrFail(Auth::id());
} catch (ModelNotFoundException $ex) {
$response['error'] = true;
$response['errors']['notFound'] = ['User Not Found.'];
return response()
->json($response, 400, [], JSON_PRETTY_PRINT);
}
if (!Hash::check($currentPass, $user->password)) {
return Redirect::back()
->withErrors(['Current Password', 'Please provide your current password properly.']);
}
$isChar = preg_match('/[a-zA-Z]+/', $newPass);
$isNum = preg_match('/\d+/', $newPass);
if (!($isChar && $isNum)) {
$response['error'] = 'Password must contain minimum 6 characters with at-least one letter and one number.';
return response()
->json($response, 200, [], JSON_PRETTY_PRINT);
}
/** hash password */
$hashpass = Hash::make($newPass);
$user->password = $hashpass;
try {
$user->save();
} catch (QueryException $ex) {
return Redirect::back()
->withErrors(['query', $ex->getMessage()]);
}
Auth::logoutOtherDevices($currentPass);
return Redirect::back()
->with('success', 'Your password has been successfully updated.');
This is because Laravel Sanctum is using its own middleware, namelyLaravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful
. WhileAuth::logoutOtherDevices($currentPassword)
needs\Illuminate\Session\Middleware\AuthenticateSession
to work.
To work around this, you can extend\Illuminate\Session\Middleware\AuthenticateSession
to works withLaravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful
. Here's the steps:
Create a new fileAuthenticateApiSession.php
inapp/Http/Middleware
(or any other folder you like). TheAuthenticateApiSession.php
should looks like this:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Session\Middleware\AuthenticateSession;
class AuthenticateApiSession extends AuthenticateSession
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if (! $request->hasSession() || ! $request->user()) {
return $next($request);
}
// Remove or comment this code block, or you'll get error.
/*if ($this->auth->viaRemember()) {
$passwordHash = explode('|', $request->cookies->get($this->auth->getRecallerName()))[2] ?? null;
if (! $passwordHash || $passwordHash != $request->user()->getAuthPassword()) {
$this->logout($request);
}
}*/
if (! $request->session()->has('password_hash')) {
$this->storePasswordHashInSession($request);
}
if ($request->session()->get('password_hash') !== $request->user()->getAuthPassword()) {
$this->logout($request);
}
return tap($next($request), function () use ($request) {
$this->storePasswordHashInSession($request);
});
}
}
Add the newly createdApp\http\Middleware\AuthenticateApiSession
class toapi
middleware group inapp/Http/Kernel.php
. Beware that it must be inserted afterEnsureFrontendRequestsAreStateful
.
'api' => [
EnsureFrontendRequestsAreStateful::class,
\App\Http\Middleware\AuthenticateApiSession::class,
'throttle:240,1',
'auth:airlock',
'branch.default',
'bindings',
],
That's it, now every ajax request to guarded API endpoint from other device should returns401
response afterAuth::logoutOtherDevices($currentPassword)
is called.
You should set your SPA (You're using sanctum, so I assume you're building an SPA) to handle invalid session in the ajax request though. Maybe redirecting the user to login page using javascript when encountering401
ajax response.
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Find the answer in similar questions on our website.
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.
PHP (from the English Hypertext Preprocessor - hypertext preprocessor) is a scripting programming language for developing web applications. Supported by most hosting providers, it is one of the most popular tools for creating dynamic websites.
The PHP scripting language has gained wide popularity due to its processing speed, simplicity, cross-platform, functionality and distribution of source codes under its own license.
https://www.php.net/
Laravel is a free open source PHP framework that came out in 2011. Since then, it has been able to become the framework of choice for web developers. One of the main reasons for this is that Laravel makes it easier, faster, and safer to develop complex web applications than any other framework.
https://laravel.com/
JavaScript is a multi-paradigm language that supports event-driven, functional, and mandatory (including object-oriented and prototype-based) programming types. Originally JavaScript was only used on the client side. JavaScript is now still used as a server-side programming language. To summarize, we can say that JavaScript is the language of the Internet.
https://www.javascript.com/
Welcome to the Q&A site for web developers. Here you can ask a question about the problem you are facing and get answers from other experts. We have created a user-friendly interface so that you can quickly and free of charge ask a question about a web programming problem. We also invite other experts to join our community and help other members who ask questions. In addition, you can use our search for questions with a solution.
Ask about the real problem you are facing. Describe in detail what you are doing and what you want to achieve.
Our goal is to create a strong community in which everyone will support each other. If you find a question and know the answer to it, help others with your knowledge.