AccountManager: Load external ID from primary storage (ReviewDb)

On sign in we can't access the account index to lookup external IDs
since Gerrit slaves don't have an account index, but Gerrit slaves must
be able to sign in. Instead load the external ID from the primary
storage which is ReviewDb in 2.14.

In addition loading the external ID from the primary storage is safer
than finding the account via the account index and then looking up the
external ID via the account cache since the account index may be stale.

Change-Id: I2b2e7330aa00af5a99a26430cc40d8862611b0d4
Signed-off-by: Edwin Kempin <ekempin@google.com>
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/account/AccountManager.java b/gerrit-server/src/main/java/com/google/gerrit/server/account/AccountManager.java
index b0dcbe4..b5d0463 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/account/AccountManager.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/account/AccountManager.java
@@ -111,7 +111,7 @@
     who = realm.authenticate(who);
     try {
       try (ReviewDb db = schema.open()) {
-        ExternalId id = findExternalId(who.getExternalIdKey());
+        ExternalId id = findExternalId(db, who.getExternalIdKey());
         if (id == null) {
           // New account, automatically create and return.
           //
@@ -133,16 +133,8 @@
     }
   }
 
-  private ExternalId findExternalId(ExternalId.Key key) throws OrmException {
-    AccountState accountState = accountQueryProvider.get().oneByExternalId(key);
-    if (accountState != null) {
-      for (ExternalId extId : accountState.getExternalIds()) {
-        if (extId.key().equals(key)) {
-          return extId;
-        }
-      }
-    }
-    return null;
+  private ExternalId findExternalId(ReviewDb db, ExternalId.Key key) throws OrmException {
+    return ExternalId.from(db.accountExternalIds().get(key.asAccountExternalIdKey()));
   }
 
   private void update(ReviewDb db, AuthRequest who, ExternalId extId)
@@ -357,7 +349,7 @@
   public AuthResult link(Account.Id to, AuthRequest who)
       throws AccountException, OrmException, IOException, ConfigInvalidException {
     try (ReviewDb db = schema.open()) {
-      ExternalId extId = findExternalId(who.getExternalIdKey());
+      ExternalId extId = findExternalId(db, who.getExternalIdKey());
       if (extId != null) {
         if (!extId.accountId().equals(to)) {
           throw new AccountException("Identity in use by another account");
@@ -432,7 +424,7 @@
   public AuthResult unlink(Account.Id from, AuthRequest who)
       throws AccountException, OrmException, IOException, ConfigInvalidException {
     try (ReviewDb db = schema.open()) {
-      ExternalId extId = findExternalId(who.getExternalIdKey());
+      ExternalId extId = findExternalId(db, who.getExternalIdKey());
       if (extId != null) {
         if (!extId.accountId().equals(from)) {
           throw new AccountException(