Search in sources :

Example 51 with MethodNotAllowedException

use of com.google.gerrit.extensions.restapi.MethodNotAllowedException in project gerrit by GerritCodeReview.

the class PutName method apply.

public Response<String> apply(IdentifiedUser user, NameInput input) throws MethodNotAllowedException, ResourceNotFoundException, IOException, ConfigInvalidException {
    if (input == null) {
        input = new NameInput();
    }
    Account.Id accountId = user.getAccountId();
    if (realm.accountBelongsToRealm(externalIds.byAccount(accountId)) && !realm.allowsEdit(AccountFieldName.FULL_NAME)) {
        throw new MethodNotAllowedException("realm does not allow editing name");
    }
    String newName = input.name;
    AccountState accountState = accountsUpdateProvider.get().update("Set Full Name via API", accountId, u -> u.setFullName(newName)).orElseThrow(() -> new ResourceNotFoundException("account not found"));
    return Strings.isNullOrEmpty(accountState.account().fullName()) ? Response.none() : Response.ok(accountState.account().fullName());
}
Also used : ResourceNotFoundException(com.google.gerrit.extensions.restapi.ResourceNotFoundException) PermissionBackendException(com.google.gerrit.server.permissions.PermissionBackendException) ConfigInvalidException(org.eclipse.jgit.errors.ConfigInvalidException) Inject(com.google.inject.Inject) Response(com.google.gerrit.extensions.restapi.Response) PermissionBackend(com.google.gerrit.server.permissions.PermissionBackend) RestModifyView(com.google.gerrit.extensions.restapi.RestModifyView) Strings(com.google.common.base.Strings) AuthException(com.google.gerrit.extensions.restapi.AuthException) AccountsUpdate(com.google.gerrit.server.account.AccountsUpdate) 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) NameInput(com.google.gerrit.extensions.common.NameInput) AccountFieldName(com.google.gerrit.extensions.client.AccountFieldName) IOException(java.io.IOException) MethodNotAllowedException(com.google.gerrit.extensions.restapi.MethodNotAllowedException) ExternalIds(com.google.gerrit.server.account.externalids.ExternalIds) Provider(com.google.inject.Provider) IdentifiedUser(com.google.gerrit.server.IdentifiedUser) ServerInitiated(com.google.gerrit.server.ServerInitiated) AccountState(com.google.gerrit.server.account.AccountState) Realm(com.google.gerrit.server.account.Realm) Singleton(com.google.inject.Singleton) Account(com.google.gerrit.entities.Account) MethodNotAllowedException(com.google.gerrit.extensions.restapi.MethodNotAllowedException) NameInput(com.google.gerrit.extensions.common.NameInput) AccountState(com.google.gerrit.server.account.AccountState) ResourceNotFoundException(com.google.gerrit.extensions.restapi.ResourceNotFoundException)

Example 52 with MethodNotAllowedException

use of com.google.gerrit.extensions.restapi.MethodNotAllowedException in project gerrit by GerritCodeReview.

the class PutUsername method apply.

@Override
public Response<String> apply(AccountResource rsrc, UsernameInput input) throws RestApiException, IOException, ConfigInvalidException, PermissionBackendException {
    if (!self.get().hasSameAccountId(rsrc.getUser())) {
        permissionBackend.currentUser().check(GlobalPermission.ADMINISTRATE_SERVER);
    }
    Account.Id accountId = rsrc.getUser().getAccountId();
    if (!externalIds.byAccount(accountId, SCHEME_USERNAME).isEmpty()) {
        throw new MethodNotAllowedException("Username cannot be changed.");
    }
    if (realm.accountBelongsToRealm(externalIds.byAccount(accountId)) && !realm.allowsEdit(AccountFieldName.USER_NAME)) {
        throw new MethodNotAllowedException("realm does not allow editing username");
    }
    if (input == null || Strings.isNullOrEmpty(input.username)) {
        throw new BadRequestException("input required");
    }
    if (!ExternalId.isValidUsername(input.username)) {
        throw new UnprocessableEntityException("invalid username");
    }
    ExternalId.Key key = externalIdKeyFactory.create(SCHEME_USERNAME, input.username);
    try {
        accountsUpdateProvider.get().update("Set Username via API", accountId, u -> u.addExternalId(externalIdFactory.create(key, accountId, null, null)));
    } catch (DuplicateKeyException dupeErr) {
        // If we are using this identity, don't report the exception.
        Optional<ExternalId> other = externalIds.get(key);
        if (other.isPresent() && other.get().accountId().equals(accountId)) {
            return Response.ok(input.username);
        }
        // Otherwise, someone else has this identity.
        throw new ResourceConflictException("username already used", dupeErr);
    }
    sshKeyCache.evict(input.username);
    return Response.ok(input.username);
}
Also used : Account(com.google.gerrit.entities.Account) UnprocessableEntityException(com.google.gerrit.extensions.restapi.UnprocessableEntityException) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) MethodNotAllowedException(com.google.gerrit.extensions.restapi.MethodNotAllowedException) Optional(java.util.Optional) ExternalId(com.google.gerrit.server.account.externalids.ExternalId) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) DuplicateKeyException(com.google.gerrit.exceptions.DuplicateKeyException)

Example 53 with MethodNotAllowedException

use of com.google.gerrit.extensions.restapi.MethodNotAllowedException 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)

Example 54 with MethodNotAllowedException

use of com.google.gerrit.extensions.restapi.MethodNotAllowedException in project gerrit by GerritCodeReview.

the class DeleteChange method apply.

@Override
public Response<Object> apply(ChangeResource rsrc, Input input) throws RestApiException, UpdateException, PermissionBackendException {
    if (!isChangeDeletable(rsrc)) {
        throw new MethodNotAllowedException("delete not permitted");
    }
    rsrc.permissions().check(ChangePermission.DELETE);
    try (BatchUpdate bu = updateFactory.create(rsrc.getProject(), rsrc.getUser(), TimeUtil.now())) {
        Change.Id id = rsrc.getChange().getId();
        bu.addOp(id, opFactory.create(id));
        bu.execute();
    }
    return Response.none();
}
Also used : MethodNotAllowedException(com.google.gerrit.extensions.restapi.MethodNotAllowedException) Change(com.google.gerrit.entities.Change) BatchUpdate(com.google.gerrit.server.update.BatchUpdate)

Example 55 with MethodNotAllowedException

use of com.google.gerrit.extensions.restapi.MethodNotAllowedException in project gerrit by GerritCodeReview.

the class GetAgreements method apply.

@Override
public Response<List<AgreementInfo>> apply(AccountResource resource) throws RestApiException, PermissionBackendException {
    if (!agreementsEnabled) {
        throw new MethodNotAllowedException("contributor agreements disabled");
    }
    if (!self.get().isIdentifiedUser()) {
        throw new AuthException("not allowed to get contributor agreements");
    }
    IdentifiedUser user = self.get().asIdentifiedUser();
    if (user != resource.getUser()) {
        try {
            permissionBackend.user(user).check(GlobalPermission.ADMINISTRATE_SERVER);
        } catch (AuthException e) {
            throw new AuthException("not allowed to get contributor agreements", e);
        }
    }
    List<AgreementInfo> results = new ArrayList<>();
    Collection<ContributorAgreement> cas = projectCache.getAllProjects().getConfig().getContributorAgreements().values();
    for (ContributorAgreement ca : cas) {
        List<AccountGroup.UUID> groupIds = new ArrayList<>();
        for (PermissionRule rule : ca.getAccepted()) {
            if ((rule.getAction() == Action.ALLOW) && (rule.getGroup() != null)) {
                if (rule.getGroup().getUUID() != null) {
                    groupIds.add(rule.getGroup().getUUID());
                } else {
                    logger.atWarning().log("group \"%s\" does not exist, referenced in CLA \"%s\"", rule.getGroup().getName(), ca.getName());
                }
            }
        }
        if (user.getEffectiveGroups().containsAnyOf(groupIds)) {
            results.add(agreementJson.format(ca));
        }
    }
    return Response.ok(results);
}
Also used : MethodNotAllowedException(com.google.gerrit.extensions.restapi.MethodNotAllowedException) PermissionRule(com.google.gerrit.entities.PermissionRule) AgreementInfo(com.google.gerrit.extensions.common.AgreementInfo) ContributorAgreement(com.google.gerrit.entities.ContributorAgreement) ArrayList(java.util.ArrayList) AuthException(com.google.gerrit.extensions.restapi.AuthException) IdentifiedUser(com.google.gerrit.server.IdentifiedUser)

Aggregations

MethodNotAllowedException (com.google.gerrit.extensions.restapi.MethodNotAllowedException)66 BadRequestException (com.google.gerrit.extensions.restapi.BadRequestException)27 AuthException (com.google.gerrit.extensions.restapi.AuthException)23 AbstractDaemonTest (com.google.gerrit.acceptance.AbstractDaemonTest)16 ResourceNotFoundException (com.google.gerrit.extensions.restapi.ResourceNotFoundException)16 Test (org.junit.Test)16 ResourceConflictException (com.google.gerrit.extensions.restapi.ResourceConflictException)15 AccountGroup (com.google.gerrit.reviewdb.client.AccountGroup)11 IOException (java.io.IOException)11 ArrayList (java.util.ArrayList)11 IdentifiedUser (com.google.gerrit.server.IdentifiedUser)10 Account (com.google.gerrit.reviewdb.client.Account)9 UnprocessableEntityException (com.google.gerrit.extensions.restapi.UnprocessableEntityException)8 PermissionBackend (com.google.gerrit.server.permissions.PermissionBackend)7 BatchUpdate (com.google.gerrit.server.update.BatchUpdate)7 Account (com.google.gerrit.entities.Account)6 GroupInfo (com.google.gerrit.extensions.common.GroupInfo)5 Response (com.google.gerrit.extensions.restapi.Response)5 Change (com.google.gerrit.reviewdb.client.Change)5 CurrentUser (com.google.gerrit.server.CurrentUser)5