I'm trying to build an API with Laravel and Sanctum for an existing system with a database that I cannot modify, and I'm having problems with authentication.
The system has a not very common user table, where a user can have the same id but with 3 different 'types'. So, at login, I send the email, password, and the type. It's not a problem and successfully logs in.
But when trying to recover the logged-in user, it shows the wrong user. Example:
Login:
(this user has id 8)
email: dummy@gmail.com
password: xxxxx
type: 2
Recovered user:
(this user also has id 8)
email: dummy@gmail.com
passsword: xxxxx
type: 1
I think it's because they have the same ID and Laravel takes the first user, which is not necessarily correct.
I'm stuck with this... What should I do? Is there a way to get the right user? Thanks
Login function
public function login(Request $request)
{
$validator = Validator::make($request->all(), [
'email' => 'required|email',
'password' => 'required',
'tip_id' => 'required|int'
]);
if (!Auth::attempt($validator->validated())) {
return response()->json(['error' => 'Email e/ou senha incorretos'], 400);
} else {
$user = User::where('email', $request->input('email'))->where('tip_id', $request->input('tip_id'))->first();
$item = time().rand(0, 9999);
$token = $user->createToken($item)->plainTextToken;
return response()->json(['token' => $token]);
}
}
User profile function
public function profile()
{
return response()->json(['user' => auth()->user()]);
}