Search in sources :

Example 1 with HasPermission

use of org.craftercms.commons.security.permissions.annotations.HasPermission in project studio by craftercms.

the class CmisServiceImpl method uploadContent.

@Override
@HasPermission(type = DefaultPermission.class, action = "upload_content_cmis")
public CmisUploadItem uploadContent(@ProtectedResourceId(SITE_ID_RESOURCE_ID) String siteId, String cmisRepoId, String cmisPath, String filename, InputStream content) throws CmisUnavailableException, CmisTimeoutException, CmisRepositoryNotFoundException, CmisPathNotFoundException, ConfigurationException {
    DataSourceRepository repositoryConfig = getConfiguration(siteId, cmisRepoId);
    CmisUploadItem cmisUploadItem = new CmisUploadItem();
    logger.debug("Create new CMIS session");
    Session session = createCMISSession(repositoryConfig);
    if (session != null) {
        String contentPath = Paths.get(repositoryConfig.getBasePath(), cmisPath).toString();
        logger.debug("Find object for CMIS path: " + contentPath);
        CmisObject cmisObject = session.getObjectByPath(contentPath);
        if (cmisObject != null) {
            if (BaseTypeId.CMIS_FOLDER.equals(cmisObject.getBaseTypeId())) {
                CmisObject docObject = null;
                try {
                    docObject = session.getObjectByPath(Paths.get(contentPath, filename).toString());
                } catch (CmisBaseException e) {
                    // Content does not exist - no error
                    logger.debug("File " + filename + " does not exist at " + contentPath);
                }
                MimetypesFileTypeMap mimeTypesMap = new MimetypesFileTypeMap();
                String mimeType = mimeTypesMap.getContentType(filename);
                ContentStream contentStream = session.getObjectFactory().createContentStream(filename, -1, mimeType, content);
                Folder folder = (Folder) cmisObject;
                cmisUploadItem.setName(filename);
                cmisUploadItem.setFolder(false);
                cmisUploadItem.setFileExtension(FilenameUtils.getExtension(filename));
                if (docObject != null) {
                    Document doc = (Document) docObject;
                    doc.setContentStream(contentStream, true);
                    String contentId = doc.getId();
                    StringTokenizer st = new StringTokenizer(contentId, ";");
                    if (st.hasMoreTokens()) {
                        cmisUploadItem.setUrl(repositoryConfig.getDownloadUrlRegex().replace(ITEM_ID, st.nextToken()));
                    }
                    session.removeObjectFromCache(doc.getId());
                } else {
                    Map<String, Object> properties = new HashMap<String, Object>();
                    properties.put(OBJECT_TYPE_ID, CMIS_DOCUMENT.value());
                    properties.put(NAME, filename);
                    Document newDoc = folder.createDocument(properties, contentStream, null);
                    session.removeObjectFromCache(newDoc.getId());
                    String contentId = newDoc.getId();
                    StringTokenizer st = new StringTokenizer(contentId, ";");
                    if (st.hasMoreTokens()) {
                        cmisUploadItem.setUrl(repositoryConfig.getDownloadUrlRegex().replace(ITEM_ID, st.nextToken()));
                    }
                }
                session.clear();
            } else if (CMIS_DOCUMENT.equals(cmisObject.getBaseTypeId())) {
                throw new CmisPathNotFoundException();
            }
        } else {
            throw new CmisPathNotFoundException();
        }
    } else {
        throw new CmisUnauthorizedException();
    }
    return cmisUploadItem;
}
Also used : DataSourceRepository(org.craftercms.studio.api.v2.dal.DataSourceRepository) MimetypesFileTypeMap(javax.activation.MimetypesFileTypeMap) HashMap(java.util.HashMap) Folder(org.apache.chemistry.opencmis.client.api.Folder) Document(org.apache.chemistry.opencmis.client.api.Document) ContentStream(org.apache.chemistry.opencmis.commons.data.ContentStream) StringTokenizer(java.util.StringTokenizer) CmisBaseException(org.apache.chemistry.opencmis.commons.exceptions.CmisBaseException) CmisUploadItem(org.craftercms.studio.model.rest.CmisUploadItem) CmisObject(org.apache.chemistry.opencmis.client.api.CmisObject) CmisObject(org.apache.chemistry.opencmis.client.api.CmisObject) CmisUnauthorizedException(org.apache.chemistry.opencmis.commons.exceptions.CmisUnauthorizedException) CmisPathNotFoundException(org.craftercms.studio.api.v1.exception.CmisPathNotFoundException) Session(org.apache.chemistry.opencmis.client.api.Session) HasPermission(org.craftercms.commons.security.permissions.annotations.HasPermission)

Example 2 with HasPermission

use of org.craftercms.commons.security.permissions.annotations.HasPermission 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 3 with HasPermission

use of org.craftercms.commons.security.permissions.annotations.HasPermission in project studio by craftercms.

the class UserServiceImpl method getUserSiteRoles.

@Override
@HasPermission(type = DefaultPermission.class, action = "read_users")
public List<String> getUserSiteRoles(long userId, String username, String site) throws ServiceLayerException, UserNotFoundException {
    List<Group> groups = userServiceInternal.getUserGroups(userId, username);
    if (CollectionUtils.isNotEmpty(groups)) {
        Map<String, List<String>> roleMappings = configurationService.geRoleMappings(site);
        Set<String> userRoles = new LinkedHashSet<>();
        if (MapUtils.isNotEmpty(roleMappings)) {
            for (Group group : groups) {
                String groupName = group.getGroupName();
                if (groupName.equals(SYSTEM_ADMIN_GROUP)) {
                    // If sysadmin, return all roles
                    Collection<List<String>> roleSets = roleMappings.values();
                    for (List<String> roleSet : roleSets) {
                        userRoles.addAll(roleSet);
                    }
                    break;
                } else {
                    List<String> roles = roleMappings.get(groupName);
                    if (CollectionUtils.isNotEmpty(roles)) {
                        userRoles.addAll(roles);
                    }
                }
            }
        }
        return new ArrayList<>(userRoles);
    } else {
        return Collections.emptyList();
    }
}
Also used : LinkedHashSet(java.util.LinkedHashSet) Group(org.craftercms.studio.api.v2.dal.Group) ArrayList(java.util.ArrayList) List(java.util.List) ArrayList(java.util.ArrayList) HasPermission(org.craftercms.commons.security.permissions.annotations.HasPermission)

Example 4 with HasPermission

use of org.craftercms.commons.security.permissions.annotations.HasPermission in project studio by craftercms.

the class UserServiceImpl method createUser.

@Override
@HasPermission(type = DefaultPermission.class, action = "create_users")
public User createUser(User user) throws UserAlreadyExistsException, ServiceLayerException, AuthenticationException {
    try {
        entitlementValidator.validateEntitlement(EntitlementType.USER, 1);
    } catch (EntitlementException e) {
        throw new ServiceLayerException("Unable to complete request due to entitlement limits. Please contact " + "your system administrator.", e);
    }
    User toRet = userServiceInternal.createUser(user);
    SiteFeed siteFeed = siteService.getSite(studioConfiguration.getProperty(CONFIGURATION_GLOBAL_SYSTEM_SITE));
    AuditLog auditLog = auditServiceInternal.createAuditLogEntry();
    auditLog.setOperation(OPERATION_CREATE);
    auditLog.setSiteId(siteFeed.getId());
    auditLog.setActorId(getCurrentUser().getUsername());
    auditLog.setPrimaryTargetId(user.getUsername());
    auditLog.setPrimaryTargetType(TARGET_TYPE_USER);
    auditLog.setPrimaryTargetValue(user.getUsername());
    auditServiceInternal.insertAuditLog(auditLog);
    return toRet;
}
Also used : EntitlementException(org.craftercms.commons.entitlements.exception.EntitlementException) User(org.craftercms.studio.api.v2.dal.User) AuthenticatedUser(org.craftercms.studio.model.AuthenticatedUser) SiteFeed(org.craftercms.studio.api.v1.dal.SiteFeed) ServiceLayerException(org.craftercms.studio.api.v1.exception.ServiceLayerException) AuditLog(org.craftercms.studio.api.v2.dal.AuditLog) HasPermission(org.craftercms.commons.security.permissions.annotations.HasPermission)

Example 5 with HasPermission

use of org.craftercms.commons.security.permissions.annotations.HasPermission in project studio by craftercms.

the class AwsMediaConvertServiceImpl method uploadVideo.

/**
 * {@inheritDoc}
 */
@Override
@HasPermission(type = DefaultPermission.class, action = "s3 write")
public MediaConvertResult uploadVideo(@ValidateStringParam @ProtectedResourceId("siteId") final String site, @ValidateStringParam final String inputProfileId, @ValidateStringParam final String outputProfileId, @ValidateStringParam final String filename, final InputStream content) throws AwsException {
    MediaConvertProfile profile = getProfile(site, inputProfileId);
    AmazonS3 s3Client = getS3Client(profile);
    AWSMediaConvert mediaConvertClient = getMediaConvertClient(profile);
    logger.info("Starting upload of file {0} for site {1}", filename, site);
    AwsUtils.uploadStream(profile.getInputPath(), filename, s3Client, partSize, filename, content);
    logger.info("Upload of file {0} for site {1} complete", filename, site);
    String originalName = FilenameUtils.getBaseName(filename);
    JobTemplate jobTemplate = mediaConvertClient.getJobTemplate(new GetJobTemplateRequest().withName(profile.getTemplate())).getJobTemplate();
    JobSettings jobSettings = new JobSettings().withInputs(new Input().withFileInput(AwsUtils.getS3Url(profile.getInputPath(), filename)));
    CreateJobRequest createJobRequest = new CreateJobRequest().withJobTemplate(profile.getTemplate()).withSettings(jobSettings).withRole(profile.getRole()).withQueue(profile.getQueue());
    logger.info("Starting transcode job of file {0} for site {1}", filename, site);
    CreateJobResult createJobResult = mediaConvertClient.createJob(createJobRequest);
    logger.debug("Job {0} started", createJobResult.getJob().getArn());
    return buildResult(jobTemplate, createJobResult, outputProfileId, originalName);
}
Also used : AmazonS3(com.amazonaws.services.s3.AmazonS3) AWSMediaConvert(com.amazonaws.services.mediaconvert.AWSMediaConvert) Input(com.amazonaws.services.mediaconvert.model.Input) CreateJobResult(com.amazonaws.services.mediaconvert.model.CreateJobResult) JobSettings(com.amazonaws.services.mediaconvert.model.JobSettings) MediaConvertProfile(org.craftercms.studio.api.v1.aws.mediaconvert.MediaConvertProfile) GetJobTemplateRequest(com.amazonaws.services.mediaconvert.model.GetJobTemplateRequest) JobTemplate(com.amazonaws.services.mediaconvert.model.JobTemplate) CreateJobRequest(com.amazonaws.services.mediaconvert.model.CreateJobRequest) HasPermission(org.craftercms.commons.security.permissions.annotations.HasPermission)

Aggregations

HasPermission (org.craftercms.commons.security.permissions.annotations.HasPermission)25 ArrayList (java.util.ArrayList)13 SiteFeed (org.craftercms.studio.api.v1.dal.SiteFeed)11 AuditLog (org.craftercms.studio.api.v2.dal.AuditLog)11 AuditLogParameter (org.craftercms.studio.api.v2.dal.AuditLogParameter)8 Group (org.craftercms.studio.api.v2.dal.Group)8 User (org.craftercms.studio.api.v2.dal.User)6 AuthenticatedUser (org.craftercms.studio.model.AuthenticatedUser)6 ServiceLayerException (org.craftercms.studio.api.v1.exception.ServiceLayerException)5 List (java.util.List)4 StringTokenizer (java.util.StringTokenizer)4 CmisObject (org.apache.chemistry.opencmis.client.api.CmisObject)4 Document (org.apache.chemistry.opencmis.client.api.Document)4 Session (org.apache.chemistry.opencmis.client.api.Session)4 AmazonS3 (com.amazonaws.services.s3.AmazonS3)3 StringUtils (org.apache.commons.lang3.StringUtils)3 DataSourceRepository (org.craftercms.studio.api.v2.dal.DataSourceRepository)3 Sardine (com.github.sardine.Sardine)2 InputStream (java.io.InputStream)2 Collections (java.util.Collections)2