/**
  * Attempts to find an external account and if none exists creates a new
  * external account with a shiny new ID and PHID.
  *
  * NOTE: This function assumes the first item in various query parameters is
  * the correct value to use in creating a new external account.
  */
 public function loadOneOrCreate()
 {
     $account = $this->executeOne();
     if (!$account) {
         $account = new PhabricatorExternalAccount();
         if ($this->accountIDs) {
             $account->setAccountID(reset($this->accountIDs));
         }
         if ($this->accountTypes) {
             $account->setAccountType(reset($this->accountTypes));
         }
         if ($this->accountDomains) {
             $account->setAccountDomain(reset($this->accountDomains));
         }
         if ($this->accountSecrets) {
             $account->setAccountSecret(reset($this->accountSecrets));
         }
         if ($this->userPHIDs) {
             $account->setUserPHID(reset($this->userPHIDs));
         }
         $account->save();
     }
     return $account;
 }
 private function setAccountKeyAndContinue(PhabricatorExternalAccount $account, $next_uri)
 {
     if ($account->getUserPHID()) {
         throw new Exception(pht('Account is already registered or linked.'));
     }
     // Regenerate the registration secret key, set it on the external account,
     // set a cookie on the user's machine, and redirect them to registration.
     // See PhabricatorAuthRegisterController for discussion of the registration
     // key.
     $registration_key = Filesystem::readRandomCharacters(32);
     $account->setProperty('registrationKey', PhabricatorHash::digest($registration_key));
     $unguarded = AphrontWriteGuard::beginScopedUnguardedWrites();
     $account->save();
     unset($unguarded);
     $this->getRequest()->setTemporaryCookie(PhabricatorCookies::COOKIE_REGISTRATION, $registration_key);
     return id(new AphrontRedirectResponse())->setURI($next_uri);
 }