Laravel Inertia (Vue) - Authenticate without Redirect - laravel

I'm making a normal Inertia post to a base Laravel login route:
submit() {
this.$inertia.post("/login", {
email: this.emailAddress,
password: this.password,
}, {
preserveState: true,
preserveScroll: true,
});
}
I'm able to catch validation errors as expected, but what I'm trying to avoid is the redirect after a successful user authentication, and instead proceed in the "logged in" state (update header to show user info, etc).
The Laravel AuthenticatesUsers trait contains this contains two key methods that gets called as part of the out-of-the-box login flow
public function login(Request $request)
{
$this->validateLogin($request);
// If the class is using the ThrottlesLogins trait, we can automatically throttle
// the login attempts for this application. We'll key this by the username and
// the IP address of the client making these requests into this application.
if (method_exists($this, 'hasTooManyLoginAttempts') &&
$this->hasTooManyLoginAttempts($request)) {
$this->fireLockoutEvent($request);
return $this->sendLockoutResponse($request);
}
if ($this->attemptLogin($request)) {
return $this->sendLoginResponse($request);
}
// If the login attempt was unsuccessful we will increment the number of attempts
// to login and redirect the user back to the login form. Of course, when this
// user surpasses their maximum number of attempts they will get locked out.
$this->incrementLoginAttempts($request);
return $this->sendFailedLoginResponse($request);
}
and
protected function sendLoginResponse(Request $request)
{
$request->session()->regenerate();
$this->clearLoginAttempts($request);
if ($response = $this->authenticated($request, $this->guard()->user())) {
return $response;
}
return $request->wantsJson()
? new Response('', 204)
: redirect()->intended($this->redirectPath());
}
I'm struggling to figure out if it's even possible to authenticate a user without redirecting this way.

You need to utilize the javascript frontend, not Inertia::post() . One way to do this is to use Axios:
submit() {
const data = {...this.form.data()};
axios.post('/auth/login', data, {
headers: {
'Content-Type': 'application/json',
},
})
.then(res => {
console.log('login success!', res);
});

Check your form and the way you submit - do you prevent the default behavior of the form submit? It seems like you are sending a POST but the native form behavior is also triggered.
You can also set a $redirectTo in your LoginController, also check RouteServiceProvider there is a public const HOME = '/' which triggered the redirect if nothing else is given.

This are my two cents...
A few days ago I was struggling with passing the result of the script to Vue without redirecting, using Inertia visits instead of Axios.
The solution I adopted was the following:
In vue:
this.$inertia.visit(`URL`, {
method: "post",
data: { //Email and password },
preserveState: false,
preserveScroll: false,
onError: (errors) => { // do what ever is needed if validation fails },
onSuccess: () => { // do what ever is needed if validation succeeds }
});
In Laravel:
// If validation fails:
return redirect()->back()->withErrors([
'login' => 'Validation fail details.'
]);
// If validation succeeds:
return redirect()->back()->with('login', 'Success message!');
This way the page does not redirect and the user can continue exactly wherever he is.
What i'm not sure is if it's possible to pass the user info over the success redirect message. Maybe returning a array like it's done in withErrors. If not possible it's always possible to make an additional request to the server to retrieve the desired information.
Hope it's usefull.

Related

Laravel Fortify returns Not Found

I send a xhr request to /login route. It does login, but the response is an html with text Not Found. I realize that fortify is saying this coz it cant find the logged in view. I have enabled views, 'views' => true in config/Fortify.php. But I want Fortify to return a success response text after successful login. How can I do this?
You can customise your response based on the request type:
public function func(Request $request)
{
if ($request->ajax()) {
return response()->json('AJAX response', 200);
}
return view('my-view');
}

Laravel 419 Error using Ajax

Okay let me explain first. I am sending a PUT request using ajax like this:
//ajax function
$(document).on("click", ".question_no", function(){
current_color = rgb2hex($(this).css('background-color'));
q_index = $(this).attr('id').slice(5);
id_team_packet = $("#id_team_packet").val();
// startTimer();
if (current_color != '#ffc966') {
$(this).css('background-color', "#ffc966");
var status = "orange";
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: '{{route('peserta.submit.ans.stat')}}',
method: 'put',
data: {q_index, id_team_packet},
success: function(data){
console.log(data)
}
})
}
})
NOTE I already have my CSRF token setup in my head, which I also include in my ajax setup as you can see below. It works great :). But once I protect that route with a Middleware, like this:
//middleware
public function handle($request, Closure $next)
{
if (Auth::user()) {
if (Auth::user()->role == 3) {
return $next($request);
}
if ($request->ajax()) {
return response()->json(['intended_url'=>'/'], 401);
}
return redirect('/');
}
if ($request->ajax()) {
return response()->json(['intended_url'=>'/'], 401);
}
return redirect('/');
}
//web.php
Route::middleware(['participant_only'])->group(function(){
Route::put('/peserta/submit-answer-status', 'PesertaController#submitAnsStat')->name('peserta.submit.ans.stat');
});
As you can see it only accepts logged in user with a role of '3'. If user tries to log in, it redirects to '/'. Now I also check if the request is using ajax, which I return a message with code 401. But unfortunately, when the middleware is applied and I ajax it, it returns this error:
message
exception Symfony\Component\HttpKernel\Exception\HttpException
file -\vendor\laravel\framework\src\Illuminate\Foundation\Exceptions\Handler.php
line 203
But if once I remove the middleware it works. I don't know where the problem is. Oh on another note, If I exclude that particular route from verifycsrftoken it returns the right response both with the middleware and without.
My question is, where is the problem and how do I fix it? Thank you :)

Laravel Passport consuming own API fail

I'm building a SPA with Vue. My front-end and my back-end (Laravel) are in the same codebase. I want to approach my API (that is in my back-end) via the Laravel Passport Middleware CreateFreshApiToken. I'm approaching my sign in method in my AuthController via web.php.
My problem:
As soon as I'm successfully signed in via my sign in method I would expect that at this time Passport created the laravel_token cookie. This is not the case. The cookie is created after a page refresh. But as I said I'm building a SPA and that's why I don't want to have page refreshes.
What I want:
I want to sign in via my sign in method then use the Passport CreateFreshApiToken middleware. After that I want to use the (just created in the middleware) laravel_token cookie so that I can correctly and safely speak to my own API in my signed-in section of the SPA.
More information:
Kernel.php
// Code...
protected $middlewareGroups = [
'web' => [
// other middlewares...
\Laravel\Passport\Http\Middleware\CreateFreshApiToken::class,
],
];
// Code...
AuthController.php
// Code...
public function login()
{
if (Auth::attempt(['email' => Input::get('email'), 'password' => Input::get('password')], true)) {
return response()->json([
'user' => Auth::user(),
'authenticated' => auth()->check(),
]);
}
return response()->json(['authenticated' => false], 401);
}
// Code...
Login.vue
// Code...
methods: {
login: function (event) {
event.preventDefault();
this.$http.post(BASE_URL + '/login', {
email: this.email,
password: this.password,
})
.then(function (response) {
localStorage.user_id = response.body.user.id;
router.push({
name: 'home'
});
});
},
},
// Code...
What goes wrong? This:
CreateFreshApiToken.php
// Code...
public function handle($request, Closure $next, $guard = null)
{
$this->guard = $guard;
$response = $next($request);
// I'm signed in at this point
if ($this->shouldReceiveFreshToken($request, $response)) { // returns false unless you refresh the page. That's why it won't create the laravel_token cookie
$response->withCookie($this->cookieFactory->make(
$request->user($this->guard)->getKey(), $request->session()->token()
));
}
return $response;
}
protected function shouldReceiveFreshToken($request, $response)
{
// both methods below return false
return $this->requestShouldReceiveFreshToken($request) &&
$this->responseShouldReceiveFreshToken($response);
}
protected function requestShouldReceiveFreshToken($request)
{
// $request->isMethod('GET') - returns false because it's a POST request
// $request->user($this->guard) - returns true as expected
return $request->isMethod('GET') && $request->user($this->guard);
}
protected function responseShouldReceiveFreshToken($response)
{
// $response instanceof Response - returns false
// ! $this->alreadyContainsToken($response) - returns false as expected
return $response instanceof Response &&
! $this->alreadyContainsToken($response);
}
// Code...
I assume it is possible what I want to achieve right? If yes, how?
I had the same issue, decided to stick to client_secret way. I guess it's not relevant for you now, but I've found 2 ways of receiving the laravel token without refresh:
1) sending dummy get request with axios or $http, whatever you use - token will get attached to response;
2) changing requestShouldReceiveFreshToken method in CreateFreshApiToken.php - replace return $request->isMethod('GET') && $request->user($this->guard); with return ($request->isMethod('GET') || $request->isMethod('POST')) && $request->user($this->guard);
function consumeOwnApi($uri, $method = 'GET', $parameters = array())
{
$req = \Illuminate\Http\Request::create($uri, $method, $parameters, $_COOKIE);
$req->headers->set('X-CSRF-TOKEN', app('request')->session()->token());
return app()->handle($req)->getData();
}

laravel: how to actually login users (ajax login)

Can't...Log users... in... Angry.
Basically, I'm running users through the regular login, with my own authenticated method defined to return a json object instead of being redirected. For the moment, I'm returning the results of this function
Auth::check();
Which returns true when all is said and done.
The problem is that my logins don't appear to exist beyond this single call. If I make anymore ajax calls, Auth::check() fails every time. If I refresh the page, auth::check() fails.
Please god help me.
PS. My session driver is current set to cookies.
//EDIT TO SHOW THE PEOPLE I'M NOT CRAZY
public function ajaxLogin(Request $request)
{
if(Auth::check()){
return response()
->json('loggedIn');
}
// If the class is using the ThrottlesLogins trait, we can automatically throttle
// the login attempts for this application. We'll key this by the username and
// the IP address of the client making these requests into this application.
$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 the login attempt was unsuccessful we will increment the number of attempts
// to login and redirect the user back to the login form. Of course, when this
// user surpasses their maximum number of attempts they will get locked out.
if ($throttles && ! $lockedOut) {
$this->incrementLoginAttempts($request);
}
return response()
->json([
$this->loginUsername() => $this->getFailedLoginMessage(),
]);
}
protected function authenticated($request, $user){
Auth::login($user);
return response()->json( 'yo');
}
If I send the right credentials, I get back yo. If I send the right credentials again (another ajax call) I get yo. I can never get logged in.
From what I can tell, for some reason, my sessions are being destroyed with every request? I don't know why, but this does appear to be why I'm never logged in.
//EDIT ADD SITUATIONAL CLARITY
laravel -v 5.2
this is all through the auth controller, so just the default:
Route::group(['middleware' => 'web'], function () {
Route::auth();
Route::get('/home', 'HomeController#index');
});

laravel TokenMismatchExceptions on login

I'm getting this TokenMismatchException with Laravel 4. It happens to me if the browser sits on the login page for a while. For example a lot of times when I come back to work on my project the next day, if my browser has the login page open in a tab, when I try to log in I get the TokenMismatchException. If I'm logging in and out throughout the day while working, I never see it. It's like the token expires or something.
Route.php
// route to show the admin login form
Route::get('login', array('uses' => 'AdminController#showLogin'));
// route to process the admin login form
Route::post('login', array('uses' => 'AdminController#doLogin'));
AdminController.php
public function showLogin()
{
// show the login form
return View::make('admin.login');
}
public function doLogin()
{
// validate the info, create rules for the inputs
$rules = array('username' => 'required','password' => 'required' );
// run the validation rules on the inputs from the form
$validator = Validator::make(Input::all(), $rules);
// if the validator fails, redirect back to the form
if ($validator->fails()) {
return Redirect::to('login')
->withErrors($validator) // send back all errors to the login form
->withInput(Input::except('password')); // send back the input (not the password) so that we can repopulate the form
} else {
// create our user data for the authentication
$userdata = array('my_username'=> Input::get('username'),'password'=> Input::get('password'));
// attempt to do the login
if (Auth::attempt($userdata)) {
return Redirect::intended('dashboard');
} else {
// Authentication not successful, send back to form
return Redirect::to('login')->with('message', 'Your username/password combination was incorrect');
}
}
}
Please, help is needed...
That's normal, session will expire if you get idle for too long. It's a security measure, so you just need to make sure you redirect your user to login when the token expires. Add this to your global.php file or create a exceptions.php file to it:
App::error(function(\Illuminate\Session\TokenMismatchException $exception)
{
return Redirect::route('login')->with('message','Your session has expired. Please try logging in again.');
});

Resources