Search in sources :

Example 1 with DELETE

use of org.craftercms.studio.api.v2.dal.RepoOperation.Action.DELETE in project studio by craftercms.

the class UserServiceImpl method deleteUsers.

@Override
@HasPermission(type = DefaultPermission.class, action = "delete_users")
public void deleteUsers(List<Long> userIds, List<String> usernames) throws ServiceLayerException, AuthenticationException, UserNotFoundException {
    User currentUser = getCurrentUser();
    if (CollectionUtils.containsAny(userIds, Arrays.asList(currentUser.getId())) || CollectionUtils.containsAny(usernames, Arrays.asList(currentUser.getUsername()))) {
        throw new ServiceLayerException("Cannot delete self.");
    }
    generalLockService.lock(REMOVE_SYSTEM_ADMIN_MEMBER_LOCK);
    try {
        try {
            Group g = groupServiceInternal.getGroupByName(SYSTEM_ADMIN_GROUP);
            List<User> members = groupServiceInternal.getGroupMembers(g.getId(), 0, Integer.MAX_VALUE, StringUtils.EMPTY);
            if (CollectionUtils.isNotEmpty(members)) {
                List<User> membersAfterRemove = new ArrayList<User>();
                membersAfterRemove.addAll(members);
                members.forEach(m -> {
                    if (CollectionUtils.isNotEmpty(userIds)) {
                        if (userIds.contains(m.getId())) {
                            membersAfterRemove.remove(m);
                        }
                    }
                    if (CollectionUtils.isNotEmpty(usernames)) {
                        if (usernames.contains(m.getUsername())) {
                            membersAfterRemove.remove(m);
                        }
                    }
                });
                if (CollectionUtils.isEmpty(membersAfterRemove)) {
                    throw new ServiceLayerException("Removing all members of the System Admin group is not allowed." + " We must have at least one system administrator.");
                }
            }
        } catch (GroupNotFoundException e) {
            throw new ServiceLayerException("The System Admin group is not found.", e);
        }
        List<User> toDelete = userServiceInternal.getUsersByIdOrUsername(userIds, usernames);
        userServiceInternal.deleteUsers(userIds, usernames);
        SiteFeed siteFeed = siteService.getSite(studioConfiguration.getProperty(CONFIGURATION_GLOBAL_SYSTEM_SITE));
        AuditLog auditLog = auditServiceInternal.createAuditLogEntry();
        auditLog.setOperation(OPERATION_DELETE);
        auditLog.setActorId(getCurrentUser().getUsername());
        auditLog.setPrimaryTargetId(siteFeed.getSiteId());
        auditLog.setPrimaryTargetType(TARGET_TYPE_USER);
        auditLog.setPrimaryTargetValue(siteFeed.getName());
        List<AuditLogParameter> paramters = new ArrayList<AuditLogParameter>();
        for (User deletedUser : toDelete) {
            AuditLogParameter paramter = new AuditLogParameter();
            paramter.setTargetId(Long.toString(deletedUser.getId()));
            paramter.setTargetType(TARGET_TYPE_USER);
            paramter.setTargetValue(deletedUser.getUsername());
            paramters.add(paramter);
        }
        auditLog.setParameters(paramters);
        auditServiceInternal.insertAuditLog(auditLog);
    } finally {
        generalLockService.unlock(REMOVE_SYSTEM_ADMIN_MEMBER_LOCK);
    }
}
Also used : Group(org.craftercms.studio.api.v2.dal.Group) User(org.craftercms.studio.api.v2.dal.User) AuthenticatedUser(org.craftercms.studio.model.AuthenticatedUser) SiteFeed(org.craftercms.studio.api.v1.dal.SiteFeed) ArrayList(java.util.ArrayList) ServiceLayerException(org.craftercms.studio.api.v1.exception.ServiceLayerException) GroupNotFoundException(org.craftercms.studio.api.v1.exception.security.GroupNotFoundException) AuditLogParameter(org.craftercms.studio.api.v2.dal.AuditLogParameter) AuditLog(org.craftercms.studio.api.v2.dal.AuditLog) HasPermission(org.craftercms.commons.security.permissions.annotations.HasPermission)

Example 2 with DELETE

use of org.craftercms.studio.api.v2.dal.RepoOperation.Action.DELETE in project studio by craftercms.

the class GitContentRepository method publish.

@RetryingOperation
@Override
public void publish(String site, String sandboxBranch, List<DeploymentItemTO> deploymentItems, String environment, String author, String comment) throws DeploymentException {
    if (CollectionUtils.isEmpty(deploymentItems)) {
        return;
    }
    String commitId = EMPTY;
    String gitLockKey = SITE_PUBLISHED_REPOSITORY_GIT_LOCK.replaceAll(PATTERN_SITE, site);
    generalLockService.lock(gitLockKey);
    try {
        GitRepositoryHelper helper = GitRepositoryHelper.getHelper(studioConfiguration, securityService, userServiceInternal, encryptor, generalLockService, retryingRepositoryOperationFacade);
        Repository repo = helper.getRepository(site, PUBLISHED);
        boolean repoCreated = false;
        if (Objects.isNull(repo)) {
            helper.createPublishedRepository(site, sandboxBranch);
            repo = helper.getRepository(site, PUBLISHED);
            repoCreated = Objects.nonNull(repo);
        }
        String path = EMPTY;
        String sandboxBranchName = sandboxBranch;
        if (StringUtils.isEmpty(sandboxBranchName)) {
            sandboxBranchName = studioConfiguration.getProperty(REPO_SANDBOX_BRANCH);
        }
        synchronized (repo) {
            try (Git git = new Git(repo)) {
                String inProgressBranchName = environment + IN_PROGRESS_BRANCH_NAME_SUFFIX;
                // fetch "origin/master"
                logger.debug("Fetch from sandbox for site " + site);
                FetchCommand fetchCommand = git.fetch();
                retryingRepositoryOperationFacade.call(fetchCommand);
                // checkout master and pull from sandbox
                logger.debug("Checkout published/master branch for site " + site);
                try {
                    // First delete it in case it already exists (ignored if does not exist)
                    String currentBranch = repo.getBranch();
                    if (currentBranch.endsWith(IN_PROGRESS_BRANCH_NAME_SUFFIX)) {
                        ResetCommand resetCommand = git.reset().setMode(HARD);
                        retryingRepositoryOperationFacade.call(resetCommand);
                    }
                    Ref ref = repo.exactRef(R_HEADS + sandboxBranchName);
                    boolean createBranch = (ref == null);
                    CheckoutCommand checkoutCommand = git.checkout().setName(sandboxBranchName).setCreateBranch(createBranch);
                    retryingRepositoryOperationFacade.call(checkoutCommand);
                    logger.debug("Delete in-progress branch, in case it was not cleaned up for site " + site);
                    DeleteBranchCommand deleteBranchCommand = git.branchDelete().setBranchNames(inProgressBranchName).setForce(true);
                    retryingRepositoryOperationFacade.call(deleteBranchCommand);
                    PullCommand pullCommand = git.pull().setRemote(DEFAULT_REMOTE_NAME).setRemoteBranchName(sandboxBranchName).setStrategy(THEIRS);
                    retryingRepositoryOperationFacade.call(pullCommand);
                } catch (RefNotFoundException e) {
                    logger.error("Failed to checkout published master and to pull content from sandbox for site " + site, e);
                    throw new DeploymentException("Failed to checkout published master and to pull content from " + "sandbox for site " + site);
                }
                // checkout environment branch
                logger.debug("Checkout environment branch " + environment + " for site " + site);
                try {
                    CheckoutCommand checkoutCommand = git.checkout().setName(environment);
                    retryingRepositoryOperationFacade.call(checkoutCommand);
                } catch (RefNotFoundException e) {
                    logger.info("Not able to find branch " + environment + " for site " + site + ". Creating new branch");
                    // create new environment branch
                    // it will start as empty orphan branch
                    CheckoutCommand checkoutCommand = git.checkout().setOrphan(true).setForceRefUpdate(true).setStartPoint(sandboxBranchName).setUpstreamMode(TRACK).setName(environment);
                    retryingRepositoryOperationFacade.call(checkoutCommand);
                    // remove any content to create empty branch
                    RmCommand rmcmd = git.rm();
                    File[] toDelete = repo.getWorkTree().listFiles();
                    for (File toDel : toDelete) {
                        if (!repo.getDirectory().equals(toDel) && !StringUtils.equals(toDel.getName(), DOT_GIT_IGNORE)) {
                            rmcmd.addFilepattern(toDel.getName());
                        }
                    }
                    retryingRepositoryOperationFacade.call(rmcmd);
                    CommitCommand commitCommand = git.commit().setMessage(helper.getCommitMessage(REPO_INITIAL_COMMIT_COMMIT_MESSAGE)).setAllowEmpty(true);
                    retryingRepositoryOperationFacade.call(commitCommand);
                }
                // Create in progress branch
                try {
                    // Create in progress branch
                    logger.debug("Create in-progress branch for site " + site);
                    CheckoutCommand checkoutCommand = git.checkout().setCreateBranch(true).setForceRefUpdate(true).setStartPoint(environment).setUpstreamMode(TRACK).setName(inProgressBranchName);
                    retryingRepositoryOperationFacade.call(checkoutCommand);
                } catch (GitAPIException e) {
                    // TODO: DB: Error ?
                    logger.error("Failed to create in-progress published branch for site " + site);
                }
                Set<String> deployedCommits = new HashSet<String>();
                Set<String> deployedPackages = new HashSet<String>();
                logger.debug("Checkout deployed files started.");
                AddCommand addCommand = git.add();
                for (DeploymentItemTO deploymentItem : deploymentItems) {
                    commitId = deploymentItem.getCommitId();
                    path = helper.getGitPath(deploymentItem.getPath());
                    if (Objects.isNull(commitId) || !commitIdExists(site, PUBLISHED, commitId)) {
                        if (contentExists(site, path)) {
                            if (Objects.isNull(commitId)) {
                                logger.warn("Commit ID is NULL for content " + path + ". Was the git repo reset at some point?");
                            } else {
                                logger.warn("Commit ID " + commitId + " does not exist for content " + path + ". Was the git repo reset at some point?");
                            }
                            logger.info("Publishing content from HEAD for " + path);
                            commitId = getRepoLastCommitId(site);
                        } else {
                            logger.warn("Skipping file " + path + " because commit id is null");
                            continue;
                        }
                    }
                    logger.debug("Checking out file " + path + " from commit id " + commitId + " for site " + site);
                    CheckoutCommand checkout = git.checkout();
                    checkout.setStartPoint(commitId).addPath(path);
                    retryingRepositoryOperationFacade.call(checkout);
                    if (deploymentItem.isMove()) {
                        if (!StringUtils.equals(deploymentItem.getPath(), deploymentItem.getOldPath())) {
                            String oldPath = helper.getGitPath(deploymentItem.getOldPath());
                            RmCommand rmCommand = git.rm().addFilepattern(oldPath).setCached(false);
                            retryingRepositoryOperationFacade.call(rmCommand);
                            cleanUpMoveFolders(git, oldPath);
                        }
                    }
                    if (deploymentItem.isDelete()) {
                        String deletePath = helper.getGitPath(deploymentItem.getPath());
                        boolean isPage = deletePath.endsWith(FILE_SEPARATOR + INDEX_FILE);
                        RmCommand rmCommand = git.rm().addFilepattern(deletePath).setCached(false);
                        retryingRepositoryOperationFacade.call(rmCommand);
                        Path parentToDelete = Paths.get(path).getParent();
                        deleteParentFolder(git, parentToDelete, isPage);
                    }
                    deployedCommits.add(commitId);
                    String packageId = deploymentItem.getPackageId();
                    if (StringUtils.isNotEmpty(packageId)) {
                        deployedPackages.add(deploymentItem.getPackageId());
                    }
                    addCommand.addFilepattern(path);
                    objectMetadataManager.updateLastPublishedDate(site, deploymentItem.getPath(), ZonedDateTime.now(UTC));
                }
                logger.debug("Checkout deployed files completed.");
                // commit all deployed files
                String commitMessage = studioConfiguration.getProperty(REPO_PUBLISHED_COMMIT_MESSAGE);
                logger.debug("Get Author Ident started.");
                User user = userServiceInternal.getUserByIdOrUsername(-1, author);
                PersonIdent authorIdent = helper.getAuthorIdent(user);
                logger.debug("Get Author Ident completed.");
                logger.debug("Git add all published items started.");
                retryingRepositoryOperationFacade.call(addCommand);
                logger.debug("Git add all published items completed.");
                commitMessage = commitMessage.replace("{username}", author);
                commitMessage = commitMessage.replace("{datetime}", ZonedDateTime.now(UTC).format(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HHmmssSSSX")));
                commitMessage = commitMessage.replace("{source}", "UI");
                commitMessage = commitMessage.replace("{message}", comment);
                StringBuilder sb = new StringBuilder();
                for (String c : deployedCommits) {
                    sb.append(c).append(" ");
                }
                StringBuilder sbPackage = new StringBuilder();
                for (String p : deployedPackages) {
                    sbPackage.append(p).append(" ");
                }
                commitMessage = commitMessage.replace("{commit_id}", sb.toString().trim());
                commitMessage = commitMessage.replace("{package_id}", sbPackage.toString().trim());
                logger.debug("Git commit all published items started.");
                String prologue = studioConfiguration.getProperty(REPO_COMMIT_MESSAGE_PROLOGUE);
                String postscript = studioConfiguration.getProperty(REPO_COMMIT_MESSAGE_POSTSCRIPT);
                StringBuilder sbCommitMessage = new StringBuilder();
                if (StringUtils.isNotEmpty(prologue)) {
                    sbCommitMessage.append(prologue).append("\n\n");
                }
                sbCommitMessage.append(commitMessage);
                if (StringUtils.isNotEmpty(postscript)) {
                    sbCommitMessage.append("\n\n").append(postscript);
                }
                CommitCommand commitCommand = git.commit().setMessage(sbCommitMessage.toString()).setAuthor(authorIdent);
                RevCommit revCommit = retryingRepositoryOperationFacade.call(commitCommand);
                logger.debug("Git commit all published items completed.");
                int commitTime = revCommit.getCommitTime();
                // tag
                ZonedDateTime tagDate2 = Instant.ofEpochSecond(commitTime).atZone(UTC);
                ZonedDateTime publishDate = ZonedDateTime.now(UTC);
                String tagName2 = tagDate2.format(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HHmmssSSSX")) + "_published_on_" + publishDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HHmmssSSSX"));
                logger.debug("Get Author Ident started.");
                PersonIdent authorIdent2 = helper.getAuthorIdent(user);
                logger.debug("Get Author Ident completed.");
                logger.debug("Git tag started.");
                TagCommand tagCommand = git.tag().setTagger(authorIdent2).setName(tagName2).setMessage(commitMessage);
                retryingRepositoryOperationFacade.call(tagCommand);
                logger.debug("Git tag completed.");
                // checkout environment
                logger.debug("Checkout environment " + environment + " branch for site " + site);
                CheckoutCommand checkoutCommand = git.checkout().setName(environment);
                retryingRepositoryOperationFacade.call(checkoutCommand);
                Ref branchRef = repo.findRef(inProgressBranchName);
                // merge in-progress branch
                logger.debug("Merge in-progress branch into environment " + environment + " for site " + site);
                MergeCommand mergeCommand = git.merge().setCommit(true).include(branchRef);
                retryingRepositoryOperationFacade.call(mergeCommand);
                // clean up
                logger.debug("Delete in-progress branch (clean up) for site " + site);
                DeleteBranchCommand deleteBranchCommand = git.branchDelete().setBranchNames(inProgressBranchName).setForce(true);
                retryingRepositoryOperationFacade.call(deleteBranchCommand);
                git.close();
                if (repoCreated) {
                    siteService.setPublishedRepoCreated(site);
                }
            }
        }
    } catch (Exception e) {
        logger.error("Error when publishing site " + site + " to environment " + environment, e);
        throw new DeploymentException("Error when publishing site " + site + " to environment " + environment + " [commit ID = " + commitId + "]");
    } finally {
        generalLockService.unlock(gitLockKey);
    }
}
Also used : CheckoutCommand(org.eclipse.jgit.api.CheckoutCommand) User(org.craftercms.studio.api.v2.dal.User) MergeCommand(org.eclipse.jgit.api.MergeCommand) TagCommand(org.eclipse.jgit.api.TagCommand) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) RefNotFoundException(org.eclipse.jgit.api.errors.RefNotFoundException) ZonedDateTime(java.time.ZonedDateTime) ResetCommand(org.eclipse.jgit.api.ResetCommand) RmCommand(org.eclipse.jgit.api.RmCommand) CommitCommand(org.eclipse.jgit.api.CommitCommand) GitRepositoryHelper(org.craftercms.studio.api.v2.utils.GitRepositoryHelper) HashSet(java.util.HashSet) RevCommit(org.eclipse.jgit.revwalk.RevCommit) Path(java.nio.file.Path) DeleteBranchCommand(org.eclipse.jgit.api.DeleteBranchCommand) PullCommand(org.eclipse.jgit.api.PullCommand) DeploymentItemTO(org.craftercms.studio.api.v1.to.DeploymentItemTO) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) ServiceLayerException(org.craftercms.studio.api.v1.exception.ServiceLayerException) IOException(java.io.IOException) RefNotFoundException(org.eclipse.jgit.api.errors.RefNotFoundException) RemoteRepositoryNotFoundException(org.craftercms.studio.api.v1.exception.repository.RemoteRepositoryNotFoundException) UserNotFoundException(org.craftercms.studio.api.v1.exception.security.UserNotFoundException) DeploymentException(org.craftercms.studio.api.v1.service.deployment.DeploymentException) SiteNotFoundException(org.craftercms.studio.api.v1.exception.SiteNotFoundException) CryptoException(org.craftercms.commons.crypto.CryptoException) DuplicateKeyException(org.springframework.dao.DuplicateKeyException) InvalidRemoteRepositoryCredentialsException(org.craftercms.studio.api.v1.exception.repository.InvalidRemoteRepositoryCredentialsException) InvalidRemoteRepositoryException(org.craftercms.studio.api.v1.exception.repository.InvalidRemoteRepositoryException) RemoteRepository(org.craftercms.studio.api.v2.dal.RemoteRepository) Repository(org.eclipse.jgit.lib.Repository) ContentRepository(org.craftercms.studio.api.v2.repository.ContentRepository) Ref(org.eclipse.jgit.lib.Ref) Git(org.eclipse.jgit.api.Git) FetchCommand(org.eclipse.jgit.api.FetchCommand) PersonIdent(org.eclipse.jgit.lib.PersonIdent) DeploymentException(org.craftercms.studio.api.v1.service.deployment.DeploymentException) File(java.io.File) AddCommand(org.eclipse.jgit.api.AddCommand) RetryingOperation(org.craftercms.studio.api.v2.annotation.RetryingOperation)

Example 3 with DELETE

use of org.craftercms.studio.api.v2.dal.RepoOperation.Action.DELETE in project studio by craftercms.

the class StudioUserAPIAccessDecisionVoter method vote.

@Override
public int vote(Authentication authentication, Object o, Collection collection) {
    int toRet = ACCESS_ABSTAIN;
    String requestUri = "";
    if (o instanceof FilterInvocation) {
        FilterInvocation filterInvocation = (FilterInvocation) o;
        HttpServletRequest request = filterInvocation.getRequest();
        requestUri = request.getRequestURI().replace(request.getContextPath(), "");
        String userParam = request.getParameter("username");
        String siteParam = request.getParameter("site_id");
        if (StringUtils.isEmpty(userParam) && StringUtils.equalsIgnoreCase(request.getMethod(), HttpMethod.POST.name()) && !ServletFileUpload.isMultipartContent(request)) {
            try {
                InputStream is = request.getInputStream();
                is.mark(0);
                String jsonString = IOUtils.toString(is);
                if (StringUtils.isNoneEmpty(jsonString)) {
                    JSONObject jsonObject = JSONObject.fromObject(jsonString);
                    if (jsonObject.has("username")) {
                        userParam = jsonObject.getString("username");
                    }
                    if (jsonObject.has("site_id")) {
                        siteParam = jsonObject.getString("site_id");
                    }
                }
                is.reset();
            } catch (IOException | JSONException e) {
                // TODO: ??
                logger.debug("Failed to extract username from POST request");
            }
        }
        User currentUser = null;
        try {
            String username = authentication.getPrincipal().toString();
            currentUser = userServiceInternal.getUserByIdOrUsername(-1, username);
        } catch (ClassCastException | UserNotFoundException | ServiceLayerException e) {
            // anonymous user
            if (!authentication.getPrincipal().toString().equals("anonymousUser")) {
                logger.info("Error getting current user", e);
                return ACCESS_ABSTAIN;
            }
        }
        switch(requestUri) {
            case FORGOT_PASSWORD:
            case LOGIN:
            case LOGOUT:
            case SET_PASSWORD:
            case VALIDATE_TOKEN:
                toRet = ACCESS_GRANTED;
                break;
            case CHANGE_PASSWORD:
                if (currentUser != null && isSelf(currentUser, userParam)) {
                    toRet = ACCESS_GRANTED;
                } else {
                    toRet = ACCESS_DENIED;
                }
                break;
            case CREATE:
            case DELETE:
            case DISABLE:
            case ENABLE:
            case RESET_PASSWORD:
            case STATUS:
                if (currentUser != null && isAdmin(currentUser)) {
                    toRet = ACCESS_GRANTED;
                } else {
                    toRet = ACCESS_DENIED;
                }
                break;
            case GET_ALL:
                if (currentUser != null) {
                    toRet = ACCESS_GRANTED;
                } else {
                    toRet = ACCESS_DENIED;
                }
                break;
            case GET:
                if (currentUser != null && (isAdmin(currentUser) || isSelf(currentUser, userParam) || isSiteMember(currentUser, userParam))) {
                    toRet = ACCESS_GRANTED;
                } else {
                    toRet = ACCESS_DENIED;
                }
                break;
            case GET_PER_SITE:
                if (currentUser != null && (isAdmin(currentUser) || isSiteMember(currentUser, userParam))) {
                    toRet = ACCESS_GRANTED;
                } else {
                    toRet = ACCESS_DENIED;
                }
                break;
            case UPDATE:
                if (currentUser != null && (isAdmin(currentUser) || isSelf(currentUser, userParam))) {
                    toRet = ACCESS_GRANTED;
                } else {
                    toRet = ACCESS_DENIED;
                }
                break;
            default:
                toRet = ACCESS_ABSTAIN;
                break;
        }
    }
    logger.debug("Request: " + requestUri + " - Access: " + toRet);
    return toRet;
}
Also used : UserNotFoundException(org.craftercms.studio.api.v1.exception.security.UserNotFoundException) User(org.craftercms.studio.api.v2.dal.User) InputStream(java.io.InputStream) JSONException(net.sf.json.JSONException) ServiceLayerException(org.craftercms.studio.api.v1.exception.ServiceLayerException) IOException(java.io.IOException) HttpServletRequest(javax.servlet.http.HttpServletRequest) JSONObject(net.sf.json.JSONObject) FilterInvocation(org.springframework.security.web.FilterInvocation)

Example 4 with DELETE

use of org.craftercms.studio.api.v2.dal.RepoOperation.Action.DELETE in project studio by craftercms.

the class StudioAuditLogProcessingTask method processAuditLogFromRepo.

private void processAuditLogFromRepo(String siteId, int batchSize) throws SiteNotFoundException {
    List<GitLog> unauditedGitlogs = contentRepository.getUnauditedCommits(siteId, batchSize);
    if (unauditedGitlogs != null) {
        SiteFeed siteFeed = siteService.getSite(siteId);
        for (GitLog gl : unauditedGitlogs) {
            if (contentRepository.commitIdExists(siteId, gl.getCommitId())) {
                String prevCommitId = gl.getCommitId() + PREVIOUS_COMMIT_SUFFIX;
                List<RepoOperation> operations = contentRepository.getOperationsFromDelta(siteId, prevCommitId, gl.getCommitId());
                for (RepoOperation repoOperation : operations) {
                    Map<String, String> activityInfo = new HashMap<String, String>();
                    String contentClass;
                    AuditLog auditLog;
                    switch(repoOperation.getAction()) {
                        case CREATE:
                        case COPY:
                            contentClass = contentService.getContentTypeClass(siteId, repoOperation.getPath());
                            if (repoOperation.getPath().endsWith(DmConstants.XML_PATTERN)) {
                                activityInfo.put(DmConstants.KEY_CONTENT_TYPE, contentClass);
                            }
                            logger.debug("Insert audit log for site: " + siteId + " path: " + repoOperation.getPath());
                            auditLog = auditServiceInternal.createAuditLogEntry();
                            auditLog.setOperation(OPERATION_CREATE);
                            auditLog.setOperationTimestamp(repoOperation.getDateTime());
                            auditLog.setSiteId(siteFeed.getId());
                            auditLog.setActorId(repoOperation.getAuthor());
                            auditLog.setActorDetails(repoOperation.getAuthor());
                            auditLog.setPrimaryTargetId(siteId + ":" + repoOperation.getPath());
                            auditLog.setPrimaryTargetType(TARGET_TYPE_CONTENT_ITEM);
                            auditLog.setPrimaryTargetValue(repoOperation.getPath());
                            auditLog.setPrimaryTargetSubtype(contentService.getContentTypeClass(siteId, repoOperation.getPath()));
                            auditLog.setOrigin(ORIGIN_GIT);
                            auditServiceInternal.insertAuditLog(auditLog);
                            break;
                        case UPDATE:
                            contentClass = contentService.getContentTypeClass(siteId, repoOperation.getPath());
                            if (repoOperation.getPath().endsWith(DmConstants.XML_PATTERN)) {
                                activityInfo.put(DmConstants.KEY_CONTENT_TYPE, contentClass);
                            }
                            logger.debug("Insert audit log for site: " + siteId + " path: " + repoOperation.getPath());
                            auditLog = auditServiceInternal.createAuditLogEntry();
                            auditLog.setOperation(OPERATION_UPDATE);
                            auditLog.setOperationTimestamp(repoOperation.getDateTime());
                            auditLog.setSiteId(siteFeed.getId());
                            auditLog.setActorId(repoOperation.getAuthor());
                            auditLog.setActorDetails(repoOperation.getAuthor());
                            auditLog.setOrigin(ORIGIN_GIT);
                            auditLog.setPrimaryTargetId(siteId + ":" + repoOperation.getPath());
                            auditLog.setPrimaryTargetType(TARGET_TYPE_CONTENT_ITEM);
                            auditLog.setPrimaryTargetValue(repoOperation.getPath());
                            auditLog.setPrimaryTargetSubtype(contentService.getContentTypeClass(siteId, repoOperation.getPath()));
                            auditServiceInternal.insertAuditLog(auditLog);
                            break;
                        case DELETE:
                            contentClass = contentService.getContentTypeClass(siteId, repoOperation.getPath());
                            if (repoOperation.getPath().endsWith(DmConstants.XML_PATTERN)) {
                                activityInfo.put(DmConstants.KEY_CONTENT_TYPE, contentClass);
                            }
                            logger.debug("Insert audit log for site: " + siteId + " path: " + repoOperation.getPath());
                            auditLog = auditServiceInternal.createAuditLogEntry();
                            auditLog.setOperation(OPERATION_DELETE);
                            auditLog.setOperationTimestamp(repoOperation.getDateTime());
                            auditLog.setSiteId(siteFeed.getId());
                            auditLog.setOrigin(ORIGIN_GIT);
                            auditLog.setActorId(repoOperation.getAuthor());
                            auditLog.setActorDetails(repoOperation.getAuthor());
                            auditLog.setPrimaryTargetId(siteId + ":" + repoOperation.getPath());
                            auditLog.setPrimaryTargetType(TARGET_TYPE_CONTENT_ITEM);
                            auditLog.setPrimaryTargetValue(repoOperation.getPath());
                            auditLog.setPrimaryTargetSubtype(contentService.getContentTypeClass(siteId, repoOperation.getPath()));
                            auditServiceInternal.insertAuditLog(auditLog);
                            break;
                        case MOVE:
                            contentClass = contentService.getContentTypeClass(siteId, repoOperation.getMoveToPath());
                            if (repoOperation.getMoveToPath().endsWith(DmConstants.XML_PATTERN)) {
                                activityInfo.put(DmConstants.KEY_CONTENT_TYPE, contentClass);
                            }
                            logger.debug("Insert audit log for site: " + siteId + " path: " + repoOperation.getMoveToPath());
                            auditLog = auditServiceInternal.createAuditLogEntry();
                            auditLog.setOperation(OPERATION_MOVE);
                            auditLog.setOperationTimestamp(repoOperation.getDateTime());
                            auditLog.setSiteId(siteFeed.getId());
                            auditLog.setActorId(repoOperation.getAuthor());
                            auditLog.setActorDetails(repoOperation.getAuthor());
                            auditLog.setOrigin(ORIGIN_GIT);
                            auditLog.setPrimaryTargetId(siteId + ":" + repoOperation.getMoveToPath());
                            auditLog.setPrimaryTargetType(TARGET_TYPE_CONTENT_ITEM);
                            auditLog.setPrimaryTargetValue(repoOperation.getMoveToPath());
                            auditLog.setPrimaryTargetSubtype(contentService.getContentTypeClass(siteId, repoOperation.getMoveToPath()));
                            auditServiceInternal.insertAuditLog(auditLog);
                            break;
                        default:
                            logger.error("Error: Unknown repo operation for site " + siteId + " operation: " + repoOperation.getAction());
                            break;
                    }
                }
            }
            contentRepository.markGitLogAudited(siteId, gl.getCommitId());
        }
    }
}
Also used : RepoOperation(org.craftercms.studio.api.v2.dal.RepoOperation) HashMap(java.util.HashMap) GitLog(org.craftercms.studio.api.v2.dal.GitLog) SiteFeed(org.craftercms.studio.api.v1.dal.SiteFeed) AuditLog(org.craftercms.studio.api.v2.dal.AuditLog)

Example 5 with DELETE

use of org.craftercms.studio.api.v2.dal.RepoOperation.Action.DELETE in project studio by craftercms.

the class StudioSiteAPIAccessDecisionVoter method vote.

@Override
public int vote(Authentication authentication, Object o, Collection collection) {
    int toRet = ACCESS_ABSTAIN;
    String requestUri = "";
    if (o instanceof FilterInvocation) {
        FilterInvocation filterInvocation = (FilterInvocation) o;
        HttpServletRequest request = filterInvocation.getRequest();
        requestUri = request.getRequestURI().replace(request.getContextPath(), "");
        String userParam = request.getParameter("username");
        if (StringUtils.isEmpty(userParam) && StringUtils.equalsIgnoreCase(request.getMethod(), HttpMethod.POST.name()) && !ServletFileUpload.isMultipartContent(request)) {
            try {
                InputStream is = request.getInputStream();
                is.mark(0);
                String jsonString = IOUtils.toString(is);
                if (StringUtils.isNoneEmpty(jsonString)) {
                    JSONObject jsonObject = JSONObject.fromObject(jsonString);
                    if (jsonObject.has("username")) {
                        userParam = jsonObject.getString("username");
                    }
                }
                is.reset();
            } catch (IOException | JSONException e) {
                // TODO: ??
                logger.debug("Failed to extract username from POST request");
            }
        }
        User currentUser = null;
        try {
            String username = authentication.getPrincipal().toString();
            currentUser = userServiceInternal.getUserByIdOrUsername(-1, username);
        } catch (ClassCastException | UserNotFoundException | ServiceLayerException e) {
            // anonymous user
            if (!authentication.getPrincipal().toString().equals("anonymousUser")) {
                logger.info("Error getting current user", e);
                return ACCESS_ABSTAIN;
            }
        }
        switch(requestUri) {
            case CREATE:
            case DELETE:
                if (currentUser != null && isAdmin(currentUser)) {
                    toRet = ACCESS_GRANTED;
                } else {
                    toRet = ACCESS_DENIED;
                }
                break;
            default:
                toRet = ACCESS_ABSTAIN;
                break;
        }
    }
    logger.debug("Request: " + requestUri + " - Access: " + toRet);
    return toRet;
}
Also used : UserNotFoundException(org.craftercms.studio.api.v1.exception.security.UserNotFoundException) User(org.craftercms.studio.api.v2.dal.User) InputStream(java.io.InputStream) JSONException(net.sf.json.JSONException) ServiceLayerException(org.craftercms.studio.api.v1.exception.ServiceLayerException) IOException(java.io.IOException) HttpServletRequest(javax.servlet.http.HttpServletRequest) JSONObject(net.sf.json.JSONObject) FilterInvocation(org.springframework.security.web.FilterInvocation)

Aggregations

ServiceLayerException (org.craftercms.studio.api.v1.exception.ServiceLayerException)10 IOException (java.io.IOException)7 SiteFeed (org.craftercms.studio.api.v1.dal.SiteFeed)6 UserNotFoundException (org.craftercms.studio.api.v1.exception.security.UserNotFoundException)6 User (org.craftercms.studio.api.v2.dal.User)6 ArrayList (java.util.ArrayList)5 JSONException (net.sf.json.JSONException)5 JSONObject (net.sf.json.JSONObject)5 AuditLog (org.craftercms.studio.api.v2.dal.AuditLog)5 RemoteRepository (org.craftercms.studio.api.v2.dal.RemoteRepository)5 Repository (org.eclipse.jgit.lib.Repository)5 RepoOperation (org.craftercms.studio.api.v2.dal.RepoOperation)4 Git (org.eclipse.jgit.api.Git)4 InputStream (java.io.InputStream)3 Path (java.nio.file.Path)3 ZonedDateTime (java.time.ZonedDateTime)3 HttpServletRequest (javax.servlet.http.HttpServletRequest)3 CryptoException (org.craftercms.commons.crypto.CryptoException)3 File (java.io.File)2 SimpleDateFormat (java.text.SimpleDateFormat)2