/** * * @param \nkostadinov\user\components\ClientInterface $client * @return type * @throws NotSupportedException */ public function oAuthAuthentication(ClientInterface $client) { if (!$client instanceof IUserAccount) { throw new NotSupportedException('Your client must extend the IUserInterface.'); } $account = UserAccount::findByClient($client); if (empty($account)) { // If account doesn't exist, create it Yii::info("Creating user account for user [{$client->id}][{$client->userId}]", __CLASS__); $account = UserAccount::createAndSave($client); } $event = Event::createAuthEvent($account, $client); $this->trigger(self::EVENT_BEFORE_OAUTH, $event); $result = true; if (!$account->user) { // Create a new user or link account to an existing user if (Yii::$app->user->isGuest) { // This means the user comes for a first time or has a user created by a regular login or another client $email = $client->getEmail(); if (is_null($email)) { // Sometimes the email cannot be fetched from the client Yii::info("Unable to fetch the email of account [{$client->id}][{$client->userId}]", __CLASS__); throw new MissingEmailException(); } else { try { $result = $this->createUserByOAuthIfNotExists($client, $account, $email); } catch (DuplicatedUserException $exception) { throw $exception; } } } else { // Link account to user // This means the user is logged in through a regular login or another client. Needs to be linked. $email = Yii::$app->user->identity->email; Yii::info("Linking user [{$email}] to account [{$client->id}][{$client->userId}]", __CLASS__); $account->link('user', Yii::$app->user->identity); } } else { if (Yii::$app->user->isGuest) { Yii::info("Logging in user [{$account->user->email}]", __CLASS__); $result = Yii::$app->user->login($account->user); } } $this->trigger(self::EVENT_AFTER_OAUTH, $event); return $result; }