Checking if current user is logged in through the API
I have the following in my AuthenticatedSessionController
public function status(Request $request) {
// if the user is not logged in
if (!Auth::check()) {
return json_encode(array(
'status' => 'guest'
), JSON_FORCE_OBJECT);
}
// if the account belongs to a customer
if (Auth::check() && !Auth::user()->tokenCan('admin')) {
return json_encode(array(
'status' => 'unauthorized'
), JSON_FORCE_OBJECT);
}
// if the user is a verified admin
if (Auth::check() && Auth::user()->tokenCan('admin')) {
return json_encode(array(
'status' => 'authorized',
'id' => Auth::id()
), JSON_FORCE_OBJECT);
}
}
I logged in with a valid user through the default login provided with Laravel Breeze. However, when I make a call to this function through the API, Auth:check() is false. Isn't this supposed to be true, as I am currently logged in?
Perhaps I am thinking about this all wrong. Please let me know. Any help is appreciated.
public function api_store(LoginRequest $request)
{
$request->authenticate();
if (Auth::check()) {
// if the user is logged in, issue an API token
$authorized_emails = [
'[email protected]'
];
if (in_array($request->email, $authorized_emails)) {
auth()->user()->createToken('admin', ['admin']);
} else {
auth()->user()->createToken('customer', ['customer']);
}
}
return $request;
}
I have this function which handles the login via an API request, it uses the same method as the Laravel Breeze store method, but I just made it so it can be accessed by an API and issues a token to the users. Auth and auth() work here perfectly (in the way I'm using them here at least), but not in other functions. Can this be explained?
@lpel APIs are meant to be stateless. There is no “logged in” or “logging out” or an API. You use a token to authenticate each request. If the token is valid, a user is resolved for that request and that request only. You should not be hitting an API endpoint to check if you’re “logged in” or not.
@martinbean This is my first time experimenting with this concept, and using Laravel Sanctum. From what I saw, the token was stored in the user, but then how would I authenticate it without knowing if the user is logged in, and then retrieving the token from there?
@lpel Can you please answer the question with the actual answer? Because up to now you’ve said you were using Sanctum and then Breeze, which are two totally different things.
So, what are you actually using to authenticate? Because no one can help you if you just keep changing facts.
@martinbean I don't think I changed my answer at all. In my original post, I mentioned that the user is logged in through the default login provided with Laravel Breeze - however, I'm also using the tokens provided by Laravel Sanctum.
@jlrdw I see a thing about CSRF protection. I am logging in through either the default login screen provided with Breeze, or a request through Insomnia. Would this affect the issue I'm having?