I am using Laravel Sanctum for creating API tokens. But anyone can create limitless tokens via sending request to login route without an authorization header.
I can't delete existing tokens because maybe a user has 2 phones, and 2 laptops and logged in from each of them.
I don't know how to create only one token for one device. Namely, deleting the exact token belong the device and create new one in case a user sends the request again to login route.
I tested sending a latest token of a user (if user have any tokens) instead of creating a new token on every request to login route but no luck because tokens are hashed in DB.
so, what is the best practise for solving too many tokens problem in database?
Here is login function
public function __invoke(Request $request)
{
$validated = $request->validate([
'email' => 'required|email',
'password' => 'required|string'
]);
// find user
$user = User::where('email', $validated['email'])->first();
if (!$user || !Hash::check($validated['password'], $user->password)) {
return response()->json([
'success' => false,
'message' => __('auth.failed')
], 200);
}
// store token
$token = $user->createToken($user->name.'-token')->plainTextToken;
return response()->json([
'success' => true,
'message' => 'Successfully logged in',
'user' => $user,
'token' => $token
], 200);
}
