Search in sources :

Example 26 with Account

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

the class PostGpgKeys method apply.

@Override
public Map<String, GpgKeyInfo> apply(AccountResource rsrc, Input input) throws ResourceNotFoundException, BadRequestException, ResourceConflictException, PGPException, OrmException, IOException, ConfigInvalidException {
    GpgKeys.checkVisible(self, rsrc);
    Collection<ExternalId> existingExtIds = externalIds.byAccount(rsrc.getUser().getAccountId(), SCHEME_GPGKEY);
    try (PublicKeyStore store = storeProvider.get()) {
        Set<Fingerprint> toRemove = readKeysToRemove(input, existingExtIds);
        List<PGPPublicKeyRing> newKeys = readKeysToAdd(input, toRemove);
        List<ExternalId> newExtIds = new ArrayList<>(existingExtIds.size());
        for (PGPPublicKeyRing keyRing : newKeys) {
            PGPPublicKey key = keyRing.getPublicKey();
            ExternalId.Key extIdKey = toExtIdKey(key.getFingerprint());
            Account account = getAccountByExternalId(extIdKey);
            if (account != null) {
                if (!account.getId().equals(rsrc.getUser().getAccountId())) {
                    throw new ResourceConflictException("GPG key already associated with another account");
                }
            } else {
                newExtIds.add(ExternalId.create(extIdKey, rsrc.getUser().getAccountId()));
            }
        }
        storeKeys(rsrc, newKeys, toRemove);
        List<ExternalId.Key> extIdKeysToRemove = toRemove.stream().map(fp -> toExtIdKey(fp.get())).collect(toList());
        externalIdsUpdateFactory.create().replace(rsrc.getUser().getAccountId(), extIdKeysToRemove, newExtIds);
        accountCache.evict(rsrc.getUser().getAccountId());
        return toJson(newKeys, toRemove, store, rsrc.getUser());
    }
}
Also used : ResourceNotFoundException(com.google.gerrit.extensions.restapi.ResourceNotFoundException) OrmException(com.google.gwtorm.server.OrmException) PublicKeyStore.keyToString(com.google.gerrit.gpg.PublicKeyStore.keyToString) Inject(com.google.inject.Inject) LoggerFactory(org.slf4j.LoggerFactory) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) RestModifyView(com.google.gerrit.extensions.restapi.RestModifyView) ByteArrayInputStream(java.io.ByteArrayInputStream) GpgKeyInfo(com.google.gerrit.extensions.common.GpgKeyInfo) Map(java.util.Map) PGPPublicKeyRing(org.bouncycastle.openpgp.PGPPublicKeyRing) PGPException(org.bouncycastle.openpgp.PGPException) ImmutableSet(com.google.common.collect.ImmutableSet) Collection(java.util.Collection) Set(java.util.Set) RefUpdate(org.eclipse.jgit.lib.RefUpdate) PGPPublicKey(org.bouncycastle.openpgp.PGPPublicKey) SCHEME_GPGKEY(com.google.gerrit.server.account.externalids.ExternalId.SCHEME_GPGKEY) Sets(com.google.common.collect.Sets) ExternalIds(com.google.gerrit.server.account.externalids.ExternalIds) PersonIdent(org.eclipse.jgit.lib.PersonIdent) List(java.util.List) ExternalIdsUpdate(com.google.gerrit.server.account.externalids.ExternalIdsUpdate) Joiner(com.google.common.base.Joiner) Singleton(com.google.inject.Singleton) AccountCache(com.google.gerrit.server.account.AccountCache) ConfigInvalidException(org.eclipse.jgit.errors.ConfigInvalidException) PublicKeyStore(com.google.gerrit.gpg.PublicKeyStore) InternalAccountQuery(com.google.gerrit.server.query.account.InternalAccountQuery) GerritPublicKeyChecker(com.google.gerrit.gpg.GerritPublicKeyChecker) Fingerprint(com.google.gerrit.gpg.Fingerprint) ArrayList(java.util.ArrayList) Lists(com.google.common.collect.Lists) ImmutableList(com.google.common.collect.ImmutableList) Account(com.google.gerrit.reviewdb.client.Account) CommitBuilder(org.eclipse.jgit.lib.CommitBuilder) ArmoredInputStream(org.bouncycastle.bcpg.ArmoredInputStream) CheckResult(com.google.gerrit.gpg.CheckResult) Input(com.google.gerrit.gpg.server.PostGpgKeys.Input) CurrentUser(com.google.gerrit.server.CurrentUser) Logger(org.slf4j.Logger) BaseEncoding(com.google.common.io.BaseEncoding) UTF_8(java.nio.charset.StandardCharsets.UTF_8) AccountResource(com.google.gerrit.server.account.AccountResource) EmailException(com.google.gerrit.common.errors.EmailException) PublicKeyChecker(com.google.gerrit.gpg.PublicKeyChecker) IOException(java.io.IOException) Maps(com.google.common.collect.Maps) PublicKeyStore.keyIdToString(com.google.gerrit.gpg.PublicKeyStore.keyIdToString) Collectors.toList(java.util.stream.Collectors.toList) Provider(com.google.inject.Provider) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) IdentifiedUser(com.google.gerrit.server.IdentifiedUser) AddKeySender(com.google.gerrit.server.mail.send.AddKeySender) ExternalId(com.google.gerrit.server.account.externalids.ExternalId) AccountState(com.google.gerrit.server.account.AccountState) BcPGPObjectFactory(org.bouncycastle.openpgp.bc.BcPGPObjectFactory) GerritPersonIdent(com.google.gerrit.server.GerritPersonIdent) InputStream(java.io.InputStream) PGPPublicKeyRing(org.bouncycastle.openpgp.PGPPublicKeyRing) Account(com.google.gerrit.reviewdb.client.Account) Fingerprint(com.google.gerrit.gpg.Fingerprint) ExternalId(com.google.gerrit.server.account.externalids.ExternalId) ArrayList(java.util.ArrayList) PGPPublicKey(org.bouncycastle.openpgp.PGPPublicKey) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) PublicKeyStore(com.google.gerrit.gpg.PublicKeyStore) PGPPublicKey(org.bouncycastle.openpgp.PGPPublicKey)

Example 27 with Account

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

the class RunAsFilter method doFilter.

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse res = (HttpServletResponse) response;
    String runas = req.getHeader(RUN_AS);
    if (runas != null) {
        if (!enabled) {
            replyError(req, res, SC_FORBIDDEN, RUN_AS + " disabled by auth.enableRunAs = false", null);
            return;
        }
        CurrentUser self = session.get().getUser();
        try {
            if (!self.isIdentifiedUser()) {
                // because that would be crazy.
                throw new AuthException("denied");
            }
            permissionBackend.user(self).check(GlobalPermission.RUN_AS);
        } catch (AuthException e) {
            replyError(req, res, SC_FORBIDDEN, "not permitted to use " + RUN_AS, null);
            return;
        } catch (PermissionBackendException e) {
            log.warn("cannot check runAs", e);
            replyError(req, res, SC_INTERNAL_SERVER_ERROR, RUN_AS + " unavailable", null);
            return;
        }
        Account target;
        try {
            target = accountResolver.find(db.get(), runas);
        } catch (OrmException e) {
            log.warn("cannot resolve account for " + RUN_AS, e);
            replyError(req, res, SC_INTERNAL_SERVER_ERROR, "cannot resolve " + RUN_AS, e);
            return;
        }
        if (target == null) {
            replyError(req, res, SC_FORBIDDEN, "no account matches " + RUN_AS, null);
            return;
        }
        session.get().setUserAccountId(target.getId());
    }
    chain.doFilter(req, res);
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) Account(com.google.gerrit.reviewdb.client.Account) CurrentUser(com.google.gerrit.server.CurrentUser) OrmException(com.google.gwtorm.server.OrmException) HttpServletResponse(javax.servlet.http.HttpServletResponse) AuthException(com.google.gerrit.extensions.restapi.AuthException) PermissionBackendException(com.google.gerrit.server.permissions.PermissionBackendException)

Example 28 with Account

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

the class PutActive method apply.

@Override
public Response<String> apply(AccountResource rsrc, Input input) throws ResourceNotFoundException, OrmException, IOException {
    AtomicBoolean alreadyActive = new AtomicBoolean(false);
    Account a = dbProvider.get().accounts().atomicUpdate(rsrc.getUser().getAccountId(), new AtomicUpdate<Account>() {

        @Override
        public Account update(Account a) {
            if (a.isActive()) {
                alreadyActive.set(true);
            } else {
                a.setActive(true);
            }
            return a;
        }
    });
    if (a == null) {
        throw new ResourceNotFoundException("account not found");
    }
    byIdCache.evict(a.getId());
    return alreadyActive.get() ? Response.ok("") : Response.created("");
}
Also used : AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Account(com.google.gerrit.reviewdb.client.Account) ResourceNotFoundException(com.google.gerrit.extensions.restapi.ResourceNotFoundException)

Example 29 with Account

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

the class PutAgreement method apply.

@Override
public Response<String> apply(AccountResource resource, AgreementInput input) throws IOException, OrmException, RestApiException {
    if (!agreementsEnabled) {
        throw new MethodNotAllowedException("contributor agreements disabled");
    }
    if (self.get() != resource.getUser()) {
        throw new AuthException("not allowed to enter contributor agreement");
    }
    String agreementName = Strings.nullToEmpty(input.name);
    ContributorAgreement ca = projectCache.getAllProjects().getConfig().getContributorAgreement(agreementName);
    if (ca == null) {
        throw new UnprocessableEntityException("contributor agreement not found");
    }
    if (ca.getAutoVerify() == null) {
        throw new BadRequestException("cannot enter a non-autoVerify agreement");
    }
    AccountGroup.UUID uuid = ca.getAutoVerify().getUUID();
    if (uuid == null) {
        throw new ResourceConflictException("autoverify group uuid not found");
    }
    AccountGroup group = groupCache.get(uuid);
    if (group == null) {
        throw new ResourceConflictException("autoverify group not found");
    }
    Account account = self.get().getAccount();
    addMembers.addMembers(group.getId(), ImmutableList.of(account.getId()));
    agreementSignup.fire(account, agreementName);
    return Response.ok(agreementName);
}
Also used : UnprocessableEntityException(com.google.gerrit.extensions.restapi.UnprocessableEntityException) Account(com.google.gerrit.reviewdb.client.Account) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) MethodNotAllowedException(com.google.gerrit.extensions.restapi.MethodNotAllowedException) AccountGroup(com.google.gerrit.reviewdb.client.AccountGroup) ContributorAgreement(com.google.gerrit.common.data.ContributorAgreement) AuthException(com.google.gerrit.extensions.restapi.AuthException) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException)

Example 30 with Account

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

the class AccountManager method create.

private AuthResult create(ReviewDb db, AuthRequest who) throws OrmException, AccountException, IOException, ConfigInvalidException {
    Account.Id newId = new Account.Id(db.nextAccountId());
    Account account = new Account(newId, TimeUtil.nowTs());
    ExternalId extId = ExternalId.createWithEmail(who.getExternalIdKey(), newId, who.getEmailAddress());
    account.setFullName(who.getDisplayName());
    account.setPreferredEmail(extId.email());
    boolean isFirstAccount = awaitsFirstAccountCheck.getAndSet(false) && db.accounts().anyAccounts().toList().isEmpty();
    try {
        AccountsUpdate accountsUpdate = accountsUpdateFactory.create();
        accountsUpdate.upsert(db, account);
        ExternalId existingExtId = externalIds.get(extId.key());
        if (existingExtId != null && !existingExtId.accountId().equals(extId.accountId())) {
            // external ID is assigned to another account, do not overwrite
            accountsUpdate.delete(db, account);
            throw new AccountException("Cannot assign external ID \"" + extId.key().get() + "\" to account " + newId + "; external ID already in use.");
        }
        externalIdsUpdateFactory.create().upsert(extId);
    } finally {
        // If adding the account failed, it may be that it actually was the
        // first account. So we reset the 'check for first account'-guard, as
        // otherwise the first account would not get administration permissions.
        awaitsFirstAccountCheck.set(isFirstAccount);
    }
    if (isFirstAccount) {
        // This is the first user account on our site. Assume this user
        // is going to be the site's administrator and just make them that
        // to bootstrap the authentication database.
        //
        Permission admin = projectCache.getAllProjects().getConfig().getAccessSection(AccessSection.GLOBAL_CAPABILITIES).getPermission(GlobalCapability.ADMINISTRATE_SERVER);
        AccountGroup.UUID uuid = admin.getRules().get(0).getGroup().getUUID();
        AccountGroup g = db.accountGroups().byUUID(uuid).iterator().next();
        AccountGroup.Id adminId = g.getId();
        AccountGroupMember m = new AccountGroupMember(new AccountGroupMember.Key(newId, adminId));
        auditService.dispatchAddAccountsToGroup(newId, Collections.singleton(m));
        db.accountGroupMembers().insert(Collections.singleton(m));
    }
    if (who.getUserName() != null) {
        // Only set if the name hasn't been used yet, but was given to us.
        //
        IdentifiedUser user = userFactory.create(newId);
        try {
            changeUserNameFactory.create(user, who.getUserName()).call();
        } catch (NameAlreadyUsedException e) {
            String message = "Cannot assign user name \"" + who.getUserName() + "\" to account " + newId + "; name already in use.";
            handleSettingUserNameFailure(db, account, extId, message, e, false);
        } catch (InvalidUserNameException e) {
            String message = "Cannot assign user name \"" + who.getUserName() + "\" to account " + newId + "; name does not conform.";
            handleSettingUserNameFailure(db, account, extId, message, e, false);
        } catch (OrmException e) {
            String message = "Cannot assign user name";
            handleSettingUserNameFailure(db, account, extId, message, e, true);
        }
    }
    byEmailCache.evict(account.getPreferredEmail());
    byIdCache.evict(account.getId());
    realm.onCreateAccount(who, account);
    return new AuthResult(newId, extId.key(), true);
}
Also used : Account(com.google.gerrit.reviewdb.client.Account) AccountGroupMember(com.google.gerrit.reviewdb.client.AccountGroupMember) ExternalId(com.google.gerrit.server.account.externalids.ExternalId) IdentifiedUser(com.google.gerrit.server.IdentifiedUser) NameAlreadyUsedException(com.google.gerrit.common.errors.NameAlreadyUsedException) AccountGroup(com.google.gerrit.reviewdb.client.AccountGroup) OrmException(com.google.gwtorm.server.OrmException) Permission(com.google.gerrit.common.data.Permission) ExternalId(com.google.gerrit.server.account.externalids.ExternalId)

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