Search in sources :

Example 6 with AccountException

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

the class LdapLoginServlet method doPost.

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    req.setCharacterEncoding(UTF_8.name());
    String username = Strings.nullToEmpty(req.getParameter("username")).trim();
    String password = Strings.nullToEmpty(req.getParameter("password"));
    String remember = Strings.nullToEmpty(req.getParameter("rememberme"));
    if (username.isEmpty() || password.isEmpty()) {
        sendForm(req, res, "Invalid username or password.");
        return;
    }
    AuthRequest areq = authRequestFactory.createForUser(username);
    areq.setPassword(password);
    AuthResult ares;
    try {
        ares = accountManager.authenticate(areq);
    } catch (AccountUserNameException e) {
        sendForm(req, res, e.getMessage());
        return;
    } catch (AuthenticationUnavailableException e) {
        sendForm(req, res, "Authentication unavailable at this time.");
        return;
    } catch (AuthenticationFailedException e) {
        // This exception is thrown if the user provided wrong credentials, we don't need to log a
        // stacktrace for it.
        logger.atWarning().log("'%s' failed to sign in: %s", username, e.getMessage());
        sendForm(req, res, "Invalid username or password.");
        return;
    } catch (AccountException e) {
        logger.atWarning().withCause(e).log("'%s' failed to sign in", username);
        sendForm(req, res, "Authentication failed.");
        return;
    } catch (RuntimeException e) {
        logger.atSevere().withCause(e).log("LDAP authentication failed");
        sendForm(req, res, "Authentication unavailable at this time.");
        return;
    }
    StringBuilder dest = new StringBuilder();
    dest.append(urlProvider.get(req));
    dest.append(LoginUrlToken.getToken(req));
    CacheHeaders.setNotCacheable(res);
    webSession.get().login(ares, "1".equals(remember));
    res.sendRedirect(dest.toString());
}
Also used : AuthRequest(com.google.gerrit.server.account.AuthRequest) AccountUserNameException(com.google.gerrit.server.account.AccountUserNameException) AuthenticationUnavailableException(com.google.gerrit.server.auth.AuthenticationUnavailableException) AccountException(com.google.gerrit.server.account.AccountException) AuthenticationFailedException(com.google.gerrit.server.account.AuthenticationFailedException) AuthResult(com.google.gerrit.server.account.AuthResult)

Example 7 with AccountException

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

the class OAuthSessionOverOpenID method authenticateAndRedirect.

private void authenticateAndRedirect(HttpServletRequest req, HttpServletResponse rsp) throws IOException {
    com.google.gerrit.server.account.AuthRequest areq = authRequestFactory.create(externalIdKeyFactory.parse(user.getExternalId()));
    AuthResult arsp;
    try {
        String claimedIdentifier = user.getClaimedIdentity();
        Optional<Account.Id> actualId = accountManager.lookup(user.getExternalId());
        Optional<Account.Id> claimedId = Optional.empty();
        // That why we query it here, not to lose linking mode.
        if (!Strings.isNullOrEmpty(claimedIdentifier)) {
            claimedId = accountManager.lookup(claimedIdentifier);
            if (!claimedId.isPresent()) {
                logger.atFine().log("Claimed identity is unknown");
            }
        }
        // and user account exists for this identity
        if (claimedId.isPresent()) {
            logger.atFine().log("Claimed identity is set and is known");
            if (actualId.isPresent()) {
                if (claimedId.get().equals(actualId.get())) {
                    // Both link to the same account, that's what we expected.
                    logger.atFine().log("Both link to the same account. All is fine.");
                } else {
                    // This is (for now) a fatal error. There are two records
                    // for what might be the same user. The admin would have to
                    // link the accounts manually.
                    logger.atFine().log("OAuth accounts disagree over user identity:\n" + "  Claimed ID: %s is %s\n" + "  Delgate ID: %s is %s", claimedId.get(), claimedIdentifier, actualId.get(), user.getExternalId());
                    rsp.sendError(HttpServletResponse.SC_FORBIDDEN);
                    return;
                }
            } else {
                // Claimed account already exists: link to it.
                logger.atFine().log("Claimed account already exists: link to it.");
                try {
                    accountManager.link(claimedId.get(), areq);
                } catch (ConfigInvalidException e) {
                    logger.atSevere().log("Cannot link: %s to user identity:\n  Claimed ID: %s is %s", user.getExternalId(), claimedId.get(), claimedIdentifier);
                    rsp.sendError(HttpServletResponse.SC_FORBIDDEN);
                    return;
                }
            }
        } else if (linkMode) {
            // Use case 2: link mode activated from the UI
            Account.Id accountId = identifiedUser.get().getAccountId();
            try {
                logger.atFine().log("Linking \"%s\" to \"%s\"", user.getExternalId(), accountId);
                accountManager.link(accountId, areq);
            } catch (ConfigInvalidException e) {
                logger.atSevere().log("Cannot link: %s to user identity: %s", user.getExternalId(), accountId);
                rsp.sendError(HttpServletResponse.SC_FORBIDDEN);
                return;
            } finally {
                linkMode = false;
            }
        }
        areq.setUserName(user.getUserName());
        areq.setEmailAddress(user.getEmailAddress());
        areq.setDisplayName(user.getDisplayName());
        arsp = accountManager.authenticate(areq);
    } catch (AccountException e) {
        logger.atSevere().withCause(e).log("Unable to authenticate user \"%s\"", user);
        rsp.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }
    webSession.get().login(arsp, true);
    StringBuilder rdr = new StringBuilder(urlProvider.get(req));
    rdr.append(Url.decode(redirectToken));
    rsp.sendRedirect(rdr.toString());
}
Also used : ConfigInvalidException(org.eclipse.jgit.errors.ConfigInvalidException) AccountException(com.google.gerrit.server.account.AccountException) AuthRequest(com.google.gerrit.server.account.AuthRequest) AuthResult(com.google.gerrit.server.account.AuthResult)

Example 8 with AccountException

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

the class ProjectBasicAuthFilter method verify.

private boolean verify(HttpServletRequest req, Response rsp) throws IOException {
    final String hdr = req.getHeader(AUTHORIZATION);
    if (hdr == null || !hdr.startsWith(LIT_BASIC)) {
        // session cookie instead of basic authentication.
        return true;
    }
    final byte[] decoded = BaseEncoding.base64().decode(hdr.substring(LIT_BASIC.length()));
    String usernamePassword = new String(decoded, encoding(req));
    int splitPos = usernamePassword.indexOf(':');
    if (splitPos < 1) {
        rsp.sendError(SC_UNAUTHORIZED);
        return false;
    }
    String username = usernamePassword.substring(0, splitPos);
    String password = usernamePassword.substring(splitPos + 1);
    if (Strings.isNullOrEmpty(password)) {
        rsp.sendError(SC_UNAUTHORIZED);
        return false;
    }
    if (authConfig.isUserNameToLowerCase()) {
        username = username.toLowerCase(Locale.US);
    }
    Optional<AccountState> accountState = accountCache.getByUsername(username).filter(a -> a.account().isActive());
    if (!accountState.isPresent()) {
        logger.atWarning().log("Authentication failed for %s: account inactive or not provisioned in Gerrit", username);
        rsp.sendError(SC_UNAUTHORIZED);
        return false;
    }
    AccountState who = accountState.get();
    GitBasicAuthPolicy gitBasicAuthPolicy = authConfig.getGitBasicAuthPolicy();
    if (gitBasicAuthPolicy == GitBasicAuthPolicy.HTTP || gitBasicAuthPolicy == GitBasicAuthPolicy.HTTP_LDAP) {
        if (passwordVerifier.checkPassword(who.externalIds(), username, password)) {
            logger.atFine().log("HTTP:%s %s username/password authentication succeeded", req.getMethod(), req.getRequestURI());
            return succeedAuthentication(who, null);
        }
    }
    if (gitBasicAuthPolicy == GitBasicAuthPolicy.HTTP) {
        return failAuthentication(rsp, username, req);
    }
    AuthRequest whoAuth = authRequestFactory.createForUser(username);
    whoAuth.setPassword(password);
    try {
        AuthResult whoAuthResult = accountManager.authenticate(whoAuth);
        setUserIdentified(whoAuthResult.getAccountId(), whoAuthResult);
        logger.atFine().log("HTTP:%s %s Realm authentication succeeded", req.getMethod(), req.getRequestURI());
        return true;
    } catch (NoSuchUserException e) {
        if (passwordVerifier.checkPassword(who.externalIds(), username, password)) {
            return succeedAuthentication(who, null);
        }
        logger.atWarning().withCause(e).log("%s", authenticationFailedMsg(username, req));
        rsp.sendError(SC_UNAUTHORIZED);
        return false;
    } catch (AuthenticationFailedException e) {
        // This exception is thrown if the user provided wrong credentials, we don't need to log a
        // stacktrace for it.
        logger.atWarning().log(authenticationFailedMsg(username, req) + ": %s", e.getMessage());
        rsp.sendError(SC_UNAUTHORIZED);
        return false;
    } catch (AuthenticationUnavailableException e) {
        logger.atSevere().withCause(e).log("could not reach authentication backend");
        rsp.sendError(SC_SERVICE_UNAVAILABLE);
        return false;
    } catch (AccountException e) {
        logger.atWarning().withCause(e).log("%s", authenticationFailedMsg(username, req));
        rsp.sendError(SC_UNAUTHORIZED);
        return false;
    }
}
Also used : AuthRequest(com.google.gerrit.server.account.AuthRequest) AuthenticationUnavailableException(com.google.gerrit.server.auth.AuthenticationUnavailableException) AccountException(com.google.gerrit.server.account.AccountException) AuthenticationFailedException(com.google.gerrit.server.account.AuthenticationFailedException) NoSuchUserException(com.google.gerrit.server.auth.NoSuchUserException) GitBasicAuthPolicy(com.google.gerrit.extensions.client.GitBasicAuthPolicy) AuthResult(com.google.gerrit.server.account.AuthResult) AccountState(com.google.gerrit.server.account.AccountState)

Example 9 with AccountException

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

the class AddMembers method createAccountByLdap.

private Optional<Account> createAccountByLdap(String user) throws IOException {
    if (!ExternalId.isValidUsername(user)) {
        return Optional.empty();
    }
    try {
        AuthRequest req = authRequestFactory.createForUser(user);
        req.setSkipAuthentication(true);
        return accountCache.get(accountManager.authenticate(req).getAccountId()).map(AccountState::account);
    } catch (AccountException e) {
        return Optional.empty();
    }
}
Also used : AuthRequest(com.google.gerrit.server.account.AuthRequest) UnresolvableAccountException(com.google.gerrit.server.account.AccountResolver.UnresolvableAccountException) AccountException(com.google.gerrit.server.account.AccountException) AccountState(com.google.gerrit.server.account.AccountState)

Example 10 with AccountException

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

the class DeleteEmail method apply.

public Response<?> apply(IdentifiedUser user, String email) throws ResourceNotFoundException, ResourceConflictException, MethodNotAllowedException, IOException, ConfigInvalidException {
    Account.Id accountId = user.getAccountId();
    if (realm.accountBelongsToRealm(externalIds.byAccount(accountId)) && !realm.allowsEdit(AccountFieldName.REGISTER_NEW_EMAIL)) {
        throw new MethodNotAllowedException("realm does not allow deleting emails");
    }
    Set<ExternalId> extIds = externalIds.byAccount(accountId).stream().filter(e -> email.equals(e.email())).collect(toSet());
    if (extIds.isEmpty()) {
        throw new ResourceNotFoundException(email);
    }
    if (realm.accountBelongsToRealm(extIds)) {
        String errorMsg = String.format("Cannot remove e-mail '%s' which is directly associated with %s authentication", email, authType);
        throw new ResourceConflictException(errorMsg);
    }
    try {
        accountManager.unlink(user.getAccountId(), extIds.stream().map(ExternalId::key).collect(toSet()));
    } catch (AccountException e) {
        throw new ResourceConflictException(e.getMessage());
    }
    return Response.none();
}
Also used : ResourceNotFoundException(com.google.gerrit.extensions.restapi.ResourceNotFoundException) AuthType(com.google.gerrit.extensions.client.AuthType) PermissionBackendException(com.google.gerrit.server.permissions.PermissionBackendException) ConfigInvalidException(org.eclipse.jgit.errors.ConfigInvalidException) Inject(com.google.inject.Inject) Input(com.google.gerrit.extensions.common.Input) Response(com.google.gerrit.extensions.restapi.Response) PermissionBackend(com.google.gerrit.server.permissions.PermissionBackend) RestModifyView(com.google.gerrit.extensions.restapi.RestModifyView) AuthException(com.google.gerrit.extensions.restapi.AuthException) Collectors.toSet(java.util.stream.Collectors.toSet) GlobalPermission(com.google.gerrit.server.permissions.GlobalPermission) CurrentUser(com.google.gerrit.server.CurrentUser) AccountResource(com.google.gerrit.server.account.AccountResource) Account(com.google.gerrit.entities.Account) Set(java.util.Set) AccountFieldName(com.google.gerrit.extensions.client.AccountFieldName) IOException(java.io.IOException) MethodNotAllowedException(com.google.gerrit.extensions.restapi.MethodNotAllowedException) AccountException(com.google.gerrit.server.account.AccountException) ExternalIds(com.google.gerrit.server.account.externalids.ExternalIds) Provider(com.google.inject.Provider) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) IdentifiedUser(com.google.gerrit.server.IdentifiedUser) ExternalId(com.google.gerrit.server.account.externalids.ExternalId) AuthConfig(com.google.gerrit.server.config.AuthConfig) Realm(com.google.gerrit.server.account.Realm) AccountManager(com.google.gerrit.server.account.AccountManager) Singleton(com.google.inject.Singleton) Account(com.google.gerrit.entities.Account) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) MethodNotAllowedException(com.google.gerrit.extensions.restapi.MethodNotAllowedException) AccountException(com.google.gerrit.server.account.AccountException) ExternalId(com.google.gerrit.server.account.externalids.ExternalId) ResourceNotFoundException(com.google.gerrit.extensions.restapi.ResourceNotFoundException)

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