/** * Generate and save recover code for current user. * * @param int $userId * @param int $length * @return string */ public static function recoverCode($userId, $length = 200) { // Delete old codes RecoverCode::where('user_id', $userId)->delete(); // Generate new one $code = substr(str_shuffle('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'), 0, $length) . $userId; // Insert in database $recoverCode = new RecoverCode(); $recoverCode->user_id = $userId; $recoverCode->code = $code; $recoverCode->save(); return $code; }
/** * @param int $userId * @param string $code * @param SetNewPasswordRequest $request * @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response */ public function setNewPassword($userId, $code, SetNewPasswordRequest $request) { $response = new AjaxResponse(); $recover = RecoverCode::where('user_id', $userId)->where('code', $code)->valid()->first(); if (!$recover) { $response->setFailMessage(trans('common.general_error')); return response($response->get(), $response->badRequest()); } $user = User::find($userId); if (!$user) { // User not found $response->setFailMessage(trans('common.general_error')); return response($response->get(), $response->badRequest()); } User::where('id', $userId)->update(['password' => bcrypt($request->get('new_password'))]); $response->setSuccessMessage(trans('recover.password_updated')); return response($response->get()); }