laravel 5 ajax authentification - ajax

I need to create auth from any pages over ajax. If i'm send wrong login and empty pass(or vice versa) - will be return json errors (it's ok). If i'm send wrong login and wrong pass(or right login and path) - will be return redirect.
How to change backend for get response json anyway?
my frontend code js:
$("#authform").submit(function(e) {
e.preventDefault();
$.post($(this).attr("action"), $(this).serialize(), function(data) {
console.log(data);
}, "json");
});
html:
<form id="authform" method="POST" action="{{ url('/auth/login') }}">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="email" name="email" value="{{ old('email') }}">
<input type="password" name="password">
<input type="checkbox" name="remember">
<button type="submit">Login</button>
</form>
routes.php:
Route::post('auth/login', 'Auth\AuthController#postLogin');

This is not an answer. First try this then we should
$('#authform').on('submit',function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
cache: false,
dataType: 'JSON',
url: $(#authform).attr("action"),
data: $('#authform').serialize(),
success: function(data) {
console.log(data);
},
});
return false;
});
And have you tried this link How to create AJAX login with Laravel

I'm sure there is a better solution for this problem, but what I did was:
Create a new route for loging in
Route::post('/login', 'Auth\AuthController#signIn');
In App\Http\Controllers\Auth\AuthController I added two new methods:
public function signIn(Request $request) {
$this->validateLogin($request);
$throttles = $this->isUsingThrottlesLoginsTrait();
if ($throttles && $lockedOut = $this->hasTooManyLoginAttempts($request)) {
$this->fireLockoutEvent($request);
return $this->sendLockoutResponse($request);
}
$credentials = $this->getCredentials($request);
if (Auth::guard($this->getGuard())->attempt($credentials, $request->has('remember'))) {
return $this->handleUserWasAuthenticated($request, $throttles);
}
if ($throttles && ! $lockedOut) {
$this->incrementLoginAttempts($request);
}
return $this->sendFailedLoginResponseJSON($request);
}
AND
protected function sendFailedLoginResponseJSON(Request $request)
{
return response()->json(['username' => $this->getFailedLoginMessage()], 422);
}
It's basically the same as the login method from AuthenticatesAndRegistersUsers trait, except for the last line, the login method uses
protected function sendFailedLoginResponse(Request $request)
{
return redirect()->back()
->withInput($request->only($this->loginUsername(), 'remember'))
->withErrors([
$this->loginUsername() => $this->getFailedLoginMessage(),
]);
}
which sends back a redirect with the error.
If you want both ajax and non-ajax, you can do
if($request->ajax()){
return $this->sendFailedLoginResponseJSON($request);
}
return $this->sendFailedLoginResponse($request);
in the new sign in method.

Related

How to display data from controller to blade view and how to do routings from remote api? Laravel

WelcomeController
class WelcomeController extends Controller
{
public function ajaxRequestPost(Request $request){
$request->session()->put('data', $request->all());
return redirect('dashboard');
}
public function readSession(Request $request){
$email = $request->session()->get('data');
return $email;
}
}
Routes (Web.php)
return view('welcome');
});
Route::post('/', [App\Http\Controllers\WelcomeController::class, 'ajaxRequestPost'])->name('ajaxRequest.post');
Route::get('/dashboard/read', [App\Http\Controllers\WelcomeController::class]);
Route::post('/dashboard/read', [App\Http\Controllers\WelcomeController::class, 'readSession']);
Route::get('/dashboard', function () {
$email = session()->has('data');
if(!session()->has('data')){
return redirect('/');
}
return view('dashboard', ['name'=> $email]);
});
Route::get('/logout', function () {
session()->forget('data');
return redirect('/');
});
Welcome.blade For popuplogin from remote API
<div class="hidden fixed top-0 right-0 px-6 py-4 sm:block">
<!-- insert at the bottom part of body -->
<script src="provided.js"></script>
<!-- add button to show login window -->
<button id="btnShowLogin" type="button">Login</button>
<form id="login" action="{{ url('/') }}" method="POST">
#csrf
</form>
<script type='application/javascript'>
//create new instance
var api = new API("Givenapikey");
//initialize api
api.init(function(){
//attach click event to the button
$("#btnShowLogin").click(function(){
//show login window
api.login({type:'student'},function(result){
//check result
if(result.error==0){
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrftoken"]').attr('content')
},
url: "{{ route('ajaxRequest.post') }}",
data: { username: result.details.usr_name} ,
type: 'POST',
async: false,
success: function(result){
console.log(result);
document.getElementById('login').submit();
}
});
}
});
});
});
</script>
dahsboard.blade My target blade to display my username and other details. Snippet of the code from dashboard.blade.
<span class="info">{{ $name }}</span>
I don't know if I am doing right. Routing and controllers I think I am doing it wrong especially in routing. The output in dashboard.blade is 1. I don't know why.

how to get laravel response the same page after login with ajax?

i have a login form to login a user i want to know about how to get laravel response in ajax success function. if submit the form i was got a object('status':'msg') in http://127.0.0.1:8000/login page. but i want to just redirect user correct page after login with macing alert. please help me to learn laravel with ajax function.
form
<form id="loginForm" method="POST" action="{{ route('login') }}">
#csrf
<input id="email" type="email" class="form-control name="email" value="{{ old('email') }}"
required autocomplete="email" autofocus>
<input id="password" type="password" class="form-control name="password" required
autocomplete="current-password">
<button type="submit" class="btn btn-primary">LOGIN</button>
</form>
ajax: after document ready
$('#loginForm').submit(function(e){
e.preventDefault();
var formInput = $(this);
$.ajax({
type:'POST',
url: 'login',
data: formInput.serialize(),
dataType: 'json',
cache: false,
success:function(status){
if(status== "success"){
alert("your in");
}
},
error:function(status){
if(status== "error"){
alert("no data found");
}
}
})
});
Route:
Route::post('login','loginController#login')->name('loginData');
Controller:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Auth;
use Session;
class loginController extends Controller
{
public function login(Request $request){
$credentials = $request->only('email', 'password');
if (Auth::attempt($credentials)) {
// print_r($request->all());
session()->put('role', Auth::user()->Role);
$request->session()->flash('message', 'New customer added successfully.');
$request->session()->flash('message-type', 'success');
return response()->json(['status'=>'success']);
return back();
}else{
$request->session()->flash('message', 'you have entered an invalid email address or password. please try again');
$request->session()->flash('message-type', 'danger');
return response()->json(['status'=>'error']);
return back();
}
}
}
You can return more data in your AJAX response than just a status. If you wanted to, you could also return a location to redirect to like:
return response()->json([
'status' => 'success',
'redirect' => '/user/dashboard'
]);
Then in your javascript, when you get success, you can then do:
success: function(response) {
if(response.status === "success") {
alert("your in");
window.location.href = response.redirect;
}
},

Laravel password hash is incorrect

i am trying to update password in Laravel, password is updating but when i try to login it shows wrong details, i am not sure what i am doing wrong here.
public function passwordupdate(Request $request, $id)
{
$user = User::find($id);
// Column updating with incorrect Hash
$user->password = Hash::make($request->password);
$user->setRememberToken(Str::random(60));
$user->active = 0; // This value is updating correctly
$user->save();
return response()->json(['msg' => 'password updated']);
}
As I mentioned my request was posting a null value so I am adding Ajax code to figure why.
Ajax
$('.update_password').on('click', function (e) {
console.log('Update password clicked!')
e.preventDefault();
$.ajax({
type: "POST",
dataType: 'json',
data: $(this).serialize(),
url: "/users/" + $('#user_pwid').val(),
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
success: function (data) {
if (data.msg) {
$('#response').empty();
$(".toast").toast('show');
$('#response').append(data.msg);
}
}
});
});
View/Blade
<form method="post" id="policy-form">
#csrf
<input type="hidden" value="">
<select name="name" id="user_pwid" class="form-control user_pwid border border-secondary border-dark" required>
<option selected value="">SELECT USER</option>
#foreach($users as $user)
<option value="{{$user->id}}"> {{$user->name}}</option>
#endforeach
</select>
<input type="password" name="password" id="password">
<button type="click" class="btn btn-danger btn-sm update_password rounded text-center" value="{{$user->id}}"
id="update-password"></button>
</form>
Try This:
Controller Code:
public function passwordupdate(Request $request,$id) {
$user = User::find($id);
if(!is_null($user)){
$user->password = Hash::make($request->password);
$user->setRememberToken(Str::random(60));
$user->active =0;
$user->save();
return response('success');
}
else{
return response('failed');
}
}
Ajax Code:
$('#update-password').on('click', function(e) {
e.preventDefault();
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
},
type: "post",
url: "/users/" + $('#user_pwid').val(),
data :{
password : $('#password').val(),
},
success: function (data) {
if(data == 'success'){
alert('password changed successfully');
$('#response').empty();
$(".toast").toast('show');
$('#response').append(data);
}
else{
alert('failed');
}
},
});
});
Try this it'll work
Does $request->password actually have the intended password? Are you sure you haven't written a mutator on the model that is double hashing the password?
Is there a good reason you're creating your own password reset controller instead of using the one that Laravel ships with? Also - you really don't want to send the password back to the user in JSON.

see the server error after ajax request with laravel

i receive the 500 (Internal Server Error) after make a ajax request on laravel 5.2.
as I can see what is wrong?
at some point I saw that there is a command that starts with tails, but can not find it.
thanks.
code:
html:
<form role="form" id="Login" >
{{ csrf_field() }}
<label >Correo electronico: </label>
<input id="correo" type="email" class="form-control" name="email" placeholder="Enter email">
<id id="emailError"></id>
<label >ContraseƱa:</label>
<input id="password" type="password" class="form-control" name="password" placeholder="Enter password">
<id id="passwordError"></id>
<button type="button" class="btn btn-default" id="Submit" onclick="LogIn(event)" >Iniciar sesion</button>
</form>
js:
function LogIn(event) {
event.preventDefault();
$.ajax({
type: 'post',
url: Login,
dataType: 'json',
data: {
email: $('#correo').val(),
password: $('#password').val(),
},
beforeSend: function()
{
$("#emailError").fadeOut();
$("#passwordError").fadeOut();
},
success: function (data) {
if (!data.success){
console.log(data);
if(typeof data.error.email !== 'undefined'){
$('#correo').css('border-color', 'red');
$('#emailError').fadeIn(10, function () {
$("#emailError").html(data.error.email);
})
}
if(typeof data.error.password !== 'undefined'){
$('#password').css('border-color', 'red');
$('#passwordError').fadeIn(10, function () {
$("#passwordError").html(data.error.password[0]);
})
}
}else{
console.log(data);
$('#LogIn').modal('hide');
}
}
});
}
Controller:
<?php
namespace App\Http\Controllers;
use App\Modals\Users;
use Illuminate\Http\Request;
use Validator;
use App\Http\Controllers\Controller;
use App\Http\Requests;
use App\Modals\Users as user;
use Auth;
class UserController extends Controller
{
public function index()
{
return view('home');
}
/**
* #param Request $request
* #return \Illuminate\Http\JsonResponse
*/
public function entrar (Request $request){
$validator= Validator::make($request->all(),[
'email' => 'required|email',
'password' => 'required|min:2',
]);
if ($validator->fails()){
return response()->json([
'success' => true,
'error' => $validator->errors()->toArray()
]);
}else{
return response()->json([
'success' =>true
]);
}
if (Auth::attempt(['email' => $request->email, 'password' => $request->password]))
{
return response()->json([
'success' => true
]);
}else
{
return response()->json([
'success' => false,
'error' => 'not login'
]);
}
}
}
log:
POST http://localhost:8000/Entrar 500 (Internal Server Error) jquery.min.js:4
send # jquery.min.js:4
ajax # jquery.min.js:4
LogIn # scripts.js:82
onclick # VM18805:87

How to AJAX work

I am new in AJAX. but I am trying to learn How this is working.
I am using symfony2 with fos user bundle and I want implement AJAX to my login form.
so I was doing this :
login.html.twig
<script>
$('#_submit').click(function(e){
e.preventDefault();
$.ajax({
type : $('form').attr( 'method' ),
url : $('form').attr( 'action' ),
data : $('form').serialize(),
success : function(data, status, object) {
if (data.sucess == false) {
$('.tab-1').prepend('<div />').html(data.message);
} else {
window.location.href = data.targetUrl;
}
}
});
</script>
<div id="tab-1" class="login_form">
<form action="{{ path("fos_user_security_check") }}" role="form" method="post">
<label for="username"><strong>User Name / Email Address</strong>
<input type="text" id="username" name="_username" value="{{ last_username }}" required="required" />
</label>
<label for="password"><strong>Password</strong>
<input type="password" id="password" name="_password" required="required" />
</label>
<label for="password"><strong>Remember Me</strong>
<input type="checkbox" id="remember_me" name="_remember_me" value="on" />
</label>
<input type="submit" class="submitBut" id="_submit" name="_submit" value="{{ 'security.login.submit'|trans({}, 'FOSUserBundle') }}" />
</form>
</div>
And when submit then go this file :-
<?php
namespace XXXX\UserBundle\Handler;
use Symfony\Component\Security\Http\Authentication\AuthenticationFailureHandlerInterface;
use Symfony\Component\Security\Http\Authentication\AuthenticationSuccessHandlerInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Routing\Router;
use Symfony\Component\Security\Core\SecurityContext;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Translation\Translator;
use Symfony\Component\Translation\MessageSelector;
class AuthenticationHandler implements AuthenticationSuccessHandlerInterface, AuthenticationFailureHandlerInterface
{
protected $router;
protected $security;
protected $userManager;
protected $service_container;
public function __construct(RouterInterface $router, SecurityContext $security, $userManager, $service_container)
{
$this->router = $router;
$this->security = $security;
$this->userManager = $userManager;
$this->service_container = $service_container;
}
public function onAuthenticationSuccess(Request $request, TokenInterface $token) {
if ($request->isXmlHttpRequest()) {
$result = array('success' => true);
$response = new Response(json_encode($result));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
else {
// Create a flash message with the authentication error message
$request->getSession()->getFlashBag()->set('error', $exception->getMessage());
$url = $this->router->generate('fos_user_security_login');
return new RedirectResponse($url);
}
return new RedirectResponse($this->router->generate('anag_new'));
}
public function onAuthenticationFailure(Request $request, AuthenticationException $exception) {
$translator = new Translator('fr_FR');
//$result = array(
// 'success' => false,
// 'function' => 'onAuthenticationFailure',
// 'error' => true,
// 'message' => $this->translator->trans($exception->getMessage(), array(), 'FOSUserBundle')
//);
$result = array('success' => false);
$response = new Response(json_encode($result));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
}
When submit the form then show me in login_check url:
{"success":false}
But I want when result false then return same form where I was trying to login(I mean same popup div)?
What's wrong my code ajax or action return ?
Or I am return correct ?
window.location will reload the entire page. That's not the desired result I suppose since you are using AJAX ( the hole point of AJAX is to not reload the page) instead you could display an error message if the login is not successful.
I suggest you add an error div in your html form
<div class='error' style="display:none" > ooups an erro occured </div>
and then in the ajax call just show it or add a significant message error :
if (data.sucess == false) {
$('.tab-1').prepend('<div />').html(data.message);
} else {
$('.error').show();
}

Resources