Search in sources :

Example 51 with Account

use of com.google.gerrit.reviewdb.client.Account in project gerrit by GerritCodeReview.

the class GerritGSSAuthenticator method validateIdentity.

@Override
public boolean validateIdentity(final ServerSession session, final String identity) {
    final SshSession sd = session.getAttribute(SshSession.KEY);
    int at = identity.indexOf('@');
    String username;
    if (at == -1) {
        username = identity;
    } else {
        username = identity.substring(0, at);
    }
    if (config.getBoolean("auth", "userNameToLowerCase", false)) {
        username = username.toLowerCase(Locale.US);
    }
    AccountState state = accounts.getByUsername(username);
    Account account = state == null ? null : state.getAccount();
    boolean active = account != null && account.isActive();
    if (active) {
        return SshUtil.success(username, session, sshScope, sshLog, sd, SshUtil.createUser(sd, userFactory, account.getId()));
    }
    return false;
}
Also used : Account(com.google.gerrit.reviewdb.client.Account) AccountState(com.google.gerrit.server.account.AccountState)

Example 52 with Account

use of com.google.gerrit.reviewdb.client.Account in project gerrit by GerritCodeReview.

the class AbstractQueryAccountsTest method reindex.

// reindex permissions are tested by {@link AccountIT#reindexPermissions}
@Test
public void reindex() throws Exception {
    AccountInfo user1 = newAccountWithFullName("tester", "Test Usre");
    // update account in the database so that account index is stale
    String newName = "Test User";
    Account account = db.accounts().get(new Account.Id(user1._accountId));
    account.setFullName(newName);
    db.accounts().update(Collections.singleton(account));
    assertQuery("name:" + quote(user1.name), user1);
    assertQuery("name:" + quote(newName));
    gApi.accounts().id(user1.username).index();
    assertQuery("name:" + quote(user1.name));
    assertQuery("name:" + quote(newName), user1);
}
Also used : Account(com.google.gerrit.reviewdb.client.Account) AccountInfo(com.google.gerrit.extensions.common.AccountInfo) Test(org.junit.Test)

Example 53 with Account

use of com.google.gerrit.reviewdb.client.Account in project gerrit by GerritCodeReview.

the class AbstractQueryAccountsTest method createAccount.

private Account.Id createAccount(String username, String fullName, String email, boolean active) throws Exception {
    try (ManualRequestContext ctx = oneOffRequestContext.open()) {
        Account.Id id = accountManager.authenticate(AuthRequest.forUser(username)).getAccountId();
        if (email != null) {
            accountManager.link(id, AuthRequest.forEmail(email));
        }
        Account a = db.accounts().get(id);
        a.setFullName(fullName);
        a.setPreferredEmail(email);
        a.setActive(active);
        db.accounts().update(ImmutableList.of(a));
        accountCache.evict(id);
        return id;
    }
}
Also used : Account(com.google.gerrit.reviewdb.client.Account) ManualRequestContext(com.google.gerrit.server.util.ManualRequestContext)

Example 54 with Account

use of com.google.gerrit.reviewdb.client.Account in project gerrit by GerritCodeReview.

the class OutgoingEmail method send.

/**
   * Format and enqueue the message for delivery.
   *
   * @throws EmailException
   */
public void send() throws EmailException {
    if (NotifyHandling.NONE.equals(notify) && accountsToNotify.isEmpty()) {
        return;
    }
    if (!args.emailSender.isEnabled()) {
        //
        return;
    }
    init();
    if (useHtml()) {
        appendHtml(soyHtmlTemplate("HeaderHtml"));
    }
    format();
    appendText(textTemplate("Footer"));
    if (useHtml()) {
        appendHtml(soyHtmlTemplate("FooterHtml"));
    }
    Set<Address> smtpRcptToPlaintextOnly = new HashSet<>();
    if (shouldSendMessage()) {
        if (fromId != null) {
            final Account fromUser = args.accountCache.get(fromId).getAccount();
            GeneralPreferencesInfo senderPrefs = fromUser.getGeneralPreferencesInfo();
            if (senderPrefs != null && senderPrefs.getEmailStrategy() == CC_ON_OWN_COMMENTS) {
                // If we are impersonating a user, make sure they receive a CC of
                // this message so they can always review and audit what we sent
                // on their behalf to others.
                //
                add(RecipientType.CC, fromId);
            } else if (!accountsToNotify.containsValue(fromId) && rcptTo.remove(fromId)) {
                // If they don't want a copy, but we queued one up anyway,
                // drop them from the recipient lists.
                //
                removeUser(fromUser);
            }
        }
        // In addition, check if users only want to receive plaintext email.
        for (Account.Id id : rcptTo) {
            Account thisUser = args.accountCache.get(id).getAccount();
            GeneralPreferencesInfo prefs = thisUser.getGeneralPreferencesInfo();
            if (prefs == null || prefs.getEmailStrategy() == DISABLED) {
                removeUser(thisUser);
            } else if (useHtml() && prefs.getEmailFormat() == EmailFormat.PLAINTEXT) {
                removeUser(thisUser);
                smtpRcptToPlaintextOnly.add(new Address(thisUser.getFullName(), thisUser.getPreferredEmail()));
            }
            if (smtpRcptTo.isEmpty() && smtpRcptToPlaintextOnly.isEmpty()) {
                return;
            }
        }
        // inbound email replies.
        if (!headers.containsKey("Reply-To")) {
            StringJoiner j = new StringJoiner(", ");
            if (fromId != null) {
                Address address = toAddress(fromId);
                if (address != null) {
                    j.add(address.getEmail());
                }
            }
            smtpRcptTo.stream().forEach(a -> j.add(a.getEmail()));
            smtpRcptToPlaintextOnly.stream().forEach(a -> j.add(a.getEmail()));
            setHeader("Reply-To", j.toString());
        }
        String textPart = textBody.toString();
        OutgoingEmailValidationListener.Args va = new OutgoingEmailValidationListener.Args();
        va.messageClass = messageClass;
        va.smtpFromAddress = smtpFromAddress;
        va.smtpRcptTo = smtpRcptTo;
        va.headers = headers;
        va.body = textPart;
        if (useHtml()) {
            va.htmlBody = htmlBody.toString();
        } else {
            va.htmlBody = null;
        }
        for (OutgoingEmailValidationListener validator : args.outgoingEmailValidationListeners) {
            try {
                validator.validateOutgoingEmail(va);
            } catch (ValidationException e) {
                return;
            }
        }
        if (!smtpRcptTo.isEmpty()) {
            // Send multipart message
            args.emailSender.send(va.smtpFromAddress, va.smtpRcptTo, va.headers, va.body, va.htmlBody);
        }
        if (!smtpRcptToPlaintextOnly.isEmpty()) {
            // Send plaintext message
            Map<String, EmailHeader> shallowCopy = new HashMap<>();
            shallowCopy.putAll(headers);
            // Remove To and Cc
            shallowCopy.remove(HDR_TO);
            shallowCopy.remove(HDR_CC);
            for (Address a : smtpRcptToPlaintextOnly) {
                // Add new To
                EmailHeader.AddressList to = new EmailHeader.AddressList();
                to.add(a);
                shallowCopy.put(HDR_TO, to);
            }
            args.emailSender.send(va.smtpFromAddress, smtpRcptToPlaintextOnly, shallowCopy, va.body);
        }
    }
}
Also used : Account(com.google.gerrit.reviewdb.client.Account) ValidationException(com.google.gerrit.server.validators.ValidationException) Address(com.google.gerrit.server.mail.Address) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) OutgoingEmailValidationListener(com.google.gerrit.server.validators.OutgoingEmailValidationListener) AddressList(com.google.gerrit.server.mail.send.EmailHeader.AddressList) GeneralPreferencesInfo(com.google.gerrit.extensions.client.GeneralPreferencesInfo) AddressList(com.google.gerrit.server.mail.send.EmailHeader.AddressList) StringJoiner(java.util.StringJoiner) HashSet(java.util.HashSet)

Example 55 with Account

use of com.google.gerrit.reviewdb.client.Account in project gerrit by GerritCodeReview.

the class MailProcessor method processImpl.

private void processImpl(BatchUpdate.Factory buf, MailMessage message) throws OrmException, UpdateException, RestApiException {
    for (DynamicMap.Entry<MailFilter> filter : mailFilters) {
        if (!filter.getProvider().get().shouldProcessMessage(message)) {
            log.warn(String.format("Message %s filtered by plugin %s %s. Will delete message.", message.id(), filter.getPluginName(), filter.getExportName()));
            return;
        }
    }
    MailMetadata metadata = MetadataParser.parse(message);
    if (!metadata.hasRequiredFields()) {
        log.error(String.format("Message %s is missing required metadata, have %s. Will delete message.", message.id(), metadata));
        return;
    }
    Set<Account.Id> accounts = accountByEmailCache.get(metadata.author);
    if (accounts.size() != 1) {
        log.error(String.format("Address %s could not be matched to a unique account. It was matched to %s. Will delete message.", metadata.author, accounts));
        return;
    }
    Account.Id account = accounts.iterator().next();
    if (!accountCache.get(account).getAccount().isActive()) {
        log.warn(String.format("Mail: Account %s is inactive. Will delete message.", account));
        return;
    }
    try (ManualRequestContext ctx = oneOffRequestContext.openAs(account)) {
        List<ChangeData> changeDataList = queryProvider.get().byKey(Change.Key.parse(metadata.changeId));
        if (changeDataList.size() != 1) {
            log.error(String.format("Message %s references unique change %s, but there are %d matching changes in the index. Will delete message.", message.id(), metadata.changeId, changeDataList.size()));
            return;
        }
        ChangeData cd = changeDataList.get(0);
        if (existingMessageIds(cd).contains(message.id())) {
            log.info("Message " + message.id() + " was already processed. Will delete message.");
            return;
        }
        // Get all comments; filter and sort them to get the original list of
        // comments from the outbound email.
        // TODO(hiesel) Also filter by original comment author.
        Collection<Comment> comments = cd.publishedComments().stream().filter(c -> (c.writtenOn.getTime() / 1000) == (metadata.timestamp.getTime() / 1000)).sorted(CommentsUtil.COMMENT_ORDER).collect(toList());
        Project.NameKey project = cd.project();
        String changeUrl = canonicalUrl.get() + "#/c/" + cd.getId().get();
        List<MailComment> parsedComments;
        if (useHtmlParser(message)) {
            parsedComments = HtmlParser.parse(message, comments, changeUrl);
        } else {
            parsedComments = TextParser.parse(message, comments, changeUrl);
        }
        if (parsedComments.isEmpty()) {
            log.warn("Could not parse any comments from " + message.id() + ". Will delete message.");
            return;
        }
        Op o = new Op(new PatchSet.Id(cd.getId(), metadata.patchSet), parsedComments, message.id());
        BatchUpdate batchUpdate = buf.create(cd.db(), project, ctx.getUser(), TimeUtil.nowTs());
        batchUpdate.addOp(cd.getId(), o);
        batchUpdate.execute();
    }
}
Also used : MailFilter(com.google.gerrit.server.mail.MailFilter) Account(com.google.gerrit.reviewdb.client.Account) Comment(com.google.gerrit.reviewdb.client.Comment) BatchUpdateOp(com.google.gerrit.server.update.BatchUpdateOp) PatchSet(com.google.gerrit.reviewdb.client.PatchSet) ChangeData(com.google.gerrit.server.query.change.ChangeData) BatchUpdate(com.google.gerrit.server.update.BatchUpdate) Project(com.google.gerrit.reviewdb.client.Project) DynamicMap(com.google.gerrit.extensions.registration.DynamicMap) ManualRequestContext(com.google.gerrit.server.util.ManualRequestContext)

Aggregations

Account (com.google.gerrit.reviewdb.client.Account)75 ArrayList (java.util.ArrayList)13 OrmException (com.google.gwtorm.server.OrmException)11 AccountGroup (com.google.gerrit.reviewdb.client.AccountGroup)10 ReviewDb (com.google.gerrit.reviewdb.server.ReviewDb)10 AuthException (com.google.gerrit.extensions.restapi.AuthException)8 ExternalId (com.google.gerrit.server.account.externalids.ExternalId)8 HashSet (java.util.HashSet)8 ResourceNotFoundException (com.google.gerrit.extensions.restapi.ResourceNotFoundException)7 AccountGroupMember (com.google.gerrit.reviewdb.client.AccountGroupMember)7 IdentifiedUser (com.google.gerrit.server.IdentifiedUser)7 PersonIdent (org.eclipse.jgit.lib.PersonIdent)7 BadRequestException (com.google.gerrit.extensions.restapi.BadRequestException)6 UnprocessableEntityException (com.google.gerrit.extensions.restapi.UnprocessableEntityException)6 CurrentUser (com.google.gerrit.server.CurrentUser)6 Ref (org.eclipse.jgit.lib.Ref)6 ResourceConflictException (com.google.gerrit.extensions.restapi.ResourceConflictException)5 IOException (java.io.IOException)5 Test (org.junit.Test)5 MethodNotAllowedException (com.google.gerrit.extensions.restapi.MethodNotAllowedException)4