User registration inconsistencies with social networks
Hi, I need your help. I have added the possibility to connect through social networks (Google, Facebook).
I found a small but important inconsistency, I try to explain myself better.
User 1: Register a normal account, with an email that is not owned by you ([email protected]), but register the account anyway, then log in.
User 2: Owns the email property [email protected], and decides to log in directly with google.
User 2 will be logged into the account that User 1 had already created.
To avoid this problem, I changed the code and requested the verification of the email, restricting access to some areas of the site so that only the user who verified the email can change the password if necessary.
But I was still wondering if there was something more linear, how can I improve the code? Or let's say I don't want email verification, how can I fix that problem?
public function handleProviderCallback()
{
try {
$user = Socialite::driver('google')->user();
} catch (\Exception $e) {
return redirect('/login');
}
// only allow people with @company.com to login
if(explode("@", $user->email)[1] !== 'gmail.com'){
return redirect()->to('/');
}
// check if they're an existing user
$existingUser = User::where('email', $user->email)->first();
if($existingUser){
// log them in
Auth::login($existingUser, true);
} else {
$existingUserName = User::where('name', $user->name)->count();
//
if($existingUserName == 1) {
$username = $user->name.'_'.$user->id;
} else {
$username = $user->name;
}
// create a new user
$newUser = new User;
$newUser->name = $username;
$newUser->email = $user->email;
$newUser->google_id = $user->id;
$newUser->save();
$newUser
->roles()
->attach(Role::where('name', 'User')->first());
auth()->login($newUser, true);
}
return redirect()->to('/');
}
Please or to participate in this conversation.