use of org.alfresco.repo.security.permissions.AccessDeniedException in project acs-community-packaging by Alfresco.
the class Utils method addErrorMessage.
/**
* Adds a global error message and logs exception details
*
* @param msg The error message
* @param err The exception to log
*/
public static void addErrorMessage(String msg, Throwable err) {
FacesContext context = FacesContext.getCurrentInstance();
FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_ERROR, msg, msg);
context.addMessage(null, facesMsg);
if (err != null) {
if ((err instanceof InvalidNodeRefException == false && err instanceof AccessDeniedException == false && err instanceof NoTransformerException == false) || logger.isDebugEnabled()) {
logger.error(msg, err);
}
}
}
use of org.alfresco.repo.security.permissions.AccessDeniedException in project acs-community-packaging by Alfresco.
the class NodePathLinkRenderer method encodeEnd.
/**
* @see javax.faces.render.Renderer#encodeEnd(javax.faces.context.FacesContext, javax.faces.component.UIComponent)
*/
public void encodeEnd(FacesContext context, UIComponent component) throws IOException {
// always check for this flag - as per the spec
if (!component.isRendered()) {
return;
}
Writer out = context.getResponseWriter();
// make sure we have a NodeRef or Path from the 'value' property ValueBinding
Path path = null;
NodeRef nodeRef = null;
Object val = ((UINodePath) component).getValue();
if (val instanceof NodeRef) {
nodeRef = (NodeRef) val;
} else if (val instanceof Path) {
path = (Path) val;
} else if (val != null) {
throw new IllegalArgumentException("UINodePath component 'value' " + "property must resolve to a NodeRef " + "or Path. Got a " + val.getClass().getName());
}
if (val != null) {
boolean isBreadcrumb = false;
Boolean breadcrumb = (Boolean) component.getAttributes().get("breadcrumb");
if (breadcrumb != null) {
isBreadcrumb = breadcrumb.booleanValue();
}
boolean isDisabled = false;
Boolean disabled = (Boolean) component.getAttributes().get("disabled");
if (disabled != null) {
isDisabled = disabled.booleanValue();
}
boolean showLeaf = false;
Boolean showLeafBool = (Boolean) component.getAttributes().get("showLeaf");
if (showLeafBool != null) {
showLeaf = showLeafBool.booleanValue();
}
// use Spring JSF integration to get the node service bean
NodeService service = getNodeService(context);
UserTransaction tx = null;
try {
tx = Repository.getUserTransaction(FacesContext.getCurrentInstance(), true);
tx.begin();
if (path == null) {
path = service.getPath(nodeRef);
}
if (isBreadcrumb == false || isDisabled == true) {
out.write(buildPathAsSingular(context, component, path, showLeaf, isDisabled));
} else {
out.write(buildPathAsBreadcrumb(context, component, path, showLeaf));
}
tx.commit();
} catch (InvalidNodeRefException refErr) {
// this error simply means we cannot output the path
try {
if (tx != null) {
tx.rollback();
}
} catch (Exception tex) {
}
} catch (AccessDeniedException accessErr) {
// this error simply means we cannot output the path
try {
if (tx != null) {
tx.rollback();
}
} catch (Exception tex) {
}
} catch (Throwable err) {
try {
if (tx != null) {
tx.rollback();
}
} catch (Exception tex) {
}
throw new RuntimeException(err);
}
}
}
use of org.alfresco.repo.security.permissions.AccessDeniedException 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.repo.security.permissions.AccessDeniedException in project alfresco-remote-api by Alfresco.
the class NodesImpl method makeFolders.
private NodeRef makeFolders(NodeRef parentNodeRef, List<String> pathElements) {
NodeRef currentParentRef = parentNodeRef;
// just loop and create if necessary
for (final String element : pathElements) {
final NodeRef contextNodeRef = currentParentRef;
// does it exist?
// Navigation should not check permissions
NodeRef nodeRef = AuthenticationUtil.runAs(new RunAsWork<NodeRef>() {
@Override
public NodeRef doWork() throws Exception {
return nodeService.getChildByName(contextNodeRef, ContentModel.ASSOC_CONTAINS, element);
}
}, AuthenticationUtil.getSystemUserName());
if (nodeRef == null) {
try {
// Checks for create permissions as the fileFolderService is a public service.
FileInfo createdFileInfo = fileFolderService.create(currentParentRef, element, ContentModel.TYPE_FOLDER);
currentParentRef = createdFileInfo.getNodeRef();
} catch (AccessDeniedException ade) {
throw new PermissionDeniedException(ade.getMessage());
} catch (FileExistsException fex) {
// Assume concurrency failure, so retry
throw new ConcurrencyFailureException(fex.getMessage());
}
} else if (!isSubClass(nodeRef, ContentModel.TYPE_FOLDER, false)) {
String parentName = (String) nodeService.getProperty(contextNodeRef, ContentModel.PROP_NAME);
throw new ConstraintViolatedException("Name [" + element + "] already exists in the target parent: " + parentName);
} else {
// it exists
currentParentRef = nodeRef;
}
}
return currentParentRef;
}
use of org.alfresco.repo.security.permissions.AccessDeniedException in project alfresco-remote-api by Alfresco.
the class NodesImpl method getFolderOrDocument.
@Override
public Node getFolderOrDocument(final NodeRef nodeRef, NodeRef parentNodeRef, QName nodeTypeQName, List<String> includeParam, Map<String, UserInfo> mapUserInfo) {
if (mapUserInfo == null) {
mapUserInfo = new HashMap<>(2);
}
if (includeParam == null) {
includeParam = Collections.emptyList();
}
Node node;
Map<QName, Serializable> properties = nodeService.getProperties(nodeRef);
PathInfo pathInfo = null;
if (includeParam.contains(PARAM_INCLUDE_PATH)) {
ChildAssociationRef archivedParentAssoc = (ChildAssociationRef) properties.get(ContentModel.PROP_ARCHIVED_ORIGINAL_PARENT_ASSOC);
pathInfo = lookupPathInfo(nodeRef, archivedParentAssoc);
}
if (nodeTypeQName == null) {
nodeTypeQName = getNodeType(nodeRef);
}
if (parentNodeRef == null) {
parentNodeRef = getParentNodeRef(nodeRef);
}
Type type = getType(nodeTypeQName, nodeRef);
if (type == null) {
// not direct folder (or file) ...
// might be sub-type of cm:cmobject (or a cm:link pointing to cm:cmobject or possibly even another cm:link)
node = new Node(nodeRef, parentNodeRef, properties, mapUserInfo, sr);
node.setIsFolder(false);
node.setIsFile(false);
} else if (type.equals(Type.DOCUMENT)) {
node = new Document(nodeRef, parentNodeRef, properties, mapUserInfo, sr);
} else if (type.equals(Type.FOLDER)) {
node = new Folder(nodeRef, parentNodeRef, properties, mapUserInfo, sr);
} else {
throw new RuntimeException("Unexpected - should not reach here: " + type);
}
if (includeParam.size() > 0) {
node.setProperties(mapFromNodeProperties(properties, includeParam, mapUserInfo, EXCLUDED_NS, EXCLUDED_PROPS));
}
Set<QName> aspects = null;
if (includeParam.contains(PARAM_INCLUDE_ASPECTNAMES)) {
aspects = nodeService.getAspects(nodeRef);
node.setAspectNames(mapFromNodeAspects(aspects, EXCLUDED_NS, EXCLUDED_ASPECTS));
}
if (includeParam.contains(PARAM_INCLUDE_ISLINK)) {
boolean isLink = isSubClass(nodeTypeQName, ContentModel.TYPE_LINK);
node.setIsLink(isLink);
}
if (includeParam.contains(PARAM_INCLUDE_ISLOCKED)) {
boolean isLocked = isLocked(nodeRef, aspects);
node.setIsLocked(isLocked);
}
if (includeParam.contains(PARAM_INCLUDE_ISFAVORITE)) {
boolean isFavorite = isFavorite(nodeRef);
node.setIsFavorite(isFavorite);
}
if (includeParam.contains(PARAM_INCLUDE_ALLOWABLEOPERATIONS)) {
// note: refactor when requirements change
Map<String, String> mapPermsToOps = new HashMap<>(3);
mapPermsToOps.put(PermissionService.DELETE, OP_DELETE);
mapPermsToOps.put(PermissionService.ADD_CHILDREN, OP_CREATE);
mapPermsToOps.put(PermissionService.WRITE, OP_UPDATE);
mapPermsToOps.put(PermissionService.CHANGE_PERMISSIONS, OP_UPDATE_PERMISSIONS);
List<String> allowableOperations = new ArrayList<>(3);
for (Entry<String, String> kv : mapPermsToOps.entrySet()) {
String perm = kv.getKey();
String op = kv.getValue();
if (perm.equals(PermissionService.ADD_CHILDREN) && Type.DOCUMENT.equals(type)) {
// special case: do not return "create" (as an allowable op) for file/content types - note: 'type' can be null
continue;
} else if (perm.equals(PermissionService.DELETE) && (isSpecialNode(nodeRef, nodeTypeQName))) {
// special case: do not return "delete" (as an allowable op) for specific system nodes
continue;
} else if (permissionService.hasPermission(nodeRef, perm) == AccessStatus.ALLOWED) {
allowableOperations.add(op);
}
}
node.setAllowableOperations((allowableOperations.size() > 0) ? allowableOperations : null);
}
if (includeParam.contains(PARAM_INCLUDE_PERMISSIONS)) {
Boolean inherit = permissionService.getInheritParentPermissions(nodeRef);
List<NodePermissions.NodePermission> inheritedPerms = new ArrayList<>(5);
List<NodePermissions.NodePermission> setDirectlyPerms = new ArrayList<>(5);
Set<String> settablePerms = null;
boolean allowRetrievePermission = true;
try {
for (AccessPermission accessPerm : permissionService.getAllSetPermissions(nodeRef)) {
NodePermissions.NodePermission nodePerm = new NodePermissions.NodePermission(accessPerm.getAuthority(), accessPerm.getPermission(), accessPerm.getAccessStatus().toString());
if (accessPerm.isSetDirectly()) {
setDirectlyPerms.add(nodePerm);
} else {
inheritedPerms.add(nodePerm);
}
}
settablePerms = permissionService.getSettablePermissions(nodeRef);
} catch (AccessDeniedException ade) {
// ignore - ie. denied access to retrieve permissions, eg. non-admin on root (Company Home)
allowRetrievePermission = false;
}
// returned only node info that he's allowed to see
if (allowRetrievePermission) {
NodePermissions nodePerms = new NodePermissions(inherit, inheritedPerms, setDirectlyPerms, settablePerms);
node.setPermissions(nodePerms);
}
}
if (includeParam.contains(PARAM_INCLUDE_ASSOCIATION)) {
// Ugh ... can we optimise this and return the actual assoc directly (via FileFolderService/GetChildrenCQ) ?
ChildAssociationRef parentAssocRef = nodeService.getPrimaryParent(nodeRef);
// note: parentAssocRef.parentRef can be null for -root- node !
if ((parentAssocRef == null) || (parentAssocRef.getParentRef() == null) || (!parentAssocRef.getParentRef().equals(parentNodeRef))) {
List<ChildAssociationRef> parentAssocRefs = nodeService.getParentAssocs(nodeRef);
for (ChildAssociationRef pAssocRef : parentAssocRefs) {
if (pAssocRef.getParentRef().equals(parentNodeRef)) {
// for now, assume same parent/child cannot appear more than once (due to unique name)
parentAssocRef = pAssocRef;
break;
}
}
}
if (parentAssocRef != null) {
QName assocTypeQName = parentAssocRef.getTypeQName();
if ((assocTypeQName != null) && (!EXCLUDED_NS.contains(assocTypeQName.getNamespaceURI()))) {
AssocChild childAssoc = new AssocChild(assocTypeQName.toPrefixString(namespaceService), parentAssocRef.isPrimary());
node.setAssociation(childAssoc);
}
}
}
node.setNodeType(nodeTypeQName.toPrefixString(namespaceService));
node.setPath(pathInfo);
return node;
}
Aggregations