I have an admin panel and I am currently working on the change password module. I have done the code for change password but for some reason the session is destroyed and user is logged out after changing the password. How to prevent the auto logout from happening. Please help me.
HTML
<form id="changepasswordform">
<input type="hidden" name='_token' value="{{ csrf_token() }}">
<div class="form-group">
<div class="row">
<div class="col-md-2">
<label>Password</label>
</div>
<div class="col-md-10">
<div class="custom_error_msg password_error"></div>
<input type="password" name="password" class="form-control password">
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-2">
<label>Confirm Password</label>
</div>
<div class="col-md-10">
<div class="custom_error_msg confirm_password_error"></div>
<input type="password" name="confirm_password" class="form-control confirm_password">
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-12">
<button class="btn btn-success float-right"><i class="far fa-save"></i> Save</button>
</div>
</div>
</div>
</form>
Controller
public function ChangePasswordProcess(Request $request){
/*User::find(auth()->user()->id)
->update([
'password'=> Hash::make($request->password)
]);*/
$userId = Auth::User()->id;
$user = User::find($userId);
$user->password = Hash::make($request->password);
$user->save();
return response()->json(['status' => 'success']);
}
Javascript
<script>
$(document).ready(function(){
$(".dropify").dropify();
$("#changepasswordform").submit(function(e){
e.preventDefault();
var status=false;
if($(".password").val()==""){
$(".password_error").html("Field is mandatory");
$(".password_error").show();
status=false;
} else {
$(".password_error").hide();
status=true;
}
if($(".confirm_password").val()==""){
$(".confirm_password_error").html("Field is mandatory");
$(".confirm_password_error").show();
status=false;
} else {
$(".confirm_password_error").hide();
status=true;
}
if($(".password").val()!=="" && $(".confirm_password").val()!==""){
if($(".password").val() !== $(".confirm_password").val()){
$(".confirm_password_error").html("Passwords don't match");
$(".confirm_password_error").show();
status=false;
} else {
$(".confirm_password_error").hide();
status=true;
}
}
if(status==true){
var formdata = new FormData(document.getElementById('changepasswordform'));
$.ajax({
url: "{{ route('admin.change_password_process') }}",
type: "post",
async: false,
cache: false,
contentType: false,
processData: false,
data: formdata,
success: function (res) {
if (res.status == 'success') {
Swal.fire({
icon: 'success',
title: 'Success',
text: 'Password updated successfully',
confirmButtonClass: 'btn btn-primary',
buttonsStyling: false,
}).then(function (result) {
window.location.reload();
});
}
}
});
}
});
});
</script>
On the method ChangePasswordProcess in the controller, you have to re-authenticate the user which his password changed
public function ChangePasswordProcess(Request $request){
/*User::find(auth()->user()->id)
->update([
'password'=> Hash::make($request->password)
]);*/
$userId = Auth::User()->id;
$user = User::find($userId);
$user->password = Hash::make($request->password);
$user->save();
Auth::login($user);
return response()->json(['status' => 'success']);
}
When the password_hash of the session is different from the current auth()->user() the laravel will automatically logout the user. This is done on this middleware:
vendor/laravel/framework/src/Illuminate/Session/Middleware/AuthenticateSession.php
If you update the password_hash on the session with the new hash password the user will be not logout.
session()->put([
'password_hash_' . auth()->getDefaultDriver() => $user->getAuthPassword()
]);
Example:
session()->put([
'password_hash_web' => "$2y$10$...hashpasswordstoredondatabase"
]);
Related
I m trying to login this from with ajax but ajax dont work :( can you help me
My Controller
public function login(Request $request)
{
$validator = Validator::make($request->all(), [
'password' => 'required',
'email' => 'required|email',
]);
if ($validator->passes()) {
if (auth()->attempt(array('email' => $request->input('email'),
'password' => $request->input('password')),true))
{
return response()->json(["status" => true]);
}
return response()->json(['error'=>false]);
}
return response()->json(['error'=>$validator->errors()]);
}
my View
<div id="giris-yap" class="ekran" x-show="tab === 'giris-yap'">
<form action="javascript:void(0)" id="loginform" action="{{ route('giris') }}" method="post">
#csrf
<div class="form-group">
<input type="email" name="email" id="email" placeholder="E-Posta"
#error('email') style="border-color:red" #enderror>
<label class="lab" for="email">E-Posta</label>
<small style="color: red;" id="email" class="text-danger error-text email_err hata"></small>
</div>
<div class="password-input form-group">
<input type="password" name="password" id="password" placeholder="Şifre"
#error('password') style="border-color:red" #enderror>
<label class="lab" for="password">Şifre</label>
<span toggle="#password" class="fa fa-fw fa-eye field-icon toggle-password"></span>
<small style="color: red;" id="password" class="text-danger error-text password_err hata"></small>
</div>
<div class="remember col-2 gap-10">
<div class="form-check">
<label><input type="checkbox" name="remember"> Beni Hatırla</label>
</div>
<span class="password-request">
Şifremi Unuttum
</span>
</div>
<small id="mydiv" style="color: red; margin-top: 5px; margin-bottom: 10px; display: none " class="text-danger password_err">Lütfen Eposta ve Şifrenizi Kontrol edin.</small>
<button type="submit" class="btn loginBtn">Giriş Yap</button>
</form>
my ajax
<script>
//login ajax
$(document).ready(function() {
$("#loginform").submit(function(e){
e.preventDefault();
var email = $("#email").val();
var password = $("#password").val();
$.ajax({
url: "{{ route('giris') }}",
type:'POST',
data:{'_token' : '{{ csrf_token() }}', email:email, password:password},
success: function(data) {
printMsg(data)
if(data.status === true)
{
console.log(data.status)
window.location.href = '/';
}
if(data.error === true){
console.log(data.error)
$('#mydiv').show()
}
},
});
});
function printMsg (msg) {
if($.isEmptyObject(msg.error)){
}else{
$.each( msg.error, function( key, value ) {
$('.'+key+'_err').text(value);
});
}
}
});
</script>
do not pass route just pass in form open tag #csrf and on button Sign In and then
in js script like this. function login(){ $.ajaxSetup({
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}});
$.ajax({ type : 'POST', url: '{{route('login.check')}}', data : data,success : function(response) {console.log(response); if(response == 1) {
window.location.replace('{{route('test.index')}}'); }else if(response == 3)
{ $("#err").hide().html("Username or Password Incorrect. PleaseCheck").fadeIn('slow'); } } });}
I wrote a small script that updates the information on the page when editing. Everything basically works as it should, but I just can’t update the image. I don’t understand what the matter is. Without a script, with a page reload, everything works as it should.
Ajax script
<script type="text/javascript">
$("document").ready(function() {
$("#editPostButton{{$post->id}}").click(function() {
var formData = $("#EditPostForm{{$post->id}}").serialize();
$.ajax({
url: "{{route('editPost', ['id' => $user->id, 'postId' => $post->id])}}",
type: "POST",
data: formData,
success: function(data) {
$("#textpostdata{{$post->id}}").html($(data).find("#textpostdata{{$post->id}}").html());
$("#closeButton{{$post->id}}").click();
}
});
});
});
</script>
My Controller
public function editPost(Request $request, $id, $postId) {
$validator = $this->validate($request,[
'title' => 'max:100',
'message' => 'max:5000',
'img' => 'mimes:jpeg,png,gif,jpg|max:5000',
'videoPost' => 'max:100'
]);
if($validator) {
$user = User::find($id);
if(!$user && $user != Auth::user()->id) {
return abort(404);
}
$post = Profile::find($postId);
if(!$post) {
return abort(404);
}
$post->user_id = Auth::user()->id;
$post->title = $request->title;
$post->message = $request->message;
$post->videoPost = str_replace('watch?v=', 'embed/', $request->videoPost);
if($request->file('img')) {
$path = Storage::putFile('public/'.Auth::user()->id.'/post', $request->file('img'));
$url = Storage::url($path);
$post->img = $url;
}
$post->update();
return redirect()->back();
}
}
And update form
<form action="{{route('editPost', ['id' => $user->id, 'postId' => $post->id])}}" method="post" enctype="multipart/form-data" id="EditPostForm{{$post->id}}" name="postForm">
#csrf #method('PATCH')
<div class="form-group">
<textarea maxlength="100" name="title" class="form-control" rows="1">{{$post->title}}</textarea>
</div>
<div class="form-group">
<textarea id="message" maxlength="5000" name="message" class="form-control" rows="10">{{$post->message}}</textarea>
</div>
<div class="form-group">
<textarea maxlength="100" class="form-control mt-1" id="videoPost" name="videoPost" cols="100" rows="1">{{$post->videoPost}}</textarea>
</div>
<h6>Current image</h6>
<img src="{{$post->img}}" class="img-fluid mb-2" width="230">
<div class="form-group">
<input type="file" id="img" name="img" accept="image/*">
</div>
<button type="button" class="btn btn-sm btn-primary" id="editPostButton{{$post->id}}">Edit</button>
</form>
In the step 2 of a multi step form, if a radio button is selected and "go to step 3" is clicked or if no radio button is selected and "go to step 3" is clicked it appears always this error below:
{message: "", exception: "Symfony\Component\HttpKernel\Exception\HttpException",…}
exception"Symfony\Component\HttpKernel\Exception\HttpException"
file "/Users/johnw/projects/store/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php" line : 203 message: "" trace:[{,…},…]
Do you know where can be the issue?
Html for the step 2:
<form method="post" id="step2form" action="">
<h6>Payment method</h6>
<div class="form-group">
<div class="form-check">
<input class="form-check-input" type="radio" name="payment_method" value="option1">
<label class="form-check-label d-flex align-items-center" for="exampleRadios1">
<span class="mr-auto">Payment method 1</span>
</label>
</div>
<br>
<div class="form-check">
<input class="form-check-input" type="radio" name="payment_method" value="option1">
<label class="form-check-label d-flex align-items-center" for="exampleRadios1">
<span class="mr-auto">Payment method 2</span>
</label>
</div>
</div>
<br>
<div class="text-right">
<button type="button" href="#step3" data-toggle="tab" role="tab"
class="btn btn-outline-primary prev-step">
Go back to step 2
</button>
<input type="submit" href="#step2" id="goToStep3"
class="btn btn-primary btn float-right next-step"
value="Go to step 3"/>
</div>
</form>
PaymentController method to handle ajax request for step 2:
public function storePaymentMethods(Request $request, $id, $slug = null, Validator $validator){
$validator = Validator::make($request->all(),[
'payment_method' => 'required',
]);
if($validator->passes())
{
return response()->json([
'success' => true,
'message' => 'success'
], 200);
}
$errors = $validator->errors();
$errors = json_decode($errors);
return response()->json([
'success' => false,
'errors' => $errors
], 422);
}
ajax:
$('#goToStep3').on('click', function (event) {
event.preventDefault();
var custom_form = $("#" + page_form_id);
$.ajax({
method: "POST",
url: '{{ route('products.storePaymentMethods', compact('id','slug') ) }}',
data: custom_form.serialize(),
datatype: 'json',
success: function (data, textStatus, jqXHR) {
},
error: function (data) {
var errors = data.responseJSON;
var errorsHtml = '';
$.each(errors['errors'], function (index, value) {
errorsHtml += '<ul class="alert alert-danger mt-3"><li class="text-danger">' + value + '</li></ul>';
console.log(errorsHtml);
});
$('#response').show().html(errorsHtml);
}
});
you have not added any csrf token with your form. There are several ways to do it like below mentioned ways -
Add {{ csrf_field() }} inside your form
or add token with your ajax request like _token:"{{ csrf_token() }}"
I'm trying to create a multi-step form using jQuery anad AJAX. But Im getting this error when "go to step 2" is clicked:
jquery.min.js:4 POST http://store.test/product/1/product-test/payment/storeUserInfo 500 (Internal Server Error)
Also when clicking in network tab and then click in "storeUserInfo" it appears:
exception
:
"Illuminate\Contracts\Container\BindingResolutionException"
file
:
"/Users/jakeB/projects/store/vendor/laravel/framework/src/Illuminate/Container/Container.php"
line
:
933
message
:
"Unresolvable dependency resolving [Parameter #1 [ <required> array $data ]] in class Illuminate\Validation\Validator"
Do you know where is the error?
In the PaymentController there is the storeUserInfo() Method that is the method for the step 1:
public function storeUserInfo(Request $request, $id, $slug = null, Validator $validator){
$validator = Validator::make($request->all(),[
'buyer_name' => 'required|max:255|string',
'buyer_surname' => 'required|max:255|string',
'buyer_email' => 'required|max:255|string',
'name_invoice' => 'required|max:255|string',
'country_invoice' => 'required|max:255|string',
]);
if ($validator->fails()) {
if($request->ajax())
{
return response('test');
}
$this->throwValidationException(
$request, $validator
);
}
}
Route:
Route::post('/product/{id}/{slug?}/payment/storeUserInfo', [
'uses' => 'PaymentController#storeUserInfo',
'as' =>'products.storeUserInfo'
]);
// step 1 and step 2 html
<div class="tab-pane fade show active clearfix" id="step1" role="tabpanel" aria-labelledby="home-tab">
<h6>User Info</h6>
<form method="post" id="step1form" action="">
{{csrf_field()}}
<div class="form-group font-size-sm">
<label for="name" class="text-gray">Name</label>
<input name="name" type="text" required class="form-control" value="{{ (\Auth::check()) ? Auth::user()->name : old('name')}}">
</div>
<!-- other form fields -->
<input type="submit" id="goToStep2" href="#step2"
class="btn btn-primary btn float-right next-step" value="Go to step 2"/>
</form>
</div>
<div class="tab-pane fade clearfix tabs hide" id="step2" role="tabpanel" aria-labelledby="profile-tab">
<form method="post">
<h6>Payment method</h6>
<div class="form-group">
<div class="form-check">
<input class="form-check-input" type="radio" name="paymentmethod1" value="option1" checked>
<label class="form-check-label d-flex align-items-center" for="exampleRadios1">
<span class="mr-auto">payment method 1</span>
</label>
</div>
<br>
<div class="form-check">
<input class="form-check-input" type="radio" name="credit_card" value="option1">
<label class="form-check-label d-flex align-items-center" for="exampleRadios1">
<span class="mr-auto">Stripe</span>
</label>
</div>
</div>
<div class="text-right">
<button type="button" href="#step3" data-toggle="tab" role="tab"
class="btn btn-outline-primary prev-step">
Go back to step 2
</button>
<button type="button" data-nexttab="#step3" href="#step3"
class="btn btn-primary btn ml-2 next-step">
Go to step 3
</button>
</div>
</form>
</div>
// ajax in payment.blade.php
$('#goToStep2').on('click', function (event) {
event.preventDefault();
var custom_form = $("#" + page_form_id);
$.ajax({
method: "POST",
url: '{{ route('products.storeUserInfo',compact('id','slug') ) }}',
data: custom_form.serialize(),
datatype: 'json',
success: function (data, textStatus, jqXHR) {
setTimeout(function () {
}, 3000);
},
error: function (data) {
console.log(data);
var errors = data.responseJSON;
var errorsHtml = '';
$.each(errors['errors'], function (index, value) {
errorsHtml += '<ul class="list-group"><li class="list-group-item alert alert-danger">' + value + '</li></ul>';
});
$('#response').show().html(errorsHtml);
}
});
});
});
Use Validator facade class in your PaymentController
use Validator;
class PaymentController extends Controller
{
public function storeUserInfo(Request $request, $id, $slug = null){
$validator = Validator::make($request->all(),[
'buyer_name' => 'required|max:255|string',
'buyer_surname' => 'required|max:255|string',
'buyer_email' => 'required|max:255|string',
'name_invoice' => 'required|max:255|string',
'country_invoice' => 'required|max:255|string',
]);
if ($validator->fails()) {
if($request->ajax())
{
return response('test');
}
$this->throwValidationException(
$request, $validator
);
}
}
}
i want to create form submit by using ajax jquery,but everytime i press submit, the form is always executed directly to controller without passing ajax call.
is there anything wrong with my code?
controller:
public function simpanSaran(){
$this->form_validation->set_rules('nama', 'Nama', 'required');
$this->form_validation->set_rules('email', 'Email', 'required');
$this->form_validation->set_rules('sub', 'Subjek', 'required');
$this->form_validation->set_rules('isi', 'Isi', 'required');
if ($this->form_validation->run() == FALSE) {
$this->content("user/hal_saran");
}
else {
$insert = array(
'nama' => $this->input->post('nama'),
'email' => $this->input->post('email'),
'subjek' => $this->input->post('sub'),
'komentar' => $this->input->post('isi'),
);
$this->db->insert('guest',$insert);
}
}
my view,with ajax jquery:
<script>
$(document).ready(function() {
$('#myForm').submit(function() {
e.preventDefault();
$.ajax({
type: 'POST',
url: $(this).attr('action'),
data: $(this).serialize(),
success: function() {
$('#result').slideDown();
}
}
})
return false;
});
$('.close').click(function(){
$('#result').slideUp();
});
});
</script>
<div class=" span9">
<div class="span9" id="result" style="display:none;height:80px;">
<div class="notices" >
<div class="bg-color-green" style="height:60px;">
<div class="notice-header fg-color-white">Terima Kasih!</div>
<div class="notice-text">Anda telah Memberikan Kritik dan Saran pada Kami.</div>
</div>
</div>
</div>
<div id="hid" style="display:none;"></div>
<?php
$attr = array('id' => 'myForm');
echo (form_open('lowongan/simpanSaran',$attr)) ?>
<div class="input-control text span3" style="height:40px;">
<input type="text" placeholder="Nama" name="nama" required/>
<button class="btn-clear"></button>
</div>
<div class="input-control text span3" style="height:40px;">
<input type="text" placeholder="Email" name="email" required/>
<button class="btn-clear"></button>
</div>
<div class="input-control text span3" style="height:40px;">
<input type="text" placeholder="Subjek" name="sub" required/>
<button class="btn-clear"></button>
</div>
<div class="input-control textarea span9" >
<textarea placeholder="Komentar" name="isi" style="height:200px;" required></textarea>
<button type="submit" class="fg-color-white bg-color-purple" style="margin-top:20px;"><i class="icon-comments-5"></i> Kirim</button>
<p>*Saran atau kritik akan di-reply melalui email</p>
</div>
<?php echo(form_close())?>
</div>
Just a small change :
$('#myForm').submit(function(e) {
e.preventDefault();