use of org.alfresco.rest.framework.core.exceptions.PermissionDeniedException in project alfresco-remote-api by Alfresco.
the class SitesImpl method addSiteMember.
public SiteMember addSiteMember(String siteId, SiteMember siteMember) {
String personId = people.validatePerson(siteMember.getPersonId());
SiteInfo siteInfo = validateSite(siteId);
if (siteInfo == null) {
// site does not exist
logger.debug("addSiteMember: site does not exist " + siteId + " person " + personId);
throw new EntityNotFoundException(siteId);
}
// set the site id to the short name (to deal with case sensitivity issues with using the siteId from the url)
siteId = siteInfo.getShortName();
String role = siteMember.getRole();
if (role == null) {
logger.debug("addSiteMember: Must provide a role " + siteMember);
throw new InvalidArgumentException("Must provide a role");
}
if (siteService.isMember(siteId, personId)) {
logger.debug("addSiteMember: " + personId + " is already a member of site " + siteId);
throw new ConstraintViolatedException(personId + " is already a member of site " + siteId);
}
if (!siteService.canAddMember(siteId, personId, role)) {
logger.debug("addSiteMember: PermissionDeniedException " + siteId + " person " + personId + " role " + role);
throw new PermissionDeniedException();
}
try {
siteService.setMembership(siteId, personId, role);
} catch (UnknownAuthorityException e) {
logger.debug("addSiteMember: UnknownAuthorityException " + siteId + " person " + personId + " role " + role);
throw new InvalidArgumentException("Unknown role '" + role + "'");
}
return siteMember;
}
use of org.alfresco.rest.framework.core.exceptions.PermissionDeniedException in project alfresco-remote-api by Alfresco.
the class GroupsImpl method getGroupsByPersonId.
@Override
public CollectionWithPagingInfo<Group> getGroupsByPersonId(String requestedPersonId, Parameters parameters) {
// Canonicalize the person ID, performing -me- alias substitution.
final String personId = people.validatePerson(requestedPersonId);
// Non-admins can only access their own data
// TODO: this is also in PeopleImpl.update(personId,personInfo) - refactor?
boolean isAdmin = authorityService.hasAdminAuthority();
String currentUserId = AuthenticationUtil.getFullyAuthenticatedUser();
if (!isAdmin && !currentUserId.equalsIgnoreCase(personId)) {
// The user is not an admin user and is not attempting to retrieve *their own* details.
throw new PermissionDeniedException();
}
Query q = parameters.getQuery();
Boolean isRootParam = null;
String zoneFilter = null;
if (q != null) {
GroupsQueryWalker propertyWalker = new GroupsQueryWalker();
QueryHelper.walk(q, propertyWalker);
isRootParam = propertyWalker.getIsRoot();
List<String> zonesParam = propertyWalker.getZones();
if (zonesParam != null) {
validateZonesParam(zonesParam);
zoneFilter = zonesParam.get(0);
}
}
final List<String> includeParam = parameters.getInclude();
Paging paging = parameters.getPaging();
// Retrieve sort column. This is limited for now to sort column due to
// v0 api implementation. Should be improved in the future.
Pair<String, Boolean> sortProp = getGroupsSortProp(parameters);
// Get all the authorities for a user, including but not limited to, groups.
Set<String> userAuthorities = runAsSystem(() -> authorityService.getAuthoritiesForUser(personId));
final Set<String> rootAuthorities = getAllRootAuthorities(AuthorityType.GROUP);
// Filter, transform and sort the list of user authorities into
// a suitable list of AuthorityInfo objects.
final String finalZoneFilter = zoneFilter;
final Boolean finalIsRootParam = isRootParam;
List<AuthorityInfo> groupAuthorities = userAuthorities.stream().filter(a -> a.startsWith(AuthorityType.GROUP.getPrefixString())).filter(a -> isRootPredicate(finalIsRootParam, rootAuthorities, a)).filter(a -> zonePredicate(a, finalZoneFilter)).map(this::getAuthorityInfo).sorted(new AuthorityInfoComparator(sortProp.getFirst(), sortProp.getSecond())).collect(Collectors.toList());
PagingResults<AuthorityInfo> pagingResult = Util.wrapPagingResults(paging, groupAuthorities);
// Create response.
final List<AuthorityInfo> page = pagingResult.getPage();
int totalItems = pagingResult.getTotalResultCount().getFirst();
// Transform the page of results into Group objects
List<Group> groups = page.stream().map(authority -> getGroup(authority, includeParam, rootAuthorities)).collect(Collectors.toList());
return CollectionWithPagingInfo.asPaged(paging, groups, pagingResult.hasMoreItems(), totalItems);
}
use of org.alfresco.rest.framework.core.exceptions.PermissionDeniedException in project alfresco-remote-api by Alfresco.
the class NodesImpl method lock.
@Override
public Node lock(String nodeId, LockInfo lockInfo, Parameters parameters) {
NodeRef nodeRef = validateOrLookupNode(nodeId, null);
if (isSpecialNode(nodeRef, getNodeType(nodeRef))) {
throw new PermissionDeniedException("Current user doesn't have permission to lock node " + nodeId);
}
if (!nodeMatches(nodeRef, Collections.singleton(ContentModel.TYPE_CONTENT), null, false)) {
throw new InvalidArgumentException("Node of type cm:content or a subtype is expected: " + nodeId);
}
lockInfo = validateLockInformation(lockInfo);
lockService.lock(nodeRef, lockInfo.getMappedType(), lockInfo.getTimeToExpire(), lockInfo.getLifetime());
return getFolderOrDocument(nodeId, parameters);
}
use of org.alfresco.rest.framework.core.exceptions.PermissionDeniedException in project alfresco-remote-api by Alfresco.
the class NodesImpl method upload.
@Override
public Node upload(String parentFolderNodeId, FormData formData, Parameters parameters) {
if (formData == null || !formData.getIsMultiPart()) {
throw new InvalidArgumentException("The request content-type is not multipart: " + parentFolderNodeId);
}
NodeRef parentNodeRef = validateOrLookupNode(parentFolderNodeId, null);
if (!nodeMatches(parentNodeRef, Collections.singleton(ContentModel.TYPE_FOLDER), null, false)) {
throw new InvalidArgumentException("NodeId of folder is expected: " + parentNodeRef.getId());
}
String fileName = null;
Content content = null;
boolean autoRename = false;
QName nodeTypeQName = ContentModel.TYPE_CONTENT;
// If a fileName clashes for a versionable file
boolean overwrite = false;
Boolean versionMajor = null;
String versionComment = null;
String relativePath = null;
String renditionNames = null;
Map<String, Object> qnameStrProps = new HashMap<>();
Map<QName, Serializable> properties = null;
for (FormData.FormField field : formData.getFields()) {
switch(field.getName().toLowerCase()) {
case "name":
String str = getStringOrNull(field.getValue());
if ((str != null) && (!str.isEmpty())) {
fileName = str;
}
break;
case "filedata":
if (field.getIsFile()) {
fileName = (fileName != null ? fileName : field.getFilename());
content = field.getContent();
}
break;
case "autorename":
autoRename = Boolean.valueOf(field.getValue());
break;
case "nodetype":
nodeTypeQName = createQName(getStringOrNull(field.getValue()));
if (!isSubClass(nodeTypeQName, ContentModel.TYPE_CONTENT)) {
throw new InvalidArgumentException("Can only upload type of cm:content: " + nodeTypeQName);
}
break;
case "overwrite":
overwrite = Boolean.valueOf(field.getValue());
break;
case "majorversion":
versionMajor = Boolean.valueOf(field.getValue());
break;
case "comment":
versionComment = getStringOrNull(field.getValue());
break;
case "relativepath":
relativePath = getStringOrNull(field.getValue());
break;
case "renditions":
renditionNames = getStringOrNull(field.getValue());
break;
default:
{
final String propName = field.getName();
if (propName.indexOf(QName.NAMESPACE_PREFIX) > -1) {
qnameStrProps.put(propName, field.getValue());
}
}
}
}
// result in a success message, but the files do not appear.
if (formData.getFields().length == 0) {
throw new ConstraintViolatedException("No disk space available");
}
// destination, or site + container or updateNodeRef
if ((fileName == null) || fileName.isEmpty() || (content == null)) {
throw new InvalidArgumentException("Required parameters are missing");
}
if (autoRename && overwrite) {
throw new InvalidArgumentException("Both 'overwrite' and 'autoRename' should not be true when uploading a file");
}
// if requested, make (get or create) path
parentNodeRef = getOrCreatePath(parentNodeRef, relativePath);
final QName assocTypeQName = ContentModel.ASSOC_CONTAINS;
final Set<String> renditions = getRequestedRenditions(renditionNames);
try {
// Map the given properties, if any.
if (qnameStrProps.size() > 0) {
properties = mapToNodeProperties(qnameStrProps);
}
/*
* Existing file handling
*/
NodeRef existingFile = nodeService.getChildByName(parentNodeRef, assocTypeQName, fileName);
if (existingFile != null) {
// File already exists, decide what to do
if (autoRename) {
// attempt to find a unique name
fileName = findUniqueName(parentNodeRef, fileName);
// drop-through !
} else if (overwrite && nodeService.hasAspect(existingFile, ContentModel.ASPECT_VERSIONABLE)) {
// overwrite existing (versionable) file
BasicContentInfo contentInfo = new ContentInfoImpl(content.getMimetype(), content.getEncoding(), -1, null);
return updateExistingFile(parentNodeRef, existingFile, fileName, contentInfo, content.getInputStream(), parameters, versionMajor, versionComment);
} else {
// name clash (and no autoRename or overwrite)
throw new ConstraintViolatedException(fileName + " already exists.");
}
}
// Note: pending REPO-159, we currently auto-enable versioning on new upload (but not when creating empty file)
if (versionMajor == null) {
versionMajor = true;
}
// Create a new file.
NodeRef nodeRef = createNewFile(parentNodeRef, fileName, nodeTypeQName, content, properties, assocTypeQName, parameters, versionMajor, versionComment);
// Create the response
final Node fileNode = getFolderOrDocumentFullInfo(nodeRef, parentNodeRef, nodeTypeQName, parameters);
// RA-1052
try {
List<ThumbnailDefinition> thumbnailDefs = getThumbnailDefs(renditions);
requestRenditions(thumbnailDefs, fileNode);
} catch (Exception ex) {
// Note: The log level is not 'error' as it could easily fill out the log file, especially in the Cloud.
if (logger.isDebugEnabled()) {
// Don't throw the exception as we don't want the the upload to fail, just log it.
logger.debug("Asynchronous request to create a rendition upon upload failed: " + ex.getMessage());
}
}
return fileNode;
// Do not clean formData temp files to allow for retries.
// Temp files will be deleted later when GC call DiskFileItem#finalize() method or by temp file cleaner.
} catch (AccessDeniedException ade) {
throw new PermissionDeniedException(ade.getMessage());
}
/*
* NOTE: Do not clean formData temp files to allow for retries. It's
* possible for a temp file to remain if max retry attempts are
* made, but this is rare, so leave to usual temp file cleanup.
*/
}
use of org.alfresco.rest.framework.core.exceptions.PermissionDeniedException in project alfresco-remote-api by Alfresco.
the class NodesImpl method deleteNode.
@Override
public void deleteNode(String nodeId, Parameters parameters) {
NodeRef nodeRef = validateOrLookupNode(nodeId, null);
if (isSpecialNode(nodeRef, getNodeType(nodeRef))) {
throw new PermissionDeniedException("Cannot delete: " + nodeId);
}
// default false (if not provided)
boolean permanentDelete = Boolean.valueOf(parameters.getParameter(PARAM_PERMANENT));
if (permanentDelete == true) {
boolean isAdmin = authorityService.hasAdminAuthority();
if (!isAdmin) {
String owner = ownableService.getOwner(nodeRef);
if (!AuthenticationUtil.getRunAsUser().equals(owner)) {
// non-owner/non-admin cannot permanently delete (even if they have delete permission)
throw new PermissionDeniedException("Non-owner/non-admin cannot permanently delete: " + nodeId);
}
}
// Set as temporary to delete node instead of archiving.
nodeService.addAspect(nodeRef, ContentModel.ASPECT_TEMPORARY, null);
}
final ActivityInfo activityInfo = getActivityInfo(getParentNodeRef(nodeRef), nodeRef);
postActivity(Activity_Type.DELETED, activityInfo, true);
fileFolderService.delete(nodeRef);
}
Aggregations