use of org.alfresco.service.cmr.security.PermissionService in project acs-community-packaging by Alfresco.
the class BaseServlet method checkAccess.
/**
* Check the user has the given permission on the given node. If they do not either force a log on if this is a guest
* user or forward to an error page.
*
* @param req
* the request
* @param res
* the response
* @param nodeRef
* the node in question
* @param allowLogIn
* Indicates whether guest users without access to the node should be redirected to the log in page. If
* <code>false</code>, a status 403 forbidden page is displayed instead.
* @return <code>true</code>, if the user has access
* @throws IOException
* Signals that an I/O exception has occurred.
* @throws ServletException
* On other errors
*/
public boolean checkAccess(HttpServletRequest req, HttpServletResponse res, NodeRef nodeRef, String permission, boolean allowLogIn) throws IOException, ServletException {
ServletContext sc = getServletContext();
ServiceRegistry serviceRegistry = getServiceRegistry(sc);
PermissionService permissionService = serviceRegistry.getPermissionService();
// check that the user has the permission
if (permissionService.hasPermission(nodeRef, permission) == AccessStatus.DENIED) {
if (logger.isDebugEnabled())
logger.debug("User does not have " + permission + " permission for NodeRef: " + nodeRef.toString());
if (allowLogIn && serviceRegistry.getAuthorityService().hasGuestAuthority()) {
if (logger.isDebugEnabled())
logger.debug("Redirecting to login page...");
redirectToLoginPage(req, res, sc);
} else {
if (logger.isDebugEnabled())
logger.debug("Forwarding to error page...");
Application.handleSystemError(sc, req, res, MSG_ERROR_PERMISSIONS, HttpServletResponse.SC_FORBIDDEN, logger);
}
return false;
}
return true;
}
use of org.alfresco.service.cmr.security.PermissionService in project acs-community-packaging by Alfresco.
the class ExternalAccessServlet method service.
/**
* @see javax.servlet.http.HttpServlet#service(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
*/
protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
String uri = req.getRequestURI();
if (logger.isDebugEnabled())
logger.debug("Processing URL: " + uri + (req.getQueryString() != null ? ("?" + req.getQueryString()) : ""));
AuthenticationStatus status = servletAuthenticate(req, res);
if (status == AuthenticationStatus.Failure) {
return;
}
setNoCacheHeaders(res);
uri = uri.substring(req.getContextPath().length());
StringTokenizer t = new StringTokenizer(uri, "/");
int tokenCount = t.countTokens();
if (tokenCount < 2) {
throw new IllegalArgumentException("Externally addressable URL did not contain all required args: " + uri);
}
// skip servlet name
t.nextToken();
String outcome = t.nextToken();
// get rest of the tokens arguments
String[] args = new String[tokenCount - 2];
for (int i = 0; i < tokenCount - 2; i++) {
args[i] = t.nextToken();
}
if (logger.isDebugEnabled())
logger.debug("External outcome found: " + outcome);
// we almost always need this bean reference
FacesContext fc = FacesHelper.getFacesContext(req, res, getServletContext());
BrowseBean browseBean = (BrowseBean) FacesHelper.getManagedBean(fc, "BrowseBean");
// get services we need
ServiceRegistry serviceRegistry = getServiceRegistry(getServletContext());
PermissionService permissionService = serviceRegistry.getPermissionService();
// as we are potentially coming in from an external app reset the view stack
Stack viewStack = (Stack) fc.getExternalContext().getSessionMap().get("_alfViewStack");
if (viewStack != null) {
viewStack.clear();
if (logger.isDebugEnabled())
logger.debug("Cleared view stack");
}
// setup is required for certain outcome requests
if (OUTCOME_DOCDETAILS.equals(outcome)) {
NodeRef nodeRef = null;
if (args[0].equals(WebDAVServlet.WEBDAV_PREFIX)) {
nodeRef = resolveWebDAVPath(fc, args);
} else if (args.length == 3) {
StoreRef storeRef = new StoreRef(args[0], args[1]);
nodeRef = new NodeRef(storeRef, args[2]);
}
if (nodeRef != null) {
// check that the user has at least READ access - else redirect to an error or login page
if (!checkAccess(req, res, nodeRef, PermissionService.READ_CONTENT, true)) {
return;
}
// setup the Document on the browse bean
browseBean.setupContentAction(nodeRef.getId(), true);
}
// perform the appropriate JSF navigation outcome
NavigationHandler navigationHandler = fc.getApplication().getNavigationHandler();
navigationHandler.handleNavigation(fc, null, "dialog:" + OUTCOME_DOCDETAILS);
} else if (OUTCOME_SPACEDETAILS.equals(outcome)) {
NodeRef nodeRef = null;
if (args[0].equals(WebDAVServlet.WEBDAV_PREFIX)) {
nodeRef = resolveWebDAVPath(fc, args);
} else if (args.length == 3) {
StoreRef storeRef = new StoreRef(args[0], args[1]);
nodeRef = new NodeRef(storeRef, args[2]);
}
if (nodeRef != null) {
// check that the user has at least READ access - else redirect to an error or login page
if (!checkAccess(req, res, nodeRef, PermissionService.READ_CONTENT, true)) {
return;
}
// setup the Space on the browse bean
browseBean.setupSpaceAction(nodeRef.getId(), true);
}
// perform the appropriate JSF navigation outcome
NavigationHandler navigationHandler = fc.getApplication().getNavigationHandler();
navigationHandler.handleNavigation(fc, null, "dialog:" + OUTCOME_SPACEDETAILS);
} else if (OUTCOME_BROWSE.equals(outcome)) {
NodeRef nodeRef = null;
if (args.length != 0 && args[0].equals(WebDAVServlet.WEBDAV_PREFIX)) {
nodeRef = resolveWebDAVPath(fc, args);
} else if (args.length >= 3) {
int offset = 0;
offset = args.length - 3;
StoreRef storeRef = new StoreRef(args[0 + offset], args[1 + offset]);
nodeRef = new NodeRef(storeRef, args[2 + offset]);
}
if (nodeRef != null) {
// check that the user has at least READ access - else redirect to an error or login page
if (!checkAccess(req, res, nodeRef, PermissionService.READ_CONTENT, true)) {
return;
}
// this call sets up the current node Id, and updates or initialises the
// breadcrumb component with the selected node as appropriate.
browseBean.updateUILocation(nodeRef);
// force a "late" refresh of the BrowseBean to handle external servlet access URL
browseBean.externalAccessRefresh();
// check for view mode first argument
if (args[0].equals(ARG_TEMPLATE)) {
browseBean.setDashboardView(true);
}
// the above calls into BrowseBean setup the NavigationHandler automatically
} else {
// perform the appropriate JSF navigation outcome
NavigationHandler navigationHandler = fc.getApplication().getNavigationHandler();
navigationHandler.handleNavigation(fc, null, outcome);
}
} else if (OUTCOME_MYALFRESCO.equals(outcome)) {
// setup the Dashboard Manager ready for the page we want to display
if (req.getParameter(ARG_PAGE) != null) {
DashboardManager manager = (DashboardManager) FacesHelper.getManagedBean(fc, DashboardManager.BEAN_NAME);
manager.getPageConfig().setCurrentPage(req.getParameter(ARG_PAGE));
}
// perform the appropriate JSF navigation outcome
NavigationHandler navigationHandler = fc.getApplication().getNavigationHandler();
navigationHandler.handleNavigation(fc, null, outcome);
} else if (OUTCOME_DIALOG.equals(outcome) || OUTCOME_WIZARD.equals(outcome)) {
if (args.length != 0) {
if (args.length > 1) {
String currentNodeId = null;
if (args[1].equals(WebDAVServlet.WEBDAV_PREFIX)) {
// Drop the first argument
String[] args2 = new String[args.length - 1];
for (int i = 1; i < args.length; i++) {
args2[i - 1] = args[i];
if (logger.isDebugEnabled()) {
logger.debug("Added segment " + args2[i - 1]);
}
}
NodeRef nodeRef = resolveWebDAVPath(fc, args2);
currentNodeId = nodeRef.getId();
} else {
currentNodeId = args[1];
}
if (logger.isDebugEnabled()) {
logger.debug("currentNodeId: " + currentNodeId);
}
// if a GUID was passed, use it to init the NavigationBean current context
NavigationBean navigator = (NavigationBean) FacesHelper.getManagedBean(fc, NavigationBean.BEAN_NAME);
navigator.setCurrentNodeId(currentNodeId);
browseBean.setupSpaceAction(currentNodeId, true);
// setup the Document on the browse bean
// avoid java.lang.NullPointerException
// at org.alfresco.web.bean.content.InviteContentUsersWizard.getPermissionsForType(InviteContentUsersWizard.java:49)
// at org.alfresco.web.bean.wizard.BaseInviteUsersWizard.getRoles(BaseInviteUsersWizard.java:562)
browseBean.setupContentAction(currentNodeId, true);
}
NavigationHandler navigationHandler = fc.getApplication().getNavigationHandler();
navigationHandler.handleNavigation(fc, null, outcome + ':' + args[0]);
}
} else if (OUTCOME_LOGOUT.equals(outcome)) {
// special case for logout
// invalidate ticket and clear the Security context for this thread
Application.logOut(fc);
res.sendRedirect(req.getContextPath() + FACES_SERVLET + Application.getLoginPage(getServletContext()));
return;
}
// perform the forward to the page processed by the Faces servlet
String viewId = fc.getViewRoot().getViewId();
ViewSequenceUtils.nextViewSequence(fc);
getServletContext().getRequestDispatcher(FACES_SERVLET + viewId).forward(req, res);
}
use of org.alfresco.service.cmr.security.PermissionService in project acs-community-packaging by Alfresco.
the class UISpaceSelector method getRootChildren.
public Collection<NodeRef> getRootChildren(FacesContext context) {
NodeRef rootRef = new NodeRef(Repository.getStoreRef(), Application.getCompanyRootId(context));
// get a child association reference back from the parent node to satisfy
// the generic API we have in the abstract super class
PermissionService ps = Repository.getServiceRegistry(context).getPermissionService();
if (ps.hasPermission(rootRef, PermissionService.READ) != AccessStatus.ALLOWED) {
// get the root space from the current user home instead
String homeId = Application.getCurrentUser(context).getHomeSpaceId();
rootRef = new NodeRef(Repository.getStoreRef(), homeId);
}
List<NodeRef> roots = new ArrayList<NodeRef>(1);
roots.add(rootRef);
return roots;
}
use of org.alfresco.service.cmr.security.PermissionService in project acs-community-packaging by Alfresco.
the class BaseTemplateContentServlet method processTemplateRequest.
/**
* Processes the template request using the current context i.e. no
* authentication checks are made, it is presumed they have already
* been done.
*
* @param req The HTTP request
* @param res The HTTP response
* @param redirectToLogin Flag to determine whether to redirect to the login
* page if the user does not have the correct permissions
*/
protected void processTemplateRequest(HttpServletRequest req, HttpServletResponse res, boolean redirectToLogin) throws ServletException, IOException {
Log logger = getLogger();
String uri = req.getRequestURI();
if (logger.isDebugEnabled()) {
String queryString = req.getQueryString();
logger.debug("Processing URL: " + uri + ((queryString != null && queryString.length() > 0) ? ("?" + queryString) : ""));
}
uri = uri.substring(req.getContextPath().length());
StringTokenizer t = new StringTokenizer(uri, "/");
int tokenCount = t.countTokens();
// skip servlet name
t.nextToken();
NodeRef nodeRef = null;
NodeRef templateRef = null;
try {
String contentPath = req.getParameter(ARG_CONTEXT_PATH);
if (contentPath != null && contentPath.length() != 0) {
// process the name based path to resolve the NodeRef
PathRefInfo pathInfo = resolveNamePath(getServletContext(), contentPath);
nodeRef = pathInfo.NodeRef;
} else if (tokenCount > 3) {
// get NodeRef to the content from the URL elements
StoreRef storeRef = new StoreRef(t.nextToken(), t.nextToken());
nodeRef = new NodeRef(storeRef, t.nextToken());
}
// get NodeRef to the template if supplied
String templatePath = req.getParameter(ARG_TEMPLATE_PATH);
if (templatePath != null && templatePath.length() != 0) {
// process the name based path to resolve the NodeRef
PathRefInfo pathInfo = resolveNamePath(getServletContext(), templatePath);
templateRef = pathInfo.NodeRef;
} else if (tokenCount >= 7) {
StoreRef storeRef = new StoreRef(t.nextToken(), t.nextToken());
templateRef = new NodeRef(storeRef, t.nextToken());
}
} catch (AccessDeniedException err) {
if (redirectToLogin) {
if (logger.isDebugEnabled())
logger.debug("Redirecting to login page...");
redirectToLoginPage(req, res, getServletContext());
} else {
if (logger.isDebugEnabled())
logger.debug("Returning 403 Forbidden error...");
res.sendError(HttpServletResponse.SC_FORBIDDEN);
}
return;
}
// TODO: should this default to something else?
if (nodeRef == null && templateRef != null) {
nodeRef = templateRef;
}
if (nodeRef == null) {
throw new TemplateException("Not enough elements supplied in URL or no 'path' argument specified.");
}
// get the services we need to retrieve the content
ServiceRegistry serviceRegistry = getServiceRegistry(getServletContext());
NodeService nodeService = serviceRegistry.getNodeService();
TemplateService templateService = serviceRegistry.getTemplateService();
PermissionService permissionService = serviceRegistry.getPermissionService();
// check that the user has at least READ access on any nodes - else redirect to the login page
if (permissionService.hasPermission(nodeRef, PermissionService.READ) == AccessStatus.DENIED || (templateRef != null && permissionService.hasPermission(templateRef, PermissionService.READ) == AccessStatus.DENIED)) {
if (redirectToLogin) {
if (logger.isDebugEnabled())
logger.debug("Redirecting to login page...");
redirectToLoginPage(req, res, getServletContext());
} else {
if (logger.isDebugEnabled())
logger.debug("Returning 403 Forbidden error...");
res.sendError(HttpServletResponse.SC_FORBIDDEN);
}
return;
}
String mimetype = MIMETYPE_HTML;
if (req.getParameter(ARG_MIMETYPE) != null) {
mimetype = req.getParameter(ARG_MIMETYPE);
}
res.setContentType(mimetype);
try {
UserTransaction txn = null;
try {
txn = serviceRegistry.getTransactionService().getUserTransaction(true);
txn.begin();
// if template not supplied, then use the default against the node
if (templateRef == null) {
if (nodeService.hasAspect(nodeRef, ContentModel.ASPECT_TEMPLATABLE)) {
templateRef = (NodeRef) nodeService.getProperty(nodeRef, ContentModel.PROP_TEMPLATE);
}
if (templateRef == null) {
throw new TemplateException("Template reference not set against node or not supplied in URL.");
}
}
// create the model - put the supplied noderef in as space/document as appropriate
Map<String, Object> model = getModel(serviceRegistry, req, templateRef, nodeRef);
// to be streamed directly to the browser response stream.
try {
templateService.processTemplate(templateRef.toString(), model, res.getWriter());
// commit the transaction
txn.commit();
} catch (SocketException e) {
if (e.getMessage().contains("ClientAbortException")) {
// the client cut the connection - our mission was accomplished apart from a little error message
logger.error("Client aborted stream read:\n node: " + nodeRef + "\n template: " + templateRef);
try {
if (txn != null) {
txn.rollback();
}
} catch (Exception tex) {
}
} else {
throw e;
}
} finally {
res.getWriter().close();
}
} catch (Throwable txnErr) {
try {
if (txn != null) {
txn.rollback();
}
} catch (Exception tex) {
}
throw txnErr;
}
} catch (Throwable err) {
throw new AlfrescoRuntimeException("Error during template servlet processing: " + err.getMessage(), err);
}
}
use of org.alfresco.service.cmr.security.PermissionService in project acs-community-packaging by Alfresco.
the class UploadContentServlet method doPut.
/**
* @see javax.servlet.http.HttpServlet#doPut(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
*/
protected void doPut(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
if (logger.isDebugEnabled() == true) {
String queryString = req.getQueryString();
logger.debug("Authenticating request to URL: " + req.getRequestURI() + ((queryString != null && queryString.length() > 0) ? ("?" + queryString) : ""));
}
AuthenticationStatus status = servletAuthenticate(req, res, false);
if (status == AuthenticationStatus.Failure || status == AuthenticationStatus.Guest) {
res.sendError(HttpServletResponse.SC_UNAUTHORIZED);
return;
}
// Tokenise the URI
String uri = req.getRequestURI();
uri = uri.substring(req.getContextPath().length());
StringTokenizer t = new StringTokenizer(uri, "/");
int tokenCount = t.countTokens();
// skip servlet name
t.nextToken();
// get or calculate the noderef and filename to download as
NodeRef nodeRef = null;
String filename = null;
QName propertyQName = null;
if (tokenCount == 2) {
// filename is the only token
filename = t.nextToken();
} else if (tokenCount == 4 || tokenCount == 5) {
// assume 'workspace' or other NodeRef based protocol for remaining URL
// elements
StoreRef storeRef = new StoreRef(t.nextToken(), t.nextToken());
String id = t.nextToken();
// build noderef from the appropriate URL elements
nodeRef = new NodeRef(storeRef, id);
if (tokenCount == 5) {
// filename is last remaining token
filename = t.nextToken();
}
// get qualified of the property to get content from - default to
// ContentModel.PROP_CONTENT
propertyQName = ContentModel.PROP_CONTENT;
String property = req.getParameter(ARG_PROPERTY);
if (property != null && property.length() != 0) {
propertyQName = QName.createQName(property);
}
} else {
logger.debug("Upload URL did not contain all required args: " + uri);
res.sendError(HttpServletResponse.SC_EXPECTATION_FAILED);
return;
}
// get the services we need to retrieve the content
ServiceRegistry serviceRegistry = getServiceRegistry(getServletContext());
ContentService contentService = serviceRegistry.getContentService();
PermissionService permissionService = serviceRegistry.getPermissionService();
MimetypeService mimetypeService = serviceRegistry.getMimetypeService();
NodeService nodeService = serviceRegistry.getNodeService();
InputStream is = req.getInputStream();
BufferedInputStream inputStream = new BufferedInputStream(is);
// Sort out the mimetype
String mimetype = req.getParameter(ARG_MIMETYPE);
if (mimetype == null || mimetype.length() == 0) {
mimetype = MIMETYPE_OCTET_STREAM;
if (filename != null) {
MimetypeService mimetypeMap = serviceRegistry.getMimetypeService();
int extIndex = filename.lastIndexOf('.');
if (extIndex != -1) {
String ext = filename.substring(extIndex + 1);
mimetype = mimetypeService.getMimetype(ext);
}
}
}
// Get the encoding
String encoding = req.getParameter(ARG_ENCODING);
if (encoding == null || encoding.length() == 0) {
// Get the encoding
ContentCharsetFinder charsetFinder = mimetypeService.getContentCharsetFinder();
Charset charset = charsetFinder.getCharset(inputStream, mimetype);
encoding = charset.name();
}
// Get the locale
Locale locale = I18NUtil.parseLocale(req.getParameter(ARG_LOCALE));
if (locale == null) {
locale = I18NUtil.getContentLocale();
if (nodeRef != null) {
ContentData contentData = (ContentData) nodeService.getProperty(nodeRef, propertyQName);
if (contentData != null) {
locale = contentData.getLocale();
}
}
}
if (logger.isDebugEnabled()) {
if (nodeRef != null) {
logger.debug("Found NodeRef: " + nodeRef.toString());
}
logger.debug("For property: " + propertyQName);
logger.debug("File name: " + filename);
logger.debug("Mimetype: " + mimetype);
logger.debug("Encoding: " + encoding);
logger.debug("Locale: " + locale);
}
// Check that the user has the permissions to write the content
if (permissionService.hasPermission(nodeRef, PermissionService.WRITE_CONTENT) == AccessStatus.DENIED) {
if (logger.isDebugEnabled() == true) {
logger.debug("User does not have permissions to wrtie content for NodeRef: " + nodeRef.toString());
}
if (logger.isDebugEnabled()) {
logger.debug("Returning 403 Forbidden error...");
}
res.sendError(HttpServletResponse.SC_FORBIDDEN);
return;
}
// Try and get the content writer
ContentWriter writer = contentService.getWriter(nodeRef, propertyQName, true);
if (writer == null) {
if (logger.isDebugEnabled() == true) {
logger.debug("Content writer cannot be obtained for NodeRef: " + nodeRef.toString());
}
res.sendError(HttpServletResponse.SC_EXPECTATION_FAILED);
return;
}
// Set the mimetype, encoding and locale
writer.setMimetype(mimetype);
writer.setEncoding(encoding);
if (locale != null) {
writer.setLocale(locale);
}
// Stream the content into the repository
writer.putContent(inputStream);
if (logger.isDebugEnabled() == true) {
logger.debug("Content details: " + writer.getContentData().toString());
}
// Set return status
res.getWriter().write(writer.getContentData().toString());
res.flushBuffer();
if (logger.isDebugEnabled() == true) {
logger.debug("UploadContentServlet done");
}
}
Aggregations