Search in sources :

Example 16 with AccountException

use of com.google.gerrit.server.account.AccountException in project gerrit by GerritCodeReview.

the class AccountManagerIT method cannotActivateAccountOnAuthenticationWhenAutoUpdateAccountActiveStatusIsDisabled.

@Test
public void cannotActivateAccountOnAuthenticationWhenAutoUpdateAccountActiveStatusIsDisabled() throws Exception {
    String username = "foo";
    Account.Id accountId = Account.id(seq.nextAccountId());
    ExternalId.Key gerritExtIdKey = externalIdKeyFactory.create(ExternalId.SCHEME_GERRIT, username);
    accountsUpdate.insert("Create Test Account", accountId, u -> u.setActive(false).addExternalId(externalIdFactory.create(gerritExtIdKey, accountId)));
    AuthRequest who = authRequestFactory.createForUser(username);
    who.setActive(true);
    who.setAuthProvidesAccountActiveStatus(true);
    AccountException thrown = assertThrows(AccountException.class, () -> accountManager.authenticate(who));
    assertThat(thrown).hasMessageThat().contains("Authentication error, account inactive");
}
Also used : Account(com.google.gerrit.entities.Account) AuthRequest(com.google.gerrit.server.account.AuthRequest) AccountException(com.google.gerrit.server.account.AccountException) ExternalId(com.google.gerrit.server.account.externalids.ExternalId) Test(org.junit.Test) AbstractDaemonTest(com.google.gerrit.acceptance.AbstractDaemonTest)

Example 17 with AccountException

use of com.google.gerrit.server.account.AccountException in project gerrit by GerritCodeReview.

the class Helper method findAccount.

LdapQuery.Result findAccount(Helper.LdapSchema schema, DirContext ctx, String username, boolean fetchMemberOf) throws NamingException, AccountException {
    final HashMap<String, String> params = new HashMap<>();
    params.put(LdapRealm.USERNAME, username);
    List<LdapQuery> accountQueryList;
    if (fetchMemberOf && schema.type.accountMemberField() != null) {
        accountQueryList = schema.accountWithMemberOfQueryList;
    } else {
        accountQueryList = schema.accountQueryList;
    }
    for (LdapQuery accountQuery : accountQueryList) {
        List<LdapQuery.Result> res = accountQuery.query(ctx, params);
        if (res.size() == 1) {
            return res.get(0);
        } else if (res.size() > 1) {
            throw new AccountException("Duplicate users: " + username);
        }
    }
    throw new NoSuchUserException(username);
}
Also used : AccountException(com.google.gerrit.server.account.AccountException) HashMap(java.util.HashMap) NoSuchUserException(com.google.gerrit.server.auth.NoSuchUserException) ParameterizedString(com.google.gerrit.common.data.ParameterizedString)

Example 18 with AccountException

use of com.google.gerrit.server.account.AccountException in project gerrit by GerritCodeReview.

the class LdapAuthBackend method authenticate.

@Override
public AuthUser authenticate(AuthRequest req) throws MissingCredentialsException, InvalidCredentialsException, UnknownUserException, UserNotAllowedException, AuthException {
    if (req.getUsername() == null) {
        throw new MissingCredentialsException();
    }
    final String username = lowerCaseUsername ? req.getUsername().toLowerCase(Locale.US) : req.getUsername();
    try {
        final DirContext ctx;
        if (authConfig.getAuthType() == AuthType.LDAP_BIND) {
            ctx = helper.authenticate(username, req.getPassword());
        } else {
            ctx = helper.open();
        }
        try {
            final Helper.LdapSchema schema = helper.getSchema(ctx);
            final LdapQuery.Result m = helper.findAccount(schema, ctx, username, false);
            if (authConfig.getAuthType() == AuthType.LDAP) {
                // We found the user account, but we need to verify
                // the password matches it before we can continue.
                //
                helper.authenticate(m.getDN(), req.getPassword()).close();
            }
            return new AuthUser(AuthUser.UUID.create(username), username);
        } finally {
            try {
                ctx.close();
            } catch (NamingException e) {
                log.warn("Cannot close LDAP query handle", e);
            }
        }
    } catch (AccountException e) {
        log.error("Cannot query LDAP to authenticate user", e);
        throw new InvalidCredentialsException("Cannot query LDAP for account", e);
    } catch (NamingException e) {
        log.error("Cannot query LDAP to authenticate user", e);
        throw new AuthException("Cannot query LDAP for account", e);
    } catch (LoginException e) {
        log.error("Cannot authenticate server via JAAS", e);
        throw new AuthException("Cannot query LDAP for account", e);
    }
}
Also used : AuthException(com.google.gerrit.server.auth.AuthException) AuthUser(com.google.gerrit.server.auth.AuthUser) DirContext(javax.naming.directory.DirContext) AccountException(com.google.gerrit.server.account.AccountException) InvalidCredentialsException(com.google.gerrit.server.auth.InvalidCredentialsException) LoginException(javax.security.auth.login.LoginException) MissingCredentialsException(com.google.gerrit.server.auth.MissingCredentialsException) NamingException(javax.naming.NamingException)

Example 19 with AccountException

use of com.google.gerrit.server.account.AccountException in project gerrit by GerritCodeReview.

the class LdapRealm method authenticate.

@Override
public AuthRequest authenticate(final AuthRequest who) throws AccountException {
    if (config.getBoolean("ldap", "localUsernameToLowerCase", false)) {
        who.setLocalUser(who.getLocalUser().toLowerCase(Locale.US));
    }
    final String username = who.getLocalUser();
    try {
        final DirContext ctx;
        if (authConfig.getAuthType() == AuthType.LDAP_BIND) {
            ctx = helper.authenticate(username, who.getPassword());
        } else {
            ctx = helper.open();
        }
        try {
            final Helper.LdapSchema schema = helper.getSchema(ctx);
            final LdapQuery.Result m = helper.findAccount(schema, ctx, username, fetchMemberOfEagerly);
            if (authConfig.getAuthType() == AuthType.LDAP && !who.isSkipAuthentication()) {
                // We found the user account, but we need to verify
                // the password matches it before we can continue.
                //
                helper.authenticate(m.getDN(), who.getPassword()).close();
            }
            who.setDisplayName(apply(schema.accountFullName, m));
            who.setUserName(apply(schema.accountSshUserName, m));
            if (schema.accountEmailAddress != null) {
                who.setEmailAddress(apply(schema.accountEmailAddress, m));
            } else if (emailExpander.canExpand(username)) {
                // If LDAP cannot give us a valid email address for this user
                // try expanding it through the older email expander code which
                // assumes a user name within a domain.
                //
                who.setEmailAddress(emailExpander.expand(username));
            }
            //
            if (fetchMemberOfEagerly || mandatoryGroup != null) {
                Set<AccountGroup.UUID> groups = helper.queryForGroups(ctx, username, m);
                if (mandatoryGroup != null) {
                    GroupReference mandatoryGroupRef = GroupBackends.findExactSuggestion(groupBackend, mandatoryGroup);
                    if (mandatoryGroupRef == null) {
                        throw new AccountException("Could not identify mandatory group: " + mandatoryGroup);
                    }
                    if (!groups.contains(mandatoryGroupRef.getUUID())) {
                        throw new AccountException("Not member of mandatory LDAP group: " + mandatoryGroupRef.getName());
                    }
                }
                // Regardless if we enabled fetchMemberOfEagerly, we already have the
                // groups and it would be a waste not to cache them.
                membershipCache.put(username, groups);
            }
            return who;
        } finally {
            try {
                ctx.close();
            } catch (NamingException e) {
                log.warn("Cannot close LDAP query handle", e);
            }
        }
    } catch (NamingException e) {
        log.error("Cannot query LDAP to authenticate user", e);
        throw new AuthenticationUnavailableException("Cannot query LDAP for account", e);
    } catch (LoginException e) {
        log.error("Cannot authenticate server via JAAS", e);
        throw new AuthenticationUnavailableException("Cannot query LDAP for account", e);
    }
}
Also used : AuthenticationUnavailableException(com.google.gerrit.server.auth.AuthenticationUnavailableException) ParameterizedString(com.google.gerrit.common.data.ParameterizedString) DirContext(javax.naming.directory.DirContext) AccountException(com.google.gerrit.server.account.AccountException) LoginException(javax.security.auth.login.LoginException) NamingException(javax.naming.NamingException) GroupReference(com.google.gerrit.common.data.GroupReference)

Example 20 with AccountException

use of com.google.gerrit.server.account.AccountException in project gerrit by GerritCodeReview.

the class OAuthRealm method authenticate.

/**
   * Authenticates with the {@link OAuthLoginProvider} specified in the authentication request.
   *
   * <p>{@link AccountManager} calls this method without password if authenticity of the user has
   * already been established. In that case we can skip the authentication request to the {@code
   * OAuthLoginService}.
   *
   * @param who the authentication request.
   * @return the authentication request with resolved email address and display name in case the
   *     authenticity of the user could be established; otherwise {@code who} is returned unchanged.
   * @throws AccountException if the authentication request with the OAuth2 server failed or no
   *     {@code OAuthLoginProvider} was available to handle the request.
   */
@Override
public AuthRequest authenticate(AuthRequest who) throws AccountException {
    if (Strings.isNullOrEmpty(who.getPassword())) {
        return who;
    }
    if (Strings.isNullOrEmpty(who.getAuthPlugin()) || Strings.isNullOrEmpty(who.getAuthProvider())) {
        throw new AccountException("Cannot authenticate");
    }
    OAuthLoginProvider loginProvider = loginProviders.get(who.getAuthPlugin(), who.getAuthProvider());
    if (loginProvider == null) {
        throw new AccountException("Cannot authenticate");
    }
    OAuthUserInfo userInfo;
    try {
        userInfo = loginProvider.login(who.getUserName(), who.getPassword());
    } catch (IOException e) {
        throw new AccountException("Cannot authenticate", e);
    }
    if (userInfo == null) {
        throw new AccountException("Cannot authenticate");
    }
    if (!Strings.isNullOrEmpty(userInfo.getEmailAddress()) && (Strings.isNullOrEmpty(who.getUserName()) || !allowsEdit(AccountFieldName.REGISTER_NEW_EMAIL))) {
        who.setEmailAddress(userInfo.getEmailAddress());
    }
    if (!Strings.isNullOrEmpty(userInfo.getDisplayName()) && (Strings.isNullOrEmpty(who.getDisplayName()) || !allowsEdit(AccountFieldName.FULL_NAME))) {
        who.setDisplayName(userInfo.getDisplayName());
    }
    return who;
}
Also used : AccountException(com.google.gerrit.server.account.AccountException) OAuthUserInfo(com.google.gerrit.extensions.auth.oauth.OAuthUserInfo) IOException(java.io.IOException) OAuthLoginProvider(com.google.gerrit.extensions.auth.oauth.OAuthLoginProvider)

Aggregations

AccountException (com.google.gerrit.server.account.AccountException)36 AuthRequest (com.google.gerrit.server.account.AuthRequest)19 Account (com.google.gerrit.entities.Account)12 ExternalId (com.google.gerrit.server.account.externalids.ExternalId)11 Test (org.junit.Test)10 AbstractDaemonTest (com.google.gerrit.acceptance.AbstractDaemonTest)9 AuthResult (com.google.gerrit.server.account.AuthResult)7 ParameterizedString (com.google.gerrit.common.data.ParameterizedString)6 AccountState (com.google.gerrit.server.account.AccountState)5 IOException (java.io.IOException)5 AuthException (com.google.gerrit.extensions.restapi.AuthException)4 AuthenticationUnavailableException (com.google.gerrit.server.auth.AuthenticationUnavailableException)4 HashMap (java.util.HashMap)4 ResourceConflictException (com.google.gerrit.extensions.restapi.ResourceConflictException)3 UnprocessableEntityException (com.google.gerrit.extensions.restapi.UnprocessableEntityException)3 CurrentUser (com.google.gerrit.server.CurrentUser)3 NamingException (javax.naming.NamingException)3 DirContext (javax.naming.directory.DirContext)3 LoginException (javax.security.auth.login.LoginException)3 OAuthLoginProvider (com.google.gerrit.extensions.auth.oauth.OAuthLoginProvider)2