I am using Laravel 5.1 and I am trying to setup a simple login/logout system. I can easily login using:
Auth::attempt(['email' => $request->email, 'password' => $request->password]);
But if I try to logout via an ajax request using Auth::logout();
, it does not log out the user. Manually going to the logout route in a browser tab however works just fine.
note: if my controller looks like this:
public function logout()
{
Auth::logout();
dd(Auth::user());
}
Then the request returns null
. This should indicate the user has been logged out, but if I pass another request - I am still logged in.
Edit
Ajax call:
import request from 'superagent'
request.get(env.api + endpoint)
.withCredentials()
.set({
'X-Requested-With': 'XMLHttpRequest'
})
.end((err, res) => {
if (err) return reject(err);
return resolve(res.body);
})
EDIT
I found the source of my problem. It was a single route that looked like this:
Route::get('image/users/{image}', ['as' => 'fetch.users.images', 'uses' => 'Files@fetchUserImage']);
Changing the route path image/users/{image}
solved my problem. Still curious as to why this caused an error with Auth? The route was not interfering with any of my other routes.
Edit
My above edit was wrong. It is to do with that route but its not the naming.
I am requesting an image from the route Route::get('image/users/{image}', ['as' => 'fetch.users.images', 'uses' => 'Files@fetchUserImage']);
whose associated controller looks like this:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Storage;
class Files extends Controller
{
public function __construct()
{
$this->middleware('basic');
}
public function fetchUserImage($image)
{
$image = 'users/images/' . $image;
if (Storage::disk('s3')->exists($image)) {
return response(Storage::disk('s3')->get($image), 200, ['Content-Type' => 'image/jpeg']);
} else {
return response('Image not found', 404);
}
}
}
I am requesting the image with JS like this:
let img = new Image();
img.onload = () => this.state.update ? this.setState({image: props.src}) : null;
img.src = this.props.src;
When Laravel returns 404
or false
or anything that isn't an image, the JS sends the request again. After I logout, Laravel still has an image request to process and the response('Image not found', 404)
gets triggered after
my logout succeeds and then as the response
contains the logged in session info, my browser gets indirectly logged back in.
Haven't come up with a fix for this yet. Not sure how to go about it.