use of org.alfresco.repo.security.permissions.AccessDeniedException in project alfresco-remote-api by Alfresco.
the class UserFeedRetrieverWebScript method executeImpl.
/* (non-Javadoc)
* @see org.alfresco.web.scripts.DeclarativeWebScript#executeImpl(org.alfresco.web.scripts.WebScriptRequest, org.alfresco.web.scripts.WebScriptResponse)
*/
@Override
protected Map<String, Object> executeImpl(WebScriptRequest req, Status status) {
// retrieve requested format
String format = req.getFormat();
if (format == null || format.length() == 0) {
format = getDescription().getDefaultFormat();
}
// process extension
String extensionPath = req.getExtensionPath();
String[] extParts = extensionPath == null ? new String[1] : extensionPath.split("/");
String feedUserId = null;
if (extParts.length == 1) {
feedUserId = extParts[0];
} else if (extParts.length > 1) {
throw new AlfrescoRuntimeException("Unexpected extension: " + extensionPath);
}
// process arguments
// optional
String siteId = req.getParameter(PARAM_SITE_ID);
// optional
String exclThisUserStr = req.getParameter(PARAM_EXCLUDE_THIS_USER);
// optional
String exclOtherUsersStr = req.getParameter(PARAM_EXCLUDE_OTHER_USERS);
// optional
String onlyFollowingStr = req.getParameter(PARAM_ONLY_FOLLOWING);
// optional
String activityFilterStr = req.getParameter(PARAM_ACTIVITY_FILTER);
boolean exclThisUser = false;
if ((exclThisUserStr != null) && (exclThisUserStr.equalsIgnoreCase("true") || exclThisUserStr.equalsIgnoreCase("t"))) {
exclThisUser = true;
}
boolean exclOtherUsers = false;
if ((exclOtherUsersStr != null) && (exclOtherUsersStr.equalsIgnoreCase("true") || exclOtherUsersStr.equalsIgnoreCase("t"))) {
exclOtherUsers = true;
}
Set<String> userFilter = null;
if ((onlyFollowingStr != null) && (onlyFollowingStr.equalsIgnoreCase("true") || onlyFollowingStr.equalsIgnoreCase("t"))) {
userFilter = new HashSet<String>();
if (subscriptionService.isActive()) {
PagingFollowingResults following = subscriptionService.getFollowing(AuthenticationUtil.getRunAsUser(), new PagingRequest(-1, null));
if (following.getPage() != null) {
for (String userName : following.getPage()) {
userFilter.add(this.userNamesAreCaseSensitive ? userName : userName.toLowerCase());
}
}
}
}
Set<String> activityFilter = null;
if (activityFilterStr != null) {
activityFilter = new HashSet<String>();
String[] activities = activityFilterStr.split(",");
for (String s : activities) {
if (s.trim().length() > 0) {
activityFilter.add(s.trim());
}
}
if (activityFilter.size() == 0) {
activityFilter = null;
}
}
if ((feedUserId == null) || (feedUserId.length() == 0)) {
feedUserId = AuthenticationUtil.getFullyAuthenticatedUser();
}
// atom -> atomentry
if (format.equals("atomfeed") || format.equals("atom")) {
format = "atomentry";
}
Map<String, Object> model = new HashMap<String, Object>();
try {
List<String> feedEntries = activityService.getUserFeedEntries(feedUserId, siteId, exclThisUser, exclOtherUsers, userFilter, activityFilter);
if (format.equals(FeedTaskProcessor.FEED_FORMAT_JSON)) {
model.put("feedEntries", feedEntries);
model.put("siteId", siteId);
} else {
List<Map<String, Object>> activityFeedModels = new ArrayList<Map<String, Object>>();
try {
for (String feedEntry : feedEntries) {
activityFeedModels.add(JSONtoFmModel.convertJSONObjectToMap(feedEntry));
}
} catch (JSONException je) {
throw new AlfrescoRuntimeException("Unable to get user feed entries: " + je.getMessage());
}
model.put("feedEntries", activityFeedModels);
model.put("feedUserId", feedUserId);
}
} catch (AccessDeniedException ade) {
status.setCode(Status.STATUS_UNAUTHORIZED);
logger.warn("Unable to get user feed entries for '" + feedUserId + "' - currently logged in as '" + AuthenticationUtil.getFullyAuthenticatedUser() + "'");
return null;
}
return model;
}
use of org.alfresco.repo.security.permissions.AccessDeniedException in project alfresco-remote-api by Alfresco.
the class MoveMethodTest method testMNT_10380_ThrowAccessDeniedExceptionWhenUserLacksPermissions.
@Test(expected = AccessDeniedException.class)
public void testMNT_10380_ThrowAccessDeniedExceptionWhenUserLacksPermissions() throws Exception {
when(mockFileFolderService.rename(sourceNodeRef, "dest.doc")).thenThrow(new AccessDeniedException("Access denied in test by mockFileFolderService"));
moveMethod.moveOrCopy(sourceNodeRef, sourceParentNodeRef, destParentNodeRef, "dest.doc");
}
use of org.alfresco.repo.security.permissions.AccessDeniedException in project alfresco-remote-api by Alfresco.
the class PutMethodTest method testPutContentToWorkingCopy.
/**
* Putting a content to a working copy file
* <p>
* Create and check out a file by user1
* <p>
* Try to put the content to the working copy by user2
*
* See MNT-8614.
*/
@SuppressWarnings("deprecation")
@Test
public void testPutContentToWorkingCopy() throws Exception {
FileInfo folder = fileFolderService.create(companyHomeNodeRef, "folder-" + GUID.generate(), ContentModel.TYPE_FOLDER);
permissionService.setInheritParentPermissions(folder.getNodeRef(), false);
permissionService.setPermission(folder.getNodeRef(), USER1_NAME, permissionService.getAllPermission(), true);
AuthenticationUtil.setFullyAuthenticatedUser(USER1_NAME);
FileInfo testFileInfo = fileFolderService.create(folder.getNodeRef(), "file-" + GUID.generate(), ContentModel.TYPE_CONTENT);
NodeRef workingCopyNodeRef = checkOutCheckInService.checkout(testFileInfo.getNodeRef());
String workingCopyName = fileFolderService.getFileInfo(workingCopyNodeRef).getName();
String pathToWC = "/" + folder.getName() + "/" + workingCopyName;
String pathToOriginal = "/" + folder.getName() + "/" + testFileInfo.getName();
// Negative test, try to edit the WC without permissions.
AuthenticationUtil.setFullyAuthenticatedUser(USER2_NAME);
try {
lockService.lock(workingCopyNodeRef, LockType.WRITE_LOCK);
} catch (AccessDeniedException ade) {
// expected
}
try {
executeMethod(WebDAV.METHOD_LOCK, pathToWC, davLockInfoUser2File, null);
fail("The LOCK execution should fail with a 401 error");
} catch (WebDAVServerException wse) {
// The execution failed and it is expected
assertTrue("The status code was " + wse.getHttpStatusCode() + ", but should be " + HttpServletResponse.SC_UNAUTHORIZED, wse.getHttpStatusCode() == HttpServletResponse.SC_UNAUTHORIZED);
} catch (Exception e) {
fail("Unexpected exception occurred: " + (e.getCause() != null ? e.getCause().getMessage() : e.getMessage()));
}
// Construct IF HEADER
String lockToken = workingCopyNodeRef.getId() + WebDAV.LOCK_TOKEN_SEPERATOR + USER2_NAME;
String lockHeaderValue = "(<" + WebDAV.OPAQUE_LOCK_TOKEN + lockToken + ">)";
HashMap<String, String> headers = new HashMap<String, String>();
headers.put(WebDAV.HEADER_IF, lockHeaderValue);
try {
executeMethod(WebDAV.METHOD_PUT, pathToWC, testDataFile, headers);
fail("The PUT execution should fail with a 423 error");
} catch (WebDAVServerException wse) {
// The execution failed and it is expected
assertTrue("The status code was " + wse.getHttpStatusCode() + ", but should be " + HttpServletResponse.SC_UNAUTHORIZED, wse.getHttpStatusCode() == HttpServletResponse.SC_UNAUTHORIZED);
} catch (Exception e) {
fail("Unexpected exception occurred: " + (e.getCause() != null ? e.getCause().getMessage() : e.getMessage()));
}
// Positive test
AuthenticationUtil.setAdminUserAsFullyAuthenticatedUser();
permissionService.setPermission(folder.getNodeRef(), USER2_NAME, permissionService.getAllPermission(), true);
AuthenticationUtil.setFullyAuthenticatedUser(USER2_NAME);
try {
executeMethod(WebDAV.METHOD_LOCK, pathToWC, davLockInfoUser2File, null);
assertEquals("File should be locked", LockStatus.LOCK_OWNER, lockService.getLockStatus(workingCopyNodeRef));
} catch (Exception e) {
fail("Failed to lock a file: " + (e.getCause() != null ? e.getCause().getMessage() : e.getMessage()));
}
headers = new HashMap<String, String>();
headers.put(WebDAV.HEADER_IF, lockHeaderValue);
try {
executeMethod(WebDAV.METHOD_PUT, pathToWC, testDataFile, headers);
assertTrue("File does not exist.", nodeService.exists(workingCopyNodeRef));
assertEquals("Filename is not correct", workingCopyName, nodeService.getProperty(workingCopyNodeRef, ContentModel.PROP_NAME));
assertTrue("Expected return status is " + HttpServletResponse.SC_NO_CONTENT + ", but returned is " + response.getStatus(), HttpServletResponse.SC_NO_CONTENT == response.getStatus());
assertTrue("File should have NO_CONTENT aspect", nodeService.hasAspect(workingCopyNodeRef, ContentModel.ASPECT_NO_CONTENT));
InputStream updatedFileIS = fileFolderService.getReader(workingCopyNodeRef).getContentInputStream();
byte[] updatedFile = IOUtils.toByteArray(updatedFileIS);
updatedFileIS.close();
assertTrue("The content has to be equal", ArrayUtils.isEquals(testDataFile, updatedFile));
} catch (Exception e) {
fail("Failed to upload a file: " + (e.getCause() != null ? e.getCause().getMessage() : e.getMessage()));
}
headers = new HashMap<String, String>();
headers.put(WebDAV.HEADER_LOCK_TOKEN, "<" + WebDAV.OPAQUE_LOCK_TOKEN + lockToken + ">");
try {
executeMethod(WebDAV.METHOD_UNLOCK, pathToWC, null, headers);
assertTrue("Expected return status is " + HttpServletResponse.SC_NO_CONTENT + ", but returned is " + response.getStatus(), HttpServletResponse.SC_NO_CONTENT == response.getStatus());
assertFalse("File should not have NO_CONTENT aspect", nodeService.hasAspect(workingCopyNodeRef, ContentModel.ASPECT_NO_CONTENT));
assertEquals("File should be unlocked", LockStatus.NO_LOCK, lockService.getLockStatus(workingCopyNodeRef));
} catch (Exception e) {
fail("Failed to unlock a file: " + (e.getCause() != null ? e.getCause().getMessage() : e.getMessage()));
}
// Negative test try to lock or edit the original file
AuthenticationUtil.setFullyAuthenticatedUser(USER2_NAME);
try {
lockService.lock(testFileInfo.getNodeRef(), LockType.WRITE_LOCK);
} catch (UnableToAquireLockException uale) {
// expected
}
try {
executeMethod(WebDAV.METHOD_LOCK, pathToOriginal, davLockInfoUser2File, null);
fail("The LOCK execution should fail with a 423 error");
} catch (WebDAVServerException wse) {
// The execution failed and it is expected
assertTrue("The status code was " + wse.getHttpStatusCode() + ", but should be " + WebDAV.WEBDAV_SC_LOCKED, wse.getHttpStatusCode() == WebDAV.WEBDAV_SC_LOCKED);
} catch (Exception e) {
fail("Unexpected exception occurred: " + (e.getCause() != null ? e.getCause().getMessage() : e.getMessage()));
}
// Construct IF HEADER
lockToken = testFileInfo.getNodeRef().getId() + WebDAV.LOCK_TOKEN_SEPERATOR + USER2_NAME;
lockHeaderValue = "(<" + WebDAV.OPAQUE_LOCK_TOKEN + lockToken + ">)";
headers = new HashMap<String, String>();
headers.put(WebDAV.HEADER_IF, lockHeaderValue);
try {
executeMethod(WebDAV.METHOD_PUT, pathToOriginal, testDataFile, headers);
fail("The PUT execution should fail with a 423 error");
} catch (WebDAVServerException wse) {
// The execution failed and it is expected
assertTrue("The status code was " + wse.getHttpStatusCode() + ", but should be " + WebDAV.WEBDAV_SC_LOCKED, wse.getHttpStatusCode() == WebDAV.WEBDAV_SC_LOCKED);
} catch (Exception e) {
fail("Unexpected exception occurred: " + (e.getCause() != null ? e.getCause().getMessage() : e.getMessage()));
}
AuthenticationUtil.setFullyAuthenticatedUser(USER1_NAME);
checkOutCheckInService.checkin(workingCopyNodeRef, null);
AuthenticationUtil.setAdminUserAsFullyAuthenticatedUser();
nodeService.deleteNode(folder.getNodeRef());
}
use of org.alfresco.repo.security.permissions.AccessDeniedException in project alfresco-remote-api by Alfresco.
the class PutMethod method executeImpl.
/**
* Execute the WebDAV request
*
* @exception WebDAVServerException
*/
protected void executeImpl() throws WebDAVServerException, Exception {
if (logger.isDebugEnabled()) {
String path = getPath();
String userName = getDAVHelper().getAuthenticationService().getCurrentUserName();
logger.debug("Put node: \n" + " user: " + userName + "\n" + " path: " + path + "\n" + "noContent: " + noContent);
}
FileFolderService fileFolderService = getFileFolderService();
// Get the status for the request path
LockInfo nodeLockInfo = null;
try {
contentNodeInfo = getNodeForPath(getRootNodeRef(), getPath());
// make sure that we are not trying to use a folder
if (contentNodeInfo.isFolder()) {
throw new WebDAVServerException(HttpServletResponse.SC_BAD_REQUEST);
}
nodeLockInfo = checkNode(contentNodeInfo);
// 'Unhide' nodes hidden by us and behave as though we created them
NodeRef contentNodeRef = contentNodeInfo.getNodeRef();
if (fileFolderService.isHidden(contentNodeRef) && !getDAVHelper().isRenameShuffle(getPath())) {
fileFolderService.setHidden(contentNodeRef, false);
created = true;
}
} catch (FileNotFoundException e) {
// the file doesn't exist - create it
String[] paths = getDAVHelper().splitPath(getPath());
try {
FileInfo parentNodeInfo = getNodeForPath(getRootNodeRef(), paths[0]);
// create file
contentNodeInfo = getDAVHelper().createFile(parentNodeInfo, paths[1]);
created = true;
} catch (FileNotFoundException ee) {
// bad path
throw new WebDAVServerException(HttpServletResponse.SC_CONFLICT);
} catch (FileExistsException ee) {
// ALF-7079 fix, retry: it looks like concurrent access (file not found but file exists)
throw new ConcurrencyFailureException("Concurrent access was detected.", ee);
}
}
String userName = getDAVHelper().getAuthenticationService().getCurrentUserName();
LockInfo lockInfo = getDAVLockService().getLockInfo(contentNodeInfo.getNodeRef());
if (lockInfo != null) {
if (lockInfo.isLocked() && !lockInfo.getOwner().equals(userName)) {
if (logger.isDebugEnabled()) {
String path = getPath();
String owner = lockInfo.getOwner();
logger.debug("Node locked: path=[" + path + "], owner=[" + owner + "], current user=[" + userName + "]");
}
// Indicate that the resource is locked
throw new WebDAVServerException(WebDAV.WEBDAV_SC_LOCKED);
}
}
// ALF-16808: We disable the versionable aspect if we are overwriting
// empty content because it's probably part of a compound operation to
// create a new single version
boolean disabledVersioning = false;
try {
// Disable versioning if we are overwriting an empty file with content
NodeRef nodeRef = contentNodeInfo.getNodeRef();
ContentData contentData = (ContentData) getNodeService().getProperty(nodeRef, ContentModel.PROP_CONTENT);
if ((contentData == null || contentData.getSize() == 0) && getNodeService().hasAspect(nodeRef, ContentModel.ASPECT_VERSIONABLE)) {
getDAVHelper().getPolicyBehaviourFilter().disableBehaviour(nodeRef, ContentModel.ASPECT_VERSIONABLE);
disabledVersioning = true;
}
// Access the content
ContentWriter writer = fileFolderService.getWriter(contentNodeInfo.getNodeRef());
// set content properties
writer.guessMimetype(contentNodeInfo.getName());
writer.guessEncoding();
// Get the input stream from the request data
InputStream is = m_request.getInputStream();
// Write the new data to the content node
writer.putContent(is);
// - the node does not have any content (zero length binaries included)
if (nodeLockInfo != null && nodeLockInfo.isExclusive() && !(ContentData.hasContent(contentData) && contentData.getSize() > 0)) {
getNodeService().addAspect(contentNodeInfo.getNodeRef(), ContentModel.ASPECT_NO_CONTENT, null);
}
// Ask for the document metadata to be extracted
Action extract = getActionService().createAction(ContentMetadataExtracter.EXECUTOR_NAME);
if (extract != null) {
extract.setExecuteAsynchronously(false);
getActionService().executeAction(extract, contentNodeInfo.getNodeRef());
}
// from the original specified in the request, update it.
if (m_strContentType == null || !m_strContentType.equals(writer.getMimetype())) {
String oldMimeType = m_strContentType;
m_strContentType = writer.getMimetype();
if (logger.isDebugEnabled()) {
logger.debug("Mimetype originally specified as " + oldMimeType + ", now guessed to be " + m_strContentType);
}
}
// Record the uploaded file's size
fileSize = writer.getSize();
// Set the response status, depending if the node existed or not
m_response.setStatus(created ? HttpServletResponse.SC_CREATED : HttpServletResponse.SC_NO_CONTENT);
} catch (AccessDeniedException e) {
throw new WebDAVServerException(HttpServletResponse.SC_FORBIDDEN, e);
} catch (Throwable e) {
// we are about to give up
if (noContent && RetryingTransactionHelper.extractRetryCause(e) == null) {
// remove the 0 bytes content if save operation failed or was cancelled
final NodeRef nodeRef = contentNodeInfo.getNodeRef();
getTransactionService().getRetryingTransactionHelper().doInTransaction(new RetryingTransactionCallback<String>() {
public String execute() throws Throwable {
getNodeService().deleteNode(nodeRef);
if (logger.isDebugEnabled()) {
logger.debug("Put failed. DELETE " + getPath());
}
return null;
}
}, false, false);
}
throw new WebDAVServerException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e);
} finally {
if (disabledVersioning) {
getDAVHelper().getPolicyBehaviourFilter().enableBehaviour(contentNodeInfo.getNodeRef(), ContentModel.ASPECT_VERSIONABLE);
}
}
postActivity();
}
use of org.alfresco.repo.security.permissions.AccessDeniedException in project alfresco-remote-api by Alfresco.
the class NodesImpl method resolveNodeByPath.
protected NodeRef resolveNodeByPath(final NodeRef parentNodeRef, String path, boolean checkForCompanyHome) {
final List<String> pathElements = getPathElements(path);
if (!pathElements.isEmpty() && checkForCompanyHome) {
/*
if (nodeService.getRootNode(parentNodeRef.getStoreRef()).equals(parentNodeRef))
{
// special case
NodeRef chNodeRef = repositoryHelper.getCompanyHome();
String chName = (String) nodeService.getProperty(chNodeRef, ContentModel.PROP_NAME);
if (chName.equals(pathElements.get(0)))
{
pathElements = pathElements.subList(1, pathElements.size());
parentNodeRef = chNodeRef;
}
}
*/
}
FileInfo fileInfo = null;
try {
if (!pathElements.isEmpty()) {
fileInfo = fileFolderService.resolveNamePath(parentNodeRef, pathElements);
} else {
fileInfo = fileFolderService.getFileInfo(parentNodeRef);
if (fileInfo == null) {
throw new EntityNotFoundException(parentNodeRef.getId());
}
}
} catch (FileNotFoundException fnfe) {
// convert checked exception
throw new NotFoundException("The entity with relativePath: " + path + " was not found.");
} catch (AccessDeniedException ade) {
// return 404 instead of 403 (as per security review - uuid vs path)
throw new NotFoundException("The entity with relativePath: " + path + " was not found.");
}
return fileInfo.getNodeRef();
}
Aggregations