AuthClient redirect if login was success but not for existing user

tl;dr How can I redirect a visitor to the login page if their authentication with Google was a success but I don’t have that user in my records?

I have the following code in my SiteController:




public function successCallback($client)

{

	$attributes = $client->getUserAttributes();

	// Build cloud id

	$cloudId = $client->id . '-' . $attributes['id']; // ex. google-123123123123123123

	// Find user

	$user = User::findOne(['cloud_id' => $cloudId]);


	// If User exists, login that user

	// If User does not exist, return to login page with error

	if ($user) {

		Yii::$app->user->login($user, 3600 * 24 * 30);

	} else {

		// Return visitor to login page with error

		// HOW DO I GET THEM BACK TO THE LOGIN PAGE?

	}

}



Whenever a Google authentication is successful AND I have that user in the user table, the user is logged in and redirected to the home page. When the Google authentication is successful and that user is NOT in my user table, I want to redirect them to the login page, perhaps with an error saying "This Google account is not yet registered."

The use case is when multiple auth clients are available (Google and Facebook), if someone uses their Google account to register then later they come back and click Facebook, I don’t want that to create a new account automatically (what my code previously did). I want there to be a purposeful separation between logging in and registering. So, I need to send the user back to the login/register page if an authentication was successful from the Google/Facebook side but I don’t have that user in my user table.

I really hope someone can help out here–I’ve been stuck on this for days.

I’m not sure if the following is correct (the ‘else’ statement below) but I am able to keep the user on the login page either with redirectCancel or setSuccessUrl. I haven’t decided which to use at this point since I’m not sure if I want to use a flash message or some other means of communicating the authentication failure.

As a side note, I was missing ‘->action’ in the return statement–that’s why I was never able to figure this out. Hopefully this answer can help someone else in the future.





	// If User exists, login that user

	// If User does not exist, return to login page with error

	if ($user) {

		Yii::$app->user->login($user, 3600 * 24 * 30);

	} else {

		// Return visitor to login page with error

		//return $this->action->redirectCancel();

		return $this->action->setSuccessUrl(Url::to(['/site/login']));

	}

}