Search in sources :

Example 26 with UserNotFoundException

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

the class UsersController method forgotPassword.

@GetMapping(FORGOT_PASSWORD)
public ResponseBody forgotPassword(@RequestParam(value = REQUEST_PARAM_USERNAME, required = true) String username) throws ServiceLayerException {
    try {
        userService.forgotPassword(username);
    } catch (UserExternallyManagedException | UserNotFoundException e) {
        logger.error("Error processing user's forgot password request", e);
    }
    ResponseBody responseBody = new ResponseBody();
    ResultOne<String> result = new ResultOne<String>();
    result.setEntity(RESULT_KEY_MESSAGE, "If the user exists, a password recovery email has been sent to them.");
    result.setResponse(OK);
    responseBody.setResult(result);
    return responseBody;
}
Also used : UserNotFoundException(org.craftercms.studio.api.v1.exception.security.UserNotFoundException) UserExternallyManagedException(org.craftercms.studio.api.v1.exception.security.UserExternallyManagedException) ResultOne(org.craftercms.studio.model.rest.ResultOne) ResponseBody(org.craftercms.studio.model.rest.ResponseBody) GetMapping(org.springframework.web.bind.annotation.GetMapping)

Example 27 with UserNotFoundException

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

the class GitRepositoryHelper method createSiteCloneRemoteGitRepo.

public boolean createSiteCloneRemoteGitRepo(String siteId, String sandboxBranch, String remoteName, String remoteUrl, String remoteBranch, boolean singleBranch, String authenticationType, String remoteUsername, String remotePassword, String remoteToken, String remotePrivateKey, boolean createAsOrphan) throws InvalidRemoteRepositoryException, InvalidRemoteRepositoryCredentialsException, RemoteRepositoryNotFoundException, ServiceLayerException {
    boolean toRet = true;
    // prepare a new folder for the cloned repository
    Path siteSandboxPath = buildRepoPath(SANDBOX, siteId);
    File localPath = siteSandboxPath.toFile();
    localPath.delete();
    logger.debug("Add user credentials if provided");
    // then clone
    logger.debug("Cloning from " + remoteUrl + " to " + localPath);
    CloneCommand cloneCommand = Git.cloneRepository();
    Git cloneResult = null;
    String gitLockKey = SITE_SANDBOX_REPOSITORY_GIT_LOCK.replaceAll(PATTERN_SITE, siteId);
    generalLockService.lock(gitLockKey);
    try {
        final Path tempKey = Files.createTempFile(UUID.randomUUID().toString(), ".tmp");
        switch(authenticationType) {
            case RemoteRepository.AuthenticationType.NONE:
                logger.debug("No authentication");
                break;
            case RemoteRepository.AuthenticationType.BASIC:
                logger.debug("Basic authentication");
                cloneCommand.setCredentialsProvider(new UsernamePasswordCredentialsProvider(remoteUsername, remotePassword));
                break;
            case RemoteRepository.AuthenticationType.TOKEN:
                logger.debug("Token based authentication");
                cloneCommand.setCredentialsProvider(new UsernamePasswordCredentialsProvider(remoteToken, StringUtils.EMPTY));
                break;
            case RemoteRepository.AuthenticationType.PRIVATE_KEY:
                logger.debug("Private key authentication");
                tempKey.toFile().deleteOnExit();
                cloneCommand.setTransportConfigCallback(new TransportConfigCallback() {

                    @Override
                    public void configure(Transport transport) {
                        SshTransport sshTransport = (SshTransport) transport;
                        sshTransport.setSshSessionFactory(getSshSessionFactory(remotePrivateKey, tempKey));
                    }
                });
                break;
            default:
                throw new ServiceLayerException("Unsupported authentication type " + authenticationType);
        }
        if (StringUtils.isNotEmpty(remoteBranch)) {
            cloneCommand.setBranch(remoteBranch);
        }
        cloneResult = cloneCommand.setURI(remoteUrl).setDirectory(localPath).setRemote(remoteName).setCloneAllBranches(!singleBranch).call();
        Files.deleteIfExists(tempKey);
        Repository sandboxRepo = checkIfCloneWasOk(cloneResult, remoteName, remoteUrl);
        sandboxRepo = optimizeRepository(sandboxRepo);
        // Make repository orphan if needed
        if (createAsOrphan) {
            makeRepoOrphan(sandboxRepo, siteId);
        }
        sandboxes.put(siteId, sandboxRepo);
    } catch (InvalidRemoteException e) {
        logger.error("Invalid remote repository: " + remoteName + " (" + remoteUrl + ")", e);
        throw new InvalidRemoteRepositoryException("Invalid remote repository: " + remoteName + " (" + remoteUrl + ")");
    } catch (TransportException e) {
        if (StringUtils.endsWithIgnoreCase(e.getMessage(), "not authorized")) {
            logger.error("Bad credentials or read only repository: " + remoteName + " (" + remoteUrl + ")", e);
            throw new InvalidRemoteRepositoryCredentialsException("Bad credentials or read only repository: " + remoteName + " (" + remoteUrl + ") for username " + remoteUsername, e);
        } else {
            logger.error("Remote repository not found: " + remoteName + " (" + remoteUrl + ")", e);
            throw new RemoteRepositoryNotFoundException("Remote repository not found: " + remoteName + " (" + remoteUrl + ")");
        }
    } catch (GitAPIException | IOException | UserNotFoundException e) {
        logger.error("Error while creating repository for site with path" + siteSandboxPath.toString(), e);
        toRet = false;
    } finally {
        generalLockService.unlock(gitLockKey);
        if (cloneResult != null) {
            cloneResult.close();
        }
    }
    return toRet;
}
Also used : Path(java.nio.file.Path) CloneCommand(org.eclipse.jgit.api.CloneCommand) UserNotFoundException(org.craftercms.studio.api.v1.exception.security.UserNotFoundException) UsernamePasswordCredentialsProvider(org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider) InvalidRemoteRepositoryCredentialsException(org.craftercms.studio.api.v1.exception.repository.InvalidRemoteRepositoryCredentialsException) ServiceLayerException(org.craftercms.studio.api.v1.exception.ServiceLayerException) InvalidRemoteRepositoryException(org.craftercms.studio.api.v1.exception.repository.InvalidRemoteRepositoryException) IOException(java.io.IOException) TransportException(org.eclipse.jgit.api.errors.TransportException) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) RemoteRepository(org.craftercms.studio.api.v2.dal.RemoteRepository) Repository(org.eclipse.jgit.lib.Repository) Git(org.eclipse.jgit.api.Git) TransportConfigCallback(org.eclipse.jgit.api.TransportConfigCallback) RemoteRepositoryNotFoundException(org.craftercms.studio.api.v1.exception.repository.RemoteRepositoryNotFoundException) InvalidRemoteException(org.eclipse.jgit.api.errors.InvalidRemoteException) SshTransport(org.eclipse.jgit.transport.SshTransport) Transport(org.eclipse.jgit.transport.Transport) File(java.io.File) SshTransport(org.eclipse.jgit.transport.SshTransport)

Example 28 with UserNotFoundException

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

the class GitContentRepository method writeContent.

@Override
public String writeContent(String site, String path, InputStream content) {
    // Write content to git and commit it
    String commitId = null;
    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);
        synchronized (helper.getRepository(site, StringUtils.isEmpty(site) ? GLOBAL : SANDBOX)) {
            Repository repo = helper.getRepository(site, StringUtils.isEmpty(site) ? GLOBAL : SANDBOX);
            if (repo != null) {
                if (helper.writeFile(repo, site, path, content)) {
                    PersonIdent user = helper.getCurrentUserIdent();
                    String username = securityService.getCurrentUser();
                    String comment = helper.getCommitMessage(REPO_SANDBOX_WRITE_COMMIT_MESSAGE).replace(REPO_COMMIT_MESSAGE_USERNAME_VAR, username).replace(REPO_COMMIT_MESSAGE_PATH_VAR, path);
                    commitId = helper.commitFile(repo, site, path, comment, user);
                } else {
                    logger.error("Failed to write content site: " + site + " path: " + path);
                }
            } else {
                logger.error("Missing repository during write for site: " + site + " path: " + path);
            }
        }
    } catch (ServiceLayerException | UserNotFoundException | CryptoException e) {
        logger.error("Unknown service error during write for site: " + site + " path: " + path, e);
    } finally {
        generalLockService.unlock(gitLockKey);
    }
    return commitId;
}
Also used : UserNotFoundException(org.craftercms.studio.api.v1.exception.security.UserNotFoundException) RemoteRepository(org.craftercms.studio.api.v2.dal.RemoteRepository) Repository(org.eclipse.jgit.lib.Repository) ContentRepository(org.craftercms.studio.api.v1.repository.ContentRepository) PersonIdent(org.eclipse.jgit.lib.PersonIdent) ServiceLayerException(org.craftercms.studio.api.v1.exception.ServiceLayerException) GitRepositoryHelper(org.craftercms.studio.api.v2.utils.GitRepositoryHelper) CryptoException(org.craftercms.commons.crypto.CryptoException)

Example 29 with UserNotFoundException

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

the class GitContentRepository method deleteContent.

@Override
public String deleteContent(String site, String path, String approver) {
    String commitId = null;
    boolean isPage = path.endsWith(FILE_SEPARATOR + INDEX_FILE);
    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);
        synchronized (helper.getRepository(site, StringUtils.isEmpty(site) ? GLOBAL : SANDBOX)) {
            Repository repo = helper.getRepository(site, StringUtils.isEmpty(site) ? GLOBAL : SANDBOX);
            try (Git git = new Git(repo)) {
                String pathToDelete = helper.getGitPath(path);
                Path parentToDelete = Paths.get(pathToDelete).getParent();
                RmCommand rmCommand = git.rm().addFilepattern(pathToDelete).setCached(false);
                retryingRepositoryOperationFacade.call(rmCommand);
                String pathToCommit = pathToDelete;
                if (isPage) {
                    pathToCommit = deleteParentFolder(git, parentToDelete, true);
                }
                // TODO: SJ: we need to define messages in a string table of sorts
                commitId = helper.commitFile(repo, site, pathToCommit, helper.getCommitMessage(REPO_DELETE_CONTENT_COMMIT_MESSAGE).replaceAll(PATTERN_PATH, path), StringUtils.isEmpty(approver) ? helper.getCurrentUserIdent() : helper.getAuthorIdent(approver));
            }
        }
    } catch (GitAPIException | UserNotFoundException | IOException e) {
        logger.error("Error while deleting content for site: " + site + " path: " + path, e);
    } catch (ServiceLayerException | CryptoException e) {
        logger.error("Unknown service error during delete for site: " + site + " path: " + path, e);
    } finally {
        generalLockService.unlock(gitLockKey);
    }
    return commitId;
}
Also used : Path(java.nio.file.Path) UserNotFoundException(org.craftercms.studio.api.v1.exception.security.UserNotFoundException) 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) RmCommand(org.eclipse.jgit.api.RmCommand) GitRepositoryHelper(org.craftercms.studio.api.v2.utils.GitRepositoryHelper) CryptoException(org.craftercms.commons.crypto.CryptoException)

Example 30 with UserNotFoundException

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

the class GitContentRepository method createFolder.

@Override
public String createFolder(String site, String path, String name) {
    // SJ: Git doesn't care about empty folders, so we will create the folders and put a 0 byte file in them
    String commitId = null;
    boolean result;
    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);
        synchronized (helper.getRepository(site, StringUtils.isEmpty(site) ? GLOBAL : SANDBOX)) {
            Path emptyFilePath = Paths.get(path, name, EMPTY_FILE);
            Repository repo = helper.getRepository(site, StringUtils.isEmpty(site) ? GLOBAL : SANDBOX);
            try {
                // Create basic file
                File file = new File(repo.getDirectory().getParent(), emptyFilePath.toString());
                // Create parent folders
                File folder = file.getParentFile();
                if (folder != null) {
                    if (!folder.exists()) {
                        folder.mkdirs();
                    }
                }
                // Create the file
                if (!file.createNewFile()) {
                    logger.error("error writing file: site: " + site + " path: " + emptyFilePath);
                    result = false;
                } else {
                    // Add the file to git
                    try (Git git = new Git(repo)) {
                        AddCommand addCommand = git.add().addFilepattern(helper.getGitPath(emptyFilePath.toString()));
                        retryingRepositoryOperationFacade.call(addCommand);
                        git.close();
                        result = true;
                    } catch (GitAPIException e) {
                        logger.error("error adding file to git: site: " + site + " path: " + emptyFilePath, e);
                        result = false;
                    }
                }
            } catch (IOException e) {
                logger.error("error writing file: site: " + site + " path: " + emptyFilePath, e);
                result = false;
            }
            if (result) {
                try {
                    commitId = helper.commitFile(repo, site, emptyFilePath.toString(), helper.getCommitMessage(REPO_CREATE_FOLDER_COMMIT_MESSAGE).replaceAll(PATTERN_SITE, site).replaceAll(PATTERN_PATH, path + FILE_SEPARATOR + name), helper.getCurrentUserIdent());
                } catch (ServiceLayerException | UserNotFoundException e) {
                    logger.error("Unknown service error during commit for site: " + site + " path: " + emptyFilePath, e);
                }
            }
        }
    } catch (CryptoException e) {
        logger.error("Unexpected service error creating folder " + name + " for site: " + site + " path: " + path, e);
    } finally {
        generalLockService.unlock(gitLockKey);
    }
    return commitId;
}
Also used : Path(java.nio.file.Path) UserNotFoundException(org.craftercms.studio.api.v1.exception.security.UserNotFoundException) 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) GitRepositoryHelper(org.craftercms.studio.api.v2.utils.GitRepositoryHelper) CryptoException(org.craftercms.commons.crypto.CryptoException) File(java.io.File) LockFile(org.eclipse.jgit.internal.storage.file.LockFile) 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