Search in sources :

Example 31 with UserNotFoundException

use of org.craftercms.studio.api.v1.exception.security.UserNotFoundException in project studio by craftercms.

the class GitContentRepository method createVersion.

@Override
public String createVersion(String site, String path, String comment, boolean majorVersion) {
    // SJ: Will ignore minor revisions since git handles that via write/commit
    // SJ: Major revisions become git tags
    // TODO: SJ: Redesign/refactor the whole approach in 3.1+
    String toReturn = EMPTY;
    String gitLockKey = SITE_SANDBOX_REPOSITORY_GIT_LOCK.replaceAll(PATTERN_SITE, site);
    generalLockService.lock(gitLockKey);
    try {
        GitRepositoryHelper helper = GitRepositoryHelper.getHelper(studioConfiguration, securityService, userServiceInternal, encryptor, generalLockService, retryingRepositoryOperationFacade);
        if (majorVersion) {
            synchronized (helper.getRepository(site, StringUtils.isEmpty(site) ? GLOBAL : PUBLISHED)) {
                Repository repo = helper.getRepository(site, StringUtils.isEmpty(site) ? GLOBAL : PUBLISHED);
                // Tag the repository with a date-time based version label
                String gitPath = helper.getGitPath(path);
                try (Git git = new Git(repo)) {
                    PersonIdent currentUserIdent = helper.getCurrentUserIdent();
                    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HHmmssX");
                    Calendar cal = Calendar.getInstance();
                    String versionLabel = dateFormat.format(cal.getTime());
                    TagCommand tagCommand = git.tag().setName(versionLabel).setMessage(comment).setTagger(currentUserIdent);
                    retryingRepositoryOperationFacade.call(tagCommand);
                    toReturn = versionLabel;
                } catch (GitAPIException | ServiceLayerException | UserNotFoundException err) {
                    logger.error("error creating new version for site:  " + site + " path: " + path, err);
                }
            }
        } else {
            logger.info("request to create minor revision ignored for site: " + site + " path: " + path);
        }
    } catch (CryptoException e) {
        logger.error("Unexpected error creating new version for site:  " + site + " path: " + path, e);
    } finally {
        generalLockService.unlock(gitLockKey);
    }
    return toReturn;
}
Also used : UserNotFoundException(org.craftercms.studio.api.v1.exception.security.UserNotFoundException) Calendar(java.util.Calendar) ServiceLayerException(org.craftercms.studio.api.v1.exception.ServiceLayerException) TagCommand(org.eclipse.jgit.api.TagCommand) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) RemoteRepository(org.craftercms.studio.api.v2.dal.RemoteRepository) Repository(org.eclipse.jgit.lib.Repository) ContentRepository(org.craftercms.studio.api.v1.repository.ContentRepository) Git(org.eclipse.jgit.api.Git) PersonIdent(org.eclipse.jgit.lib.PersonIdent) SimpleDateFormat(java.text.SimpleDateFormat) DateFormat(java.text.DateFormat) GitRepositoryHelper(org.craftercms.studio.api.v2.utils.GitRepositoryHelper) CryptoException(org.craftercms.commons.crypto.CryptoException) SimpleDateFormat(java.text.SimpleDateFormat)

Example 32 with UserNotFoundException

use of org.craftercms.studio.api.v1.exception.security.UserNotFoundException in project studio by craftercms.

the class StudioGroupAPIAccessDecisionVoter 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 siteParam = request.getParameter("site_id");
        String userParam = request.getParameter("username");
        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.error("Error getting current user", e);
                return ACCESS_ABSTAIN;
            }
        }
        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");
            }
        }
        switch(requestUri) {
            case ADD_USER:
            case CREATE:
            case DELETE:
            case GET_ALL:
            case REMOVE_USER:
            case UPDATE:
                if (currentUser != null && (isSiteAdmin(studioConfiguration.getProperty(CONFIGURATION_GLOBAL_SYSTEM_SITE), currentUser) || isSiteAdmin(siteParam, currentUser))) {
                    toRet = ACCESS_GRANTED;
                } else {
                    toRet = ACCESS_DENIED;
                }
                break;
            case GET:
            case GET_PER_SITE:
            case USERS:
                if (currentUser != null && (isSiteAdmin(siteParam, currentUser) || isSiteMember(siteParam, 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) ServiceLayerException(org.craftercms.studio.api.v1.exception.ServiceLayerException) JSONException(net.sf.json.JSONException) IOException(java.io.IOException) HttpServletRequest(javax.servlet.http.HttpServletRequest) JSONObject(net.sf.json.JSONObject) FilterInvocation(org.springframework.security.web.FilterInvocation)

Example 33 with UserNotFoundException

use of org.craftercms.studio.api.v1.exception.security.UserNotFoundException in project studio by craftercms.

the class StudioPublishingAPIAccessDecisionVoter 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 START:
            case STOP:
                if (currentUser != null) {
                    toRet = ACCESS_GRANTED;
                } else {
                    toRet = ACCESS_DENIED;
                }
                break;
            case STATUS:
                if (siteService.exists(siteParam)) {
                    if (currentUser != null && isSiteMember(siteParam, currentUser)) {
                        toRet = ACCESS_GRANTED;
                    } else {
                        toRet = ACCESS_DENIED;
                    }
                } else {
                    toRet = ACCESS_ABSTAIN;
                }
                break;
            case COMMITS:
            case PUBLISH_ITEMS:
            case RESET_STAGING:
                if (siteService.exists(siteParam)) {
                    if (currentUser != null && (isSiteAdmin(siteParam, currentUser) || hasPermission(siteParam, "~DASHBOARD~", currentUser.getUsername(), "publish"))) {
                        toRet = ACCESS_GRANTED;
                    } else {
                        toRet = ACCESS_DENIED;
                    }
                } else {
                    toRet = ACCESS_ABSTAIN;
                }
                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 34 with UserNotFoundException

use of org.craftercms.studio.api.v1.exception.security.UserNotFoundException in project studio by craftercms.

the class RepositoryManagementServiceInternalImpl method resolveConflict.

@Override
public boolean resolveConflict(String siteId, String path, String resolution) throws CryptoException, ServiceLayerException {
    GitRepositoryHelper helper = GitRepositoryHelper.getHelper(studioConfiguration, securityService, userServiceInternal, encryptor, generalLockService, retryingRepositoryOperationFacade);
    Repository repo = helper.getRepository(siteId, SANDBOX);
    String gitLockKey = SITE_SANDBOX_REPOSITORY_GIT_LOCK.replaceAll(PATTERN_SITE, siteId);
    generalLockService.lock(gitLockKey);
    try (Git git = new Git(repo)) {
        ResetCommand resetCommand;
        CheckoutCommand checkoutCommand;
        switch(resolution.toLowerCase()) {
            case "ours":
                logger.debug("Resolve conflict using OURS strategy for site " + siteId + " and path " + path);
                logger.debug("Reset merge conflict in git index");
                resetCommand = git.reset().addPath(helper.getGitPath(path));
                retryingRepositoryOperationFacade.call(resetCommand);
                logger.debug("Checkout content from HEAD of studio repository");
                checkoutCommand = git.checkout().addPath(helper.getGitPath(path)).setStartPoint(Constants.HEAD);
                retryingRepositoryOperationFacade.call(checkoutCommand);
                break;
            case "theirs":
                logger.debug("Resolve conflict using THEIRS strategy for site " + siteId + " and path " + path);
                logger.debug("Reset merge conflict in git index");
                resetCommand = git.reset().addPath(helper.getGitPath(path));
                retryingRepositoryOperationFacade.call(resetCommand);
                logger.debug("Checkout content from merge HEAD of remote repository");
                List<ObjectId> mergeHeads = repo.readMergeHeads();
                ObjectId mergeCommitId = mergeHeads.get(0);
                checkoutCommand = git.checkout().addPath(helper.getGitPath(path)).setStartPoint(mergeCommitId.getName());
                retryingRepositoryOperationFacade.call(checkoutCommand);
                break;
            default:
                throw new ServiceLayerException("Unsupported resolution strategy for repository conflicts");
        }
        if (repo.getRepositoryState() == RepositoryState.MERGING_RESOLVED) {
            logger.debug("Merge resolved. Check if there are no uncommitted changes (repo is clean)");
            Status status = git.status().call();
            if (!status.hasUncommittedChanges()) {
                logger.debug("Repository is clean. Committing to complete merge");
                String userName = securityService.getCurrentUser();
                User user = userServiceInternal.getUserByIdOrUsername(-1, userName);
                PersonIdent personIdent = helper.getAuthorIdent(user);
                CommitCommand commitCommand = git.commit().setAllowEmpty(true).setMessage("Merge resolved. Repo is clean (no changes)").setAuthor(personIdent);
                retryingRepositoryOperationFacade.call(commitCommand);
            }
        }
    } catch (GitAPIException | IOException | UserNotFoundException | ServiceLayerException e) {
        logger.error("Error while resolving conflict for site " + siteId + " using " + resolution + " resolution " + "strategy", e);
        throw new ServiceLayerException("Error while resolving conflict for site " + siteId + " using " + resolution + " resolution " + "strategy", e);
    } finally {
        generalLockService.unlock(gitLockKey);
    }
    return true;
}
Also used : Status(org.eclipse.jgit.api.Status) RepositoryStatus(org.craftercms.studio.api.v2.dal.RepositoryStatus) UserNotFoundException(org.craftercms.studio.api.v1.exception.security.UserNotFoundException) CheckoutCommand(org.eclipse.jgit.api.CheckoutCommand) User(org.craftercms.studio.api.v2.dal.User) ObjectId(org.eclipse.jgit.lib.ObjectId) ServiceLayerException(org.craftercms.studio.api.v1.exception.ServiceLayerException) IOException(java.io.IOException) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) RemoteRepository(org.craftercms.studio.api.v2.dal.RemoteRepository) Repository(org.eclipse.jgit.lib.Repository) ContentRepository(org.craftercms.studio.api.v1.repository.ContentRepository) Git(org.eclipse.jgit.api.Git) PersonIdent(org.eclipse.jgit.lib.PersonIdent) ResetCommand(org.eclipse.jgit.api.ResetCommand) CommitCommand(org.eclipse.jgit.api.CommitCommand) GitRepositoryHelper(org.craftercms.studio.api.v2.utils.GitRepositoryHelper)

Example 35 with UserNotFoundException

use of org.craftercms.studio.api.v1.exception.security.UserNotFoundException in project studio by craftercms.

the class RepositoryManagementServiceInternalImpl method commitResolution.

@Override
public boolean commitResolution(String siteId, String commitMessage) throws CryptoException, ServiceLayerException {
    GitRepositoryHelper helper = GitRepositoryHelper.getHelper(studioConfiguration, securityService, userServiceInternal, encryptor, generalLockService, retryingRepositoryOperationFacade);
    Repository repo = helper.getRepository(siteId, SANDBOX);
    logger.debug("Commit resolution for merge conflict for site " + siteId);
    String gitLockKey = SITE_SANDBOX_REPOSITORY_GIT_LOCK.replaceAll(PATTERN_SITE, siteId);
    generalLockService.lock(gitLockKey);
    try (Git git = new Git(repo)) {
        Status status = git.status().call();
        logger.debug("Add all uncommitted changes/files");
        AddCommand addCommand = git.add();
        for (String uncommited : status.getUncommittedChanges()) {
            addCommand.addFilepattern(uncommited);
        }
        retryingRepositoryOperationFacade.call(addCommand);
        logger.debug("Commit changes");
        CommitCommand commitCommand = git.commit();
        String userName = securityService.getCurrentUser();
        User user = userServiceInternal.getUserByIdOrUsername(-1, userName);
        PersonIdent personIdent = helper.getAuthorIdent(user);
        String prologue = studioConfiguration.getProperty(REPO_COMMIT_MESSAGE_PROLOGUE);
        String postscript = studioConfiguration.getProperty(REPO_COMMIT_MESSAGE_POSTSCRIPT);
        StringBuilder sbMessage = new StringBuilder();
        if (StringUtils.isNotEmpty(prologue)) {
            sbMessage.append(prologue).append("\n\n");
        }
        sbMessage.append(commitMessage);
        if (StringUtils.isNotEmpty(postscript)) {
            sbMessage.append("\n\n").append(postscript);
        }
        commitCommand.setCommitter(personIdent).setAuthor(personIdent).setMessage(sbMessage.toString());
        retryingRepositoryOperationFacade.call(commitCommand);
        return true;
    } catch (GitAPIException | UserNotFoundException | ServiceLayerException e) {
        logger.error("Error while committing conflict resolution for site " + siteId, e);
        throw new ServiceLayerException("Error while committing conflict resolution for site " + siteId, e);
    } finally {
        generalLockService.unlock(gitLockKey);
    }
}
Also used : Status(org.eclipse.jgit.api.Status) RepositoryStatus(org.craftercms.studio.api.v2.dal.RepositoryStatus) UserNotFoundException(org.craftercms.studio.api.v1.exception.security.UserNotFoundException) User(org.craftercms.studio.api.v2.dal.User) ServiceLayerException(org.craftercms.studio.api.v1.exception.ServiceLayerException) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) RemoteRepository(org.craftercms.studio.api.v2.dal.RemoteRepository) Repository(org.eclipse.jgit.lib.Repository) ContentRepository(org.craftercms.studio.api.v1.repository.ContentRepository) Git(org.eclipse.jgit.api.Git) PersonIdent(org.eclipse.jgit.lib.PersonIdent) CommitCommand(org.eclipse.jgit.api.CommitCommand) GitRepositoryHelper(org.craftercms.studio.api.v2.utils.GitRepositoryHelper) RemoteAddCommand(org.eclipse.jgit.api.RemoteAddCommand) AddCommand(org.eclipse.jgit.api.AddCommand)

Aggregations

UserNotFoundException (org.craftercms.studio.api.v1.exception.security.UserNotFoundException)43 ServiceLayerException (org.craftercms.studio.api.v1.exception.ServiceLayerException)40 User (org.craftercms.studio.api.v2.dal.User)32 IOException (java.io.IOException)15 HashMap (java.util.HashMap)15 ArrayList (java.util.ArrayList)11 SiteFeed (org.craftercms.studio.api.v1.dal.SiteFeed)11 UserExternallyManagedException (org.craftercms.studio.api.v1.exception.security.UserExternallyManagedException)11 Group (org.craftercms.studio.api.v2.dal.Group)11 RemoteRepository (org.craftercms.studio.api.v2.dal.RemoteRepository)11 Repository (org.eclipse.jgit.lib.Repository)11 HttpServletRequest (javax.servlet.http.HttpServletRequest)10 UserAlreadyExistsException (org.craftercms.studio.api.v1.exception.security.UserAlreadyExistsException)10 Git (org.eclipse.jgit.api.Git)10 GitAPIException (org.eclipse.jgit.api.errors.GitAPIException)10 AuditLog (org.craftercms.studio.api.v2.dal.AuditLog)9 GitRepositoryHelper (org.craftercms.studio.api.v2.utils.GitRepositoryHelper)9 CryptoException (org.craftercms.commons.crypto.CryptoException)8 ContentRepository (org.craftercms.studio.api.v1.repository.ContentRepository)8 PasswordDoesNotMatchException (org.craftercms.studio.api.v1.exception.security.PasswordDoesNotMatchException)7