Search in sources :

Example 26 with AccountException

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

the class HttpLoginServlet method doGet.

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse rsp) throws ServletException, IOException {
    final String token = LoginUrlToken.getToken(req);
    CacheHeaders.setNotCacheable(rsp);
    final String user = authFilter.getRemoteUser(req);
    if (user == null || "".equals(user)) {
        logger.atSevere().log("Unable to authenticate user by %s request header." + " Check container or server configuration.", authFilter.getLoginHeader());
        final Document doc = // 
        HtmlDomUtil.parseFile(HttpLoginServlet.class, "ConfigurationError.html");
        replace(doc, "loginHeader", authFilter.getLoginHeader());
        replace(doc, "ServerName", req.getServerName());
        replace(doc, "ServerPort", ":" + req.getServerPort());
        replace(doc, "ContextPath", req.getContextPath());
        final byte[] bin = HtmlDomUtil.toUTF8(doc);
        rsp.setStatus(HttpServletResponse.SC_FORBIDDEN);
        rsp.setContentType("text/html");
        rsp.setCharacterEncoding(UTF_8.name());
        rsp.setContentLength(bin.length);
        try (ServletOutputStream out = rsp.getOutputStream()) {
            out.write(bin);
        }
        return;
    }
    final AuthRequest areq = authRequestFactory.createForUser(user);
    areq.setDisplayName(authFilter.getRemoteDisplayname(req));
    areq.setEmailAddress(authFilter.getRemoteEmail(req));
    final AuthResult arsp;
    try {
        arsp = accountManager.authenticate(areq);
    } catch (AccountException e) {
        logger.atSevere().withCause(e).log("Unable to authenticate user \"%s\"", user);
        rsp.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }
    String remoteExternalId = authFilter.getRemoteExternalIdToken(req);
    if (remoteExternalId != null) {
        try {
            logger.atFine().log("Associating external identity \"%s\" to user \"%s\"", remoteExternalId, user);
            updateRemoteExternalId(arsp, remoteExternalId);
        } catch (AccountException | ConfigInvalidException e) {
            logger.atSevere().withCause(e).log("Unable to associate external identity \"%s\" to user \"%s\"", remoteExternalId, user);
            rsp.sendError(HttpServletResponse.SC_FORBIDDEN);
            return;
        }
    }
    final StringBuilder rdr = new StringBuilder();
    if (arsp.isNew() && authConfig.getRegisterPageUrl() != null) {
        rdr.append(authConfig.getRegisterPageUrl());
    } else {
        rdr.append(urlProvider.get(req));
        if (arsp.isNew() && !token.startsWith(PageLinks.REGISTER + "/")) {
            rdr.append('#' + PageLinks.REGISTER);
        }
        rdr.append(token);
    }
    webSession.get().login(arsp, true);
    rsp.sendRedirect(rdr.toString());
}
Also used : AuthRequest(com.google.gerrit.server.account.AuthRequest) AccountException(com.google.gerrit.server.account.AccountException) ConfigInvalidException(org.eclipse.jgit.errors.ConfigInvalidException) ServletOutputStream(javax.servlet.ServletOutputStream) AuthResult(com.google.gerrit.server.account.AuthResult) Document(org.w3c.dom.Document)

Example 27 with AccountException

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

the class ProjectOAuthFilter method verify.

private boolean verify(HttpServletRequest req, Response rsp) throws IOException {
    AuthInfo authInfo;
    // first check if there is a BASIC authentication header
    String hdr = req.getHeader(AUTHORIZATION);
    if (hdr != null && hdr.startsWith(BASIC)) {
        authInfo = extractAuthInfo(hdr, encoding(req));
        if (authInfo == null) {
            rsp.sendError(SC_UNAUTHORIZED);
            return false;
        }
    } else {
        // if there is no BASIC authentication header, check if there is
        // a cookie starting with the prefix "git-"
        Cookie cookie = findGitCookie(req);
        if (cookie != null) {
            authInfo = extractAuthInfo(cookie);
            if (authInfo == null) {
                rsp.sendError(SC_UNAUTHORIZED);
                return false;
            }
        } else {
            // an anonymous connection, or there might be a session cookie
            return true;
        }
    }
    // if there is authentication information but no secret => 401
    if (Strings.isNullOrEmpty(authInfo.tokenOrSecret)) {
        rsp.sendError(SC_UNAUTHORIZED);
        return false;
    }
    Optional<AccountState> who = accountCache.getByUsername(authInfo.username).filter(a -> a.account().isActive());
    if (!who.isPresent()) {
        logger.atWarning().log("%s: account inactive or not provisioned in Gerrit", authenticationFailedMsg(authInfo.username, req));
        rsp.sendError(SC_UNAUTHORIZED);
        return false;
    }
    Account account = who.get().account();
    AuthRequest authRequest = authRequestFactory.createForExternalUser(authInfo.username);
    authRequest.setEmailAddress(account.preferredEmail());
    authRequest.setDisplayName(account.fullName());
    authRequest.setPassword(authInfo.tokenOrSecret);
    authRequest.setAuthPlugin(authInfo.pluginName);
    authRequest.setAuthProvider(authInfo.exportName);
    try {
        AuthResult authResult = accountManager.authenticate(authRequest);
        WebSession ws = session.get();
        ws.setUserAccountId(authResult.getAccountId());
        ws.setAccessPathOk(AccessPath.GIT, true);
        ws.setAccessPathOk(AccessPath.REST_API, true);
        return true;
    } catch (AccountException e) {
        logger.atWarning().withCause(e).log("%s", authenticationFailedMsg(authInfo.username, req));
        rsp.sendError(SC_UNAUTHORIZED);
        return false;
    }
}
Also used : Cookie(javax.servlet.http.Cookie) Account(com.google.gerrit.entities.Account) AuthRequest(com.google.gerrit.server.account.AuthRequest) AccountException(com.google.gerrit.server.account.AccountException) AuthResult(com.google.gerrit.server.account.AuthResult) AccountState(com.google.gerrit.server.account.AccountState)

Example 28 with AccountException

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

the class ConfirmEmail method apply.

@Override
public Response<?> apply(ConfigResource rsrc, Input input) throws AuthException, UnprocessableEntityException, IOException, ConfigInvalidException {
    CurrentUser user = self.get();
    if (!user.isIdentifiedUser()) {
        throw new AuthException("Authentication required");
    }
    if (input == null) {
        input = new Input();
    }
    if (input.token == null) {
        throw new UnprocessableEntityException("missing token");
    }
    try {
        EmailTokenVerifier.ParsedToken token = emailTokenVerifier.decode(input.token);
        Account.Id accId = user.getAccountId();
        if (accId.equals(token.getAccountId())) {
            accountManager.link(accId, token.toAuthRequest());
            return Response.none();
        }
        throw new UnprocessableEntityException("invalid token");
    } catch (EmailTokenVerifier.InvalidTokenException e) {
        throw new UnprocessableEntityException("invalid token", e);
    } catch (AccountException e) {
        throw new UnprocessableEntityException(e.getMessage());
    }
}
Also used : UnprocessableEntityException(com.google.gerrit.extensions.restapi.UnprocessableEntityException) Account(com.google.gerrit.entities.Account) Input(com.google.gerrit.server.restapi.config.ConfirmEmail.Input) DefaultInput(com.google.gerrit.extensions.restapi.DefaultInput) EmailTokenVerifier(com.google.gerrit.server.mail.EmailTokenVerifier) CurrentUser(com.google.gerrit.server.CurrentUser) AccountException(com.google.gerrit.server.account.AccountException) AuthException(com.google.gerrit.extensions.restapi.AuthException)

Example 29 with AccountException

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

the class OAuthSession method authenticateAndRedirect.

private void authenticateAndRedirect(HttpServletRequest req, HttpServletResponse rsp, OAuthToken token) throws IOException {
    AuthRequest areq = authRequestFactory.create(externalIdKeyFactory.parse(user.getExternalId()));
    AuthResult arsp;
    try {
        String claimedIdentifier = user.getClaimedIdentity();
        if (!Strings.isNullOrEmpty(claimedIdentifier)) {
            if (!authenticateWithIdentityClaimedDuringHandshake(areq, rsp, claimedIdentifier)) {
                return;
            }
        } else if (linkMode) {
            if (!authenticateWithLinkedIdentity(areq, rsp)) {
                return;
            }
        }
        areq.setUserName(user.getUserName());
        areq.setEmailAddress(user.getEmailAddress());
        areq.setDisplayName(user.getDisplayName());
        arsp = accountManager.authenticate(areq);
        accountId = arsp.getAccountId();
        tokenCache.put(accountId, token);
    } 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);
    String suffix = redirectToken.substring(OAuthWebFilter.GERRIT_LOGIN.length() + 1);
    suffix = CharMatcher.anyOf("/").trimLeadingFrom(Url.decode(suffix));
    StringBuilder rdr = new StringBuilder(urlProvider.get(req));
    rdr.append(suffix);
    rsp.sendRedirect(rdr.toString());
}
Also used : AuthRequest(com.google.gerrit.server.account.AuthRequest) AccountException(com.google.gerrit.server.account.AccountException) AuthResult(com.google.gerrit.server.account.AuthResult)

Example 30 with AccountException

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

the class CreateEmail method apply.

/**
 * To be used from plugins that want to create emails without permission checks.
 */
@UsedAt(UsedAt.Project.PLUGIN_SERVICEUSER)
public EmailInfo apply(IdentifiedUser user, IdString id, EmailInput input) throws RestApiException, EmailException, MethodNotAllowedException, IOException, ConfigInvalidException, PermissionBackendException {
    String email = id.get().trim();
    if (input == null) {
        input = new EmailInput();
    }
    if (input.email != null && !email.equals(input.email)) {
        throw new BadRequestException("email address must match URL");
    }
    if (!validator.isValid(email)) {
        throw new BadRequestException("invalid email address");
    }
    EmailInfo info = new EmailInfo();
    info.email = email;
    if (input.noConfirmation || isDevMode) {
        if (isDevMode) {
            logger.atWarning().log("skipping email validation in developer mode");
        }
        try {
            accountManager.link(user.getAccountId(), authRequestFactory.createForEmail(email));
        } catch (AccountException e) {
            throw new ResourceConflictException(e.getMessage());
        }
        if (input.preferred) {
            putPreferred.apply(new AccountResource.Email(user, email), null);
            info.preferred = true;
        }
    } else {
        try {
            RegisterNewEmailSender emailSender = registerNewEmailFactory.create(email);
            if (!emailSender.isAllowed()) {
                throw new MethodNotAllowedException("Not allowed to add email address " + email);
            }
            emailSender.setMessageId(messageIdGenerator.fromAccountUpdate(user.getAccountId()));
            emailSender.send();
            info.pendingConfirmation = true;
        } catch (EmailException | RuntimeException e) {
            logger.atSevere().withCause(e).log("Cannot send email verification message to %s", email);
            throw e;
        }
    }
    return info;
}
Also used : MethodNotAllowedException(com.google.gerrit.extensions.restapi.MethodNotAllowedException) IdString(com.google.gerrit.extensions.restapi.IdString) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) AccountResource(com.google.gerrit.server.account.AccountResource) AccountException(com.google.gerrit.server.account.AccountException) RegisterNewEmailSender(com.google.gerrit.server.mail.send.RegisterNewEmailSender) EmailException(com.google.gerrit.exceptions.EmailException) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) EmailInfo(com.google.gerrit.extensions.common.EmailInfo) EmailInput(com.google.gerrit.extensions.api.accounts.EmailInput) UsedAt(com.google.gerrit.common.UsedAt)

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