Search in sources :

Example 21 with UserNotFoundException

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

the class GitContentRepository method moveContent.

@Override
public Map<String, String> moveContent(String site, String fromPath, String toPath, String newName) {
    Map<String, String> toRet = new TreeMap<String, String>();
    String commitId;
    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);
            String gitFromPath = helper.getGitPath(fromPath);
            String gitToPath;
            if (StringUtils.isEmpty(newName)) {
                gitToPath = helper.getGitPath(toPath);
            } else {
                gitToPath = helper.getGitPath(toPath + FILE_SEPARATOR + newName);
            }
            try (Git git = new Git(repo)) {
                // Check if destination is a file, then this is a rename operation
                // Perform rename and exit
                Path sourcePath = Paths.get(repo.getDirectory().getParent(), gitFromPath);
                File sourceFile = sourcePath.toFile();
                Path targetPath = Paths.get(repo.getDirectory().getParent(), gitToPath);
                File targetFile = targetPath.toFile();
                if (sourceFile.getCanonicalFile().equals(targetFile.getCanonicalFile())) {
                    sourceFile.renameTo(targetFile);
                } else {
                    if (targetFile.isFile()) {
                        if (sourceFile.isFile()) {
                            sourceFile.renameTo(targetFile);
                        } else {
                            // This is not a valid operation
                            logger.error("Invalid move operation: Trying to rename a directory to a file " + "for site: " + site + " fromPath: " + fromPath + " toPath: " + toPath + " newName: " + newName);
                        }
                    } else if (sourceFile.isDirectory()) {
                        // Check if we're moving a single file or whole subtree
                        File[] dirList = sourceFile.listFiles();
                        for (File child : dirList) {
                            if (!child.equals(sourceFile)) {
                                FileUtils.moveToDirectory(child, targetFile, true);
                            }
                        }
                        FileUtils.deleteDirectory(sourceFile);
                    } else {
                        if (sourceFile.isFile()) {
                            FileUtils.moveFile(sourceFile, targetFile);
                        } else {
                            FileUtils.moveToDirectory(sourceFile, targetFile, true);
                        }
                    }
                }
                // The operation is done on disk, now it's time to commit
                AddCommand addCommand = git.add().addFilepattern(gitToPath);
                retryingRepositoryOperationFacade.call(addCommand);
                StatusCommand statusCommand = git.status().addPath(gitToPath);
                Status gitStatus = retryingRepositoryOperationFacade.call(statusCommand);
                Set<String> changeSet = gitStatus.getAdded();
                for (String pathToCommit : changeSet) {
                    String pathRemoved = pathToCommit.replace(gitToPath, gitFromPath);
                    CommitCommand commitCommand = git.commit().setOnly(pathToCommit).setOnly(pathRemoved).setAuthor(helper.getCurrentUserIdent()).setCommitter(helper.getCurrentUserIdent()).setMessage(helper.getCommitMessage(REPO_MOVE_CONTENT_COMMIT_MESSAGE).replaceAll(PATTERN_FROM_PATH, fromPath).replaceAll(PATTERN_TO_PATH, toPath + (StringUtils.isNotEmpty(newName) ? newName : EMPTY)));
                    RevCommit commit = retryingRepositoryOperationFacade.call(commitCommand);
                    commitId = commit.getName();
                    toRet.put(pathToCommit, commitId);
                }
            }
        }
    } catch (IOException | GitAPIException | ServiceLayerException | UserNotFoundException | CryptoException e) {
        logger.error("Error while moving content for site: " + site + " fromPath: " + fromPath + " toPath: " + toPath + " newName: " + newName);
    } finally {
        generalLockService.unlock(gitLockKey);
    }
    return toRet;
}
Also used : Path(java.nio.file.Path) Status(org.eclipse.jgit.api.Status) UserNotFoundException(org.craftercms.studio.api.v1.exception.security.UserNotFoundException) ServiceLayerException(org.craftercms.studio.api.v1.exception.ServiceLayerException) IOException(java.io.IOException) TreeMap(java.util.TreeMap) StatusCommand(org.eclipse.jgit.api.StatusCommand) 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) CommitCommand(org.eclipse.jgit.api.CommitCommand) 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) RevCommit(org.eclipse.jgit.revwalk.RevCommit)

Example 22 with UserNotFoundException

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

the class SecurityServiceImpl method validateToken.

@Override
@ValidateParams
public boolean validateToken(@ValidateStringParam(name = "token") String token) throws UserNotFoundException, UserExternallyManagedException, ServiceLayerException {
    boolean toRet = false;
    String decryptedToken = decryptToken(token);
    if (StringUtils.isNotEmpty(decryptedToken)) {
        StringTokenizer tokenElements = new StringTokenizer(decryptedToken, "|");
        if (tokenElements.countTokens() == 3) {
            String username = tokenElements.nextToken();
            User userProfile = userServiceInternal.getUserByIdOrUsername(-1, username);
            if (userProfile == null) {
                logger.info("User profile not found for " + username);
                throw new UserNotFoundException();
            } else {
                if (userProfile.isExternallyManaged()) {
                    throw new UserExternallyManagedException();
                } else {
                    long tokenTimestamp = Long.parseLong(tokenElements.nextToken());
                    if (tokenTimestamp < System.currentTimeMillis()) {
                        toRet = false;
                    } else {
                        toRet = true;
                    }
                }
            }
        }
    }
    return toRet;
}
Also used : UserNotFoundException(org.craftercms.studio.api.v1.exception.security.UserNotFoundException) UserExternallyManagedException(org.craftercms.studio.api.v1.exception.security.UserExternallyManagedException) StringTokenizer(java.util.StringTokenizer) User(org.craftercms.studio.api.v2.dal.User) ValidateParams(org.craftercms.commons.validation.annotations.param.ValidateParams)

Example 23 with UserNotFoundException

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

the class SecurityServiceImpl method isSiteAdmin.

@Override
@ValidateParams
public boolean isSiteAdmin(@ValidateStringParam(name = "username") String username, String site) {
    boolean toRet = false;
    try {
        if (userServiceInternal.isUserMemberOfGroup(username, SYSTEM_ADMIN_GROUP)) {
            return true;
        }
        List<Group> groups = userServiceInternal.getUserGroups(-1, username);
        if (CollectionUtils.isNotEmpty(groups)) {
            Map<String, List<String>> roleMappings = configurationService.geRoleMappings(site);
            if (MapUtils.isNotEmpty(roleMappings)) {
                for (Group group : groups) {
                    String groupName = group.getGroupName();
                    List<String> roles = roleMappings.get(groupName);
                    if (roles.contains(ADMIN_ROLE)) {
                        toRet = true;
                    }
                }
            }
        }
    } catch (ServiceLayerException | UserNotFoundException e) {
        logger.warn("Error getting user memberships", e);
    }
    return toRet;
}
Also used : UserNotFoundException(org.craftercms.studio.api.v1.exception.security.UserNotFoundException) Group(org.craftercms.studio.api.v2.dal.Group) ServiceLayerException(org.craftercms.studio.api.v1.exception.ServiceLayerException) ArrayList(java.util.ArrayList) List(java.util.List) ValidateParams(org.craftercms.commons.validation.annotations.param.ValidateParams)

Example 24 with UserNotFoundException

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

the class SecurityServiceImpl method getUserRoles.

@Override
@ValidateParams
public Set<String> getUserRoles(@ValidateStringParam(name = "site") final String site, @ValidateStringParam(name = "user") String user, boolean includeGlobal) {
    try {
        // TODO: We should replace this with userService.getUserSiteRoles, but that one is protected by permissions.
        // TODO: When the UserService is refactored to use UserServiceInternal, we could use that method and
        // TODO: remove this one
        List<Group> groups = userServiceInternal.getUserGroups(-1, user);
        if (groups != null && groups.size() > 0) {
            logger.debug("Groups for " + user + " in " + site + ": " + groups);
            PermissionsConfigTO rolesConfig = loadConfiguration(site, getRoleMappingsFileName());
            Set<String> userRoles = new HashSet<String>();
            if (rolesConfig != null) {
                Map<String, List<String>> rolesMap = rolesConfig.getRoles();
                for (Group group : groups) {
                    String groupName = group.getGroupName();
                    if (StringUtils.equals(groupName, SYSTEM_ADMIN_GROUP)) {
                        Collection<List<String>> mapValues = rolesMap.values();
                        mapValues.forEach(valueList -> {
                            userRoles.addAll(valueList);
                        });
                        break;
                    } else {
                        List<String> roles = rolesMap.get(groupName);
                        if (roles != null) {
                            userRoles.addAll(roles);
                        }
                    }
                }
            }
            if (includeGlobal) {
                PermissionsConfigTO globalRolesConfig = loadGlobalRolesConfiguration();
                addGlobalUserRoles(user, userRoles, globalRolesConfig);
                List<String> groupNames = groups.stream().map(x -> x.getGroupName()).collect(Collectors.toList());
                addGlobalGroupRoles(userRoles, groupNames, globalRolesConfig);
            }
            return userRoles;
        } else {
            logger.debug("No groups found for " + user + " in " + site);
        }
    } catch (ServiceLayerException | UserNotFoundException e) {
        logger.error("Error while getting groups for user {0}", e);
    }
    return new HashSet<>(0);
}
Also used : ValidateSecurePathParam(org.craftercms.commons.validation.annotations.param.ValidateSecurePathParam) UserServiceInternal(org.craftercms.studio.api.v2.service.security.internal.UserServiceInternal) ZonedDateTime(java.time.ZonedDateTime) SecretKeySpec(javax.crypto.spec.SecretKeySpec) StringUtils(org.apache.commons.lang3.StringUtils) User(org.craftercms.studio.api.v2.dal.User) UserDetailsManager(org.craftercms.studio.api.v1.service.security.UserDetailsManager) KEY_EXTERNALLY_MANAGED(org.craftercms.studio.api.v1.constant.SecurityConstants.KEY_EXTERNALLY_MANAGED) Map(java.util.Map) CONFIGURATION_SITE_ROLE_MAPPINGS_FILE_NAME(org.craftercms.studio.api.v2.utils.StudioConfiguration.CONFIGURATION_SITE_ROLE_MAPPINGS_FILE_NAME) ZoneOffset(java.time.ZoneOffset) CronJobContext(org.craftercms.studio.api.v1.job.CronJobContext) CONFIGURATION_GLOBAL_PERMISSION_MAPPINGS_FILE_NAME(org.craftercms.studio.api.v2.utils.StudioConfiguration.CONFIGURATION_GLOBAL_PERMISSION_MAPPINGS_FILE_NAME) MODULE_STUDIO(org.craftercms.studio.api.v1.constant.StudioConstants.MODULE_STUDIO) SiteFeed(org.craftercms.studio.api.v1.dal.SiteFeed) Set(java.util.Set) SiteService(org.craftercms.studio.api.v1.service.site.SiteService) JavaMailSender(org.springframework.mail.javamail.JavaMailSender) SECURITY_AUTHENTICATION_TYPE(org.craftercms.studio.api.v1.constant.StudioConstants.SECURITY_AUTHENTICATION_TYPE) KEY_EMAIL(org.craftercms.studio.api.v1.constant.SecurityConstants.KEY_EMAIL) StandardCharsets(java.nio.charset.StandardCharsets) ContentTypeConfigTO(org.craftercms.studio.api.v1.to.ContentTypeConfigTO) FILE_SEPARATOR(org.craftercms.studio.api.v1.constant.StudioConstants.FILE_SEPARATOR) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) ServiceLayerException(org.craftercms.studio.api.v1.exception.ServiceLayerException) SECURITY_CIPHER_KEY(org.craftercms.studio.api.v2.utils.StudioConfiguration.SECURITY_CIPHER_KEY) InvalidKeyException(java.security.InvalidKeyException) KEY_LASTNAME(org.craftercms.studio.api.v1.constant.SecurityConstants.KEY_LASTNAME) SYSTEM_ADMIN_GROUP(org.craftercms.studio.api.v1.constant.StudioConstants.SYSTEM_ADMIN_GROUP) PasswordDoesNotMatchException(org.craftercms.studio.api.v1.exception.security.PasswordDoesNotMatchException) Document(org.dom4j.Document) SECURITY_TYPE(org.craftercms.studio.api.v2.utils.StudioConfiguration.SECURITY_TYPE) ADMIN_ROLE(org.craftercms.studio.api.v1.constant.StudioConstants.ADMIN_ROLE) CONFIGURATION_SITE_PERMISSION_MAPPINGS_FILE_NAME(org.craftercms.studio.api.v2.utils.StudioConfiguration.CONFIGURATION_SITE_PERMISSION_MAPPINGS_FILE_NAME) CollectionUtils(org.apache.commons.collections4.CollectionUtils) AuthenticationChain(org.craftercms.studio.api.v2.service.security.AuthenticationChain) InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) ArrayList(java.util.ArrayList) SECURITY_CIPHER_ALGORITHM(org.craftercms.studio.api.v2.utils.StudioConfiguration.SECURITY_CIPHER_ALGORITHM) HttpServletRequest(javax.servlet.http.HttpServletRequest) IvParameterSpec(javax.crypto.spec.IvParameterSpec) ContentTypeService(org.craftercms.studio.api.v1.service.content.ContentTypeService) StringTokenizer(java.util.StringTokenizer) PermissionsConfigTO(org.craftercms.studio.api.v1.to.PermissionsConfigTO) RepositoryEventContext(org.craftercms.studio.api.v1.ebus.RepositoryEventContext) SECURITY_CIPHER_TYPE(org.craftercms.studio.api.v2.utils.StudioConfiguration.SECURITY_CIPHER_TYPE) UserExternallyManagedException(org.craftercms.studio.api.v1.exception.security.UserExternallyManagedException) ConfigurationService(org.craftercms.studio.api.v2.service.config.ConfigurationService) StudioConstants(org.craftercms.studio.api.v1.constant.StudioConstants) IOException(java.io.IOException) ObjectFactory(org.springframework.beans.factory.ObjectFactory) Group(org.craftercms.studio.api.v2.dal.Group) SecurityService(org.craftercms.studio.api.v1.service.security.SecurityService) SessionTokenUtils(org.craftercms.studio.impl.v1.util.SessionTokenUtils) MAIL_FROM_DEFAULT(org.craftercms.studio.api.v2.utils.StudioConfiguration.MAIL_FROM_DEFAULT) MAIL_SMTP_AUTH(org.craftercms.studio.api.v2.utils.StudioConfiguration.MAIL_SMTP_AUTH) ValidateStringParam(org.craftercms.commons.validation.annotations.param.ValidateStringParam) Node(org.dom4j.Node) FreeMarkerConfig(org.springframework.web.servlet.view.freemarker.FreeMarkerConfig) UserNotFoundException(org.craftercms.studio.api.v1.exception.security.UserNotFoundException) AuditServiceInternal(org.craftercms.studio.api.v2.service.audit.internal.AuditServiceInternal) ValidateParams(org.craftercms.commons.validation.annotations.param.ValidateParams) AuditLog(org.craftercms.studio.api.v2.dal.AuditLog) HTTP_SESSION_ATTRIBUTE_AUTHENTICATION(org.craftercms.studio.api.v1.constant.StudioConstants.HTTP_SESSION_ATTRIBUTE_AUTHENTICATION) HttpSession(javax.servlet.http.HttpSession) IllegalBlockSizeException(javax.crypto.IllegalBlockSizeException) Collection(java.util.Collection) GroupService(org.craftercms.studio.api.v2.service.security.GroupService) CONFIGURATION_GLOBAL_SYSTEM_SITE(org.craftercms.studio.api.v2.utils.StudioConfiguration.CONFIGURATION_GLOBAL_SYSTEM_SITE) Collectors(java.util.stream.Collectors) SECURITY_SESSION_TIMEOUT(org.craftercms.studio.api.v2.utils.StudioConfiguration.SECURITY_SESSION_TIMEOUT) Base64(java.util.Base64) List(java.util.List) StudioConfiguration(org.craftercms.studio.api.v2.utils.StudioConfiguration) TARGET_TYPE_USER(org.craftercms.studio.api.v2.dal.AuditLogConstants.TARGET_TYPE_USER) RequestContext(org.craftercms.commons.http.RequestContext) Logger(org.craftercms.studio.api.v1.log.Logger) HashMap(java.util.HashMap) Cipher(javax.crypto.Cipher) HashSet(java.util.HashSet) DocumentException(org.dom4j.DocumentException) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) LoggerFactory(org.craftercms.studio.api.v1.log.LoggerFactory) UserDetails(org.springframework.security.core.userdetails.UserDetails) StudioXmlConstants(org.craftercms.studio.api.v1.constant.StudioXmlConstants) MapUtils(org.apache.commons.collections4.MapUtils) ContentService(org.craftercms.studio.api.v1.service.content.ContentService) HttpServletResponse(javax.servlet.http.HttpServletResponse) CONFIGURATION_GLOBAL_ROLE_MAPPINGS_FILE_NAME(org.craftercms.studio.api.v2.utils.StudioConfiguration.CONFIGURATION_GLOBAL_ROLE_MAPPINGS_FILE_NAME) SiteNotFoundException(org.craftercms.studio.api.v1.exception.SiteNotFoundException) KEY_USERNAME(org.craftercms.studio.api.v1.constant.SecurityConstants.KEY_USERNAME) BadPaddingException(javax.crypto.BadPaddingException) OPERATION_LOGOUT(org.craftercms.studio.api.v2.dal.AuditLogConstants.OPERATION_LOGOUT) GeneralLockService(org.craftercms.studio.api.v1.service.GeneralLockService) CONFIGURATION_GLOBAL_CONFIG_BASE_PATH(org.craftercms.studio.api.v2.utils.StudioConfiguration.CONFIGURATION_GLOBAL_CONFIG_BASE_PATH) Element(org.dom4j.Element) KEY_FIRSTNAME(org.craftercms.studio.api.v1.constant.SecurityConstants.KEY_FIRSTNAME) Authentication(org.craftercms.studio.impl.v2.service.security.Authentication) CONFIGURATION_ENVIRONMENT_ACTIVE(org.craftercms.studio.api.v2.utils.StudioConfiguration.CONFIGURATION_ENVIRONMENT_ACTIVE) UserNotFoundException(org.craftercms.studio.api.v1.exception.security.UserNotFoundException) Group(org.craftercms.studio.api.v2.dal.Group) PermissionsConfigTO(org.craftercms.studio.api.v1.to.PermissionsConfigTO) ServiceLayerException(org.craftercms.studio.api.v1.exception.ServiceLayerException) ArrayList(java.util.ArrayList) List(java.util.List) HashSet(java.util.HashSet) ValidateParams(org.craftercms.commons.validation.annotations.param.ValidateParams)

Example 25 with UserNotFoundException

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

the class SecurityServiceImpl method getUserProfileByGitName.

@Override
public Map<String, Object> getUserProfileByGitName(@ValidateStringParam(name = "firstNameLastName") String gitName) throws ServiceLayerException, UserNotFoundException {
    Map<String, Object> toRet = new HashMap<String, Object>();
    User u = userServiceInternal.getUserByGitName(gitName);
    if (u != null) {
        toRet.put(KEY_USERNAME, u.getUsername());
        toRet.put(KEY_FIRSTNAME, u.getFirstName());
        toRet.put(KEY_LASTNAME, u.getLastName());
        toRet.put(KEY_EMAIL, u.getEmail());
        toRet.put(KEY_EXTERNALLY_MANAGED, u.isExternallyManaged());
        String authenticationType = studioConfiguration.getProperty(SECURITY_TYPE);
        toRet.put(SECURITY_AUTHENTICATION_TYPE, authenticationType);
    } else {
        throw new UserNotFoundException("User " + gitName + " not found");
    }
    return toRet;
}
Also used : UserNotFoundException(org.craftercms.studio.api.v1.exception.security.UserNotFoundException) User(org.craftercms.studio.api.v2.dal.User) HashMap(java.util.HashMap)

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