Line data Source code
1 : // Copyright (C) 2019 The Android Open Source Project 2 : // 3 : // Licensed under the Apache License, Version 2.0 (the "License"); 4 : // you may not use this file except in compliance with the License. 5 : // You may obtain a copy of the License at 6 : // 7 : // http://www.apache.org/licenses/LICENSE-2.0 8 : // 9 : // Unless required by applicable law or agreed to in writing, software 10 : // distributed under the License is distributed on an "AS IS" BASIS, 11 : // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 : // See the License for the specific language governing permissions and 13 : // limitations under the License. 14 : 15 : package com.google.gerrit.server.account.externalids; 16 : 17 : import static com.google.gerrit.server.account.externalids.ExternalId.SCHEME_USERNAME; 18 : 19 : import com.google.common.base.Strings; 20 : import com.google.common.flogger.FluentLogger; 21 : import com.google.gerrit.common.Nullable; 22 : import com.google.gerrit.server.account.HashedPassword; 23 : import com.google.gerrit.server.config.AuthConfig; 24 : import com.google.inject.Inject; 25 : import java.util.Collection; 26 : 27 : /** Checks if a given username and password match a user's external IDs. */ 28 : public class PasswordVerifier { 29 139 : private static final FluentLogger logger = FluentLogger.forEnclosingClass(); 30 : 31 : private final ExternalIdKeyFactory externalIdKeyFactory; 32 : 33 : private AuthConfig authConfig; 34 : 35 : @Inject 36 139 : public PasswordVerifier(ExternalIdKeyFactory externalIdKeyFactory, AuthConfig authConfig) { 37 139 : this.externalIdKeyFactory = externalIdKeyFactory; 38 139 : this.authConfig = authConfig; 39 139 : } 40 : 41 : /** Returns {@code true} if there is an external ID matching both the username and password. */ 42 : public boolean checkPassword( 43 : Collection<ExternalId> externalIds, String username, @Nullable String password) { 44 38 : if (password == null) { 45 0 : return false; 46 : } 47 : 48 38 : for (ExternalId id : externalIds) { 49 : // Only process the "username:$USER" entry, which is unique. 50 38 : if (!id.isScheme(SCHEME_USERNAME)) { 51 37 : continue; 52 : } 53 : 54 38 : if (!id.key().equals(externalIdKeyFactory.create(SCHEME_USERNAME, username))) { 55 0 : if (!authConfig.isUserNameCaseInsensitiveMigrationMode()) { 56 0 : continue; 57 : } 58 : 59 0 : if (!id.key().equals(externalIdKeyFactory.create(SCHEME_USERNAME, username, false))) { 60 0 : continue; 61 : } 62 : } 63 : 64 38 : String hashedStr = id.password(); 65 38 : if (!Strings.isNullOrEmpty(hashedStr)) { 66 : try { 67 38 : return HashedPassword.decode(hashedStr).checkPassword(password); 68 0 : } catch (HashedPassword.DecoderException e) { 69 0 : logger.atSevere().log("DecoderException for user %s: %s ", username, e.getMessage()); 70 0 : return false; 71 : } 72 : } 73 1 : } 74 1 : return false; 75 : } 76 : }