I’m trying to implement a password reset functionality in my Laravel application without requiring the email address, using only the reset token. I encountered an issue because the Password::tokenExists method requires both the token and user data, but there’s no straightforward way to get user data with only the token.
Here’s my current approach:
Store the reset token in the remember_token column of the users table.
Retrieve the user based on the remember_token.
Validate the token.
Reset the password if the token is valid.
Here’s my implementation:
public function resetPassword(Request $request) {
try {
$request->validate([
'token' => 'required|string',
'password' => 'required|string|min:8'
]);
$user = User::where('remember_token', $request->token)->first();
// Validate the token
if (!$user || !Password::tokenExists($user, $request->token)) {
return response()->json([
'status' => false,
'message' => 'Invalid or expired token.',
], 400);
}
// Reset the password
$user->password = Hash::make($request->password);
$user->remember_token = null;
$user->save();
// Remove the reset token after successful password reset
Password::deleteToken($user);
return response()->json([
'status' => true,
'message' => 'Password has been reset successfully.',
]);
} catch (ValidationException $e) {
return response()->json([
'status' => false,
'message' => $e->getMessage(),
'errors' => $e->errors(),
], 422);
} catch (Exception $e) {
return response()->json([
'status' => false,
'message' => $e->getMessage(),
], $e->getCode() ?: 500);
}
}
My questions are:
- Is storing the reset token in the remember_token column and retrieving the user based on this token a good approach?
- Are there any better or more secure methods to achieve password reset functionality without requiring the email address?
Any suggestions or improvements would be greatly appreciated!