Search in sources :

Example 21 with AccessDeniedException

use of org.alfresco.repo.security.permissions.AccessDeniedException 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);
    }
}
Also used : UserTransaction(javax.transaction.UserTransaction) StoreRef(org.alfresco.service.cmr.repository.StoreRef) SocketException(java.net.SocketException) AccessDeniedException(org.alfresco.repo.security.permissions.AccessDeniedException) Log(org.apache.commons.logging.Log) TemplateException(org.alfresco.service.cmr.repository.TemplateException) NodeService(org.alfresco.service.cmr.repository.NodeService) ServletException(javax.servlet.ServletException) SocketException(java.net.SocketException) IOException(java.io.IOException) AlfrescoRuntimeException(org.alfresco.error.AlfrescoRuntimeException) AccessDeniedException(org.alfresco.repo.security.permissions.AccessDeniedException) TemplateException(org.alfresco.service.cmr.repository.TemplateException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) PermissionService(org.alfresco.service.cmr.security.PermissionService) NodeRef(org.alfresco.service.cmr.repository.NodeRef) StringTokenizer(java.util.StringTokenizer) AlfrescoRuntimeException(org.alfresco.error.AlfrescoRuntimeException) ServiceRegistry(org.alfresco.service.ServiceRegistry) TemplateService(org.alfresco.service.cmr.repository.TemplateService)

Example 22 with AccessDeniedException

use of org.alfresco.repo.security.permissions.AccessDeniedException in project acs-community-packaging by Alfresco.

the class DownloadRawContentServlet method processRequest.

/**
 * Processes the 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
 */
private void processRequest(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    String uri = req.getRequestURI();
    String contentUrl = req.getParameter(ARG_CONTENT_URL);
    if (contentUrl == null || contentUrl.length() == 0) {
        throw new IllegalArgumentException("Download URL did not contain parameter '" + ARG_CONTENT_URL + "':" + uri);
    }
    String infoOnlyStr = req.getParameter(ARG_INFO_ONLY);
    boolean infoOnly = (infoOnlyStr == null) ? false : Boolean.parseBoolean(infoOnlyStr);
    ServiceRegistry serviceRegistry = getServiceRegistry(getServletContext());
    ContentService contentService = serviceRegistry.getContentService();
    // Attempt to get the reader
    ContentReader reader = null;
    try {
        reader = contentService.getRawReader(contentUrl);
        // If the content doesn't exist, generate an error
        if (!reader.exists()) {
            if (logger.isDebugEnabled()) {
                logger.debug("Returning 204 Not Found error...");
            }
            res.sendError(HttpServletResponse.SC_NO_CONTENT);
            return;
        }
    } catch (AccessDeniedException e) {
        if (logger.isDebugEnabled()) {
            logger.debug("Returning 403 Forbidden error after exception: ", e);
        }
        res.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }
    long readerSize = reader.getSize();
    Date readerLastModified = new Date(reader.getLastModified());
    String readerMimetype = reader.getMimetype();
    String readerEncoding = reader.getEncoding();
    Locale readerLocale = reader.getLocale();
    // Set the content info
    res.setHeader("alfresco.dr.size", DefaultTypeConverter.INSTANCE.convert(String.class, readerSize));
    res.setHeader("alfresco.dr.lastModified", DefaultTypeConverter.INSTANCE.convert(String.class, readerLastModified));
    res.setHeader("alfresco.dr.mimetype", readerMimetype);
    res.setHeader("alfresco.dr.encoding", readerEncoding);
    res.setHeader("alfresco.dr.locale", DefaultTypeConverter.INSTANCE.convert(String.class, readerLocale));
    // Pass the stream to the response, unless only the content info was requested
    if (infoOnly) {
        // Fill response details
        res.setContentType(DEFAULT_MIMETYPE);
        res.setCharacterEncoding(DEFAULT_ENCODING);
    } else {
        // Fill response details
        res.setContentType(readerMimetype);
        res.setCharacterEncoding(readerEncoding);
        try {
            OutputStream clientOs = res.getOutputStream();
            // Streams closed for us
            reader.getContent(clientOs);
        } catch (SocketException e1) {
            // Not a problem
            if (logger.isDebugEnabled()) {
                logger.debug("Client aborted stream read:\n" + "   Content URL: " + contentUrl);
            }
        } catch (ContentIOException e2) {
            // Not a problem
            if (logger.isDebugEnabled()) {
                logger.debug("Client aborted stream read:\n" + "   Content URL: " + contentUrl);
            }
        }
    }
}
Also used : Locale(java.util.Locale) SocketException(java.net.SocketException) AccessDeniedException(org.alfresco.repo.security.permissions.AccessDeniedException) ContentReader(org.alfresco.service.cmr.repository.ContentReader) OutputStream(java.io.OutputStream) ContentService(org.alfresco.service.cmr.repository.ContentService) Date(java.util.Date) ContentIOException(org.alfresco.service.cmr.repository.ContentIOException) ServiceRegistry(org.alfresco.service.ServiceRegistry)

Example 23 with AccessDeniedException

use of org.alfresco.repo.security.permissions.AccessDeniedException in project acs-community-packaging by Alfresco.

the class BaseInviteUsersWizard method getEmailTemplates.

/**
 * @return Returns the list of email templates for user notification
 */
public List<SelectItem> getEmailTemplates() {
    List<SelectItem> wrappers = null;
    try {
        FacesContext fc = FacesContext.getCurrentInstance();
        NodeRef rootNodeRef = this.getNodeService().getRootNode(Repository.getStoreRef());
        NamespaceService resolver = Repository.getServiceRegistry(fc).getNamespaceService();
        List<NodeRef> results = this.getSearchService().selectNodes(rootNodeRef, getEmailTemplateXPath(), null, resolver, false);
        wrappers = new ArrayList<SelectItem>(results.size() + 1);
        if (results.size() != 0) {
            DictionaryService dd = Repository.getServiceRegistry(fc).getDictionaryService();
            for (NodeRef ref : results) {
                if (this.getNodeService().exists(ref) == true) {
                    Node childNode = new Node(ref);
                    if (dd.isSubClass(childNode.getType(), ContentModel.TYPE_CONTENT)) {
                        wrappers.add(new SelectItem(childNode.getId(), childNode.getName()));
                    }
                }
            }
            // make sure the list is sorted by the label
            QuickSort sorter = new QuickSort(wrappers, "label", true, IDataContainer.SORT_CASEINSENSITIVE);
            sorter.sort();
        }
    } catch (AccessDeniedException accessErr) {
    // ignore the result if we cannot access the root
    }
    // add an entry (at the start) to instruct the user to select an item
    if (wrappers == null) {
        wrappers = new ArrayList<SelectItem>(1);
    }
    wrappers.add(0, new SelectItem("none", Application.getMessage(FacesContext.getCurrentInstance(), "select_a_template")));
    return wrappers;
}
Also used : FacesContext(javax.faces.context.FacesContext) NodeRef(org.alfresco.service.cmr.repository.NodeRef) DictionaryService(org.alfresco.service.cmr.dictionary.DictionaryService) QuickSort(org.alfresco.web.data.QuickSort) AccessDeniedException(org.alfresco.repo.security.permissions.AccessDeniedException) NamespaceService(org.alfresco.service.namespace.NamespaceService) SortableSelectItem(org.alfresco.web.ui.common.SortableSelectItem) SelectItem(javax.faces.model.SelectItem) Node(org.alfresco.web.bean.repository.Node)

Example 24 with AccessDeniedException

use of org.alfresco.repo.security.permissions.AccessDeniedException in project acs-community-packaging by Alfresco.

the class AdvancedSearchDialog method findNodeRefFromPath.

/**
 * Return NodeRef to the last Node referenced on the end of the specified xpath value
 *
 * @param xpath   XPath - note that any /* or //* will be removed to find trailing node
 *
 * @return NodeRef if found null otherwise
 */
private NodeRef findNodeRefFromPath(String xpath) {
    if (xpath.endsWith("//*")) {
        xpath = xpath.substring(0, xpath.lastIndexOf("//*"));
    } else if (xpath.endsWith("/*")) {
        xpath = xpath.substring(0, xpath.lastIndexOf("/*"));
    }
    NodeRef rootRef = new NodeRef(Repository.getStoreRef(), Application.getCompanyRootId(FacesContext.getCurrentInstance()));
    List<NodeRef> results = null;
    try {
        results = getSearchService().selectNodes(rootRef, xpath, null, getNamespaceService(), false);
    } catch (AccessDeniedException err) {
    // ignore and return null
    }
    return (results != null && results.size() == 1) ? results.get(0) : null;
}
Also used : NodeRef(org.alfresco.service.cmr.repository.NodeRef) AccessDeniedException(org.alfresco.repo.security.permissions.AccessDeniedException)

Example 25 with AccessDeniedException

use of org.alfresco.repo.security.permissions.AccessDeniedException in project acs-community-packaging by Alfresco.

the class AdvancedSearchDialog method getUserSearchesRef.

/**
 * @return the cached reference to the shared Saved Searches folder
 */
protected NodeRef getUserSearchesRef() {
    if (properties.getUserSearchesRef() == null) {
        NodeRef globalRef = getGlobalSearchesRef();
        if (globalRef != null) {
            FacesContext fc = FacesContext.getCurrentInstance();
            User user = Application.getCurrentUser(fc);
            String userName = ISO9075.encode(user.getUserName());
            String xpath = NamespaceService.APP_MODEL_PREFIX + ":" + QName.createValidLocalName(userName);
            List<NodeRef> results = null;
            try {
                results = getSearchService().selectNodes(globalRef, xpath, null, getNamespaceService(), false);
            } catch (AccessDeniedException err) {
            // ignore and return null
            }
            if (results != null) {
                if (results.size() == 1) {
                    properties.setUserSearchesRef(results.get(0));
                } else if (results.size() == 0 && new Node(globalRef).hasPermission(PermissionService.ADD_CHILDREN)) {
                    // attempt to create folder for this user for first time
                    // create the preferences Node for this user
                    ChildAssociationRef childRef = getNodeService().createNode(globalRef, ContentModel.ASSOC_CONTAINS, QName.createQName(NamespaceService.APP_MODEL_1_0_URI, QName.createValidLocalName(user.getUserName())), ContentModel.TYPE_FOLDER, null);
                    properties.setUserSearchesRef(childRef.getChildRef());
                }
            }
        }
    }
    return properties.getUserSearchesRef();
}
Also used : NodeRef(org.alfresco.service.cmr.repository.NodeRef) FacesContext(javax.faces.context.FacesContext) AccessDeniedException(org.alfresco.repo.security.permissions.AccessDeniedException) User(org.alfresco.web.bean.repository.User) Node(org.alfresco.web.bean.repository.Node) MapNode(org.alfresco.web.bean.repository.MapNode) ChildAssociationRef(org.alfresco.service.cmr.repository.ChildAssociationRef)

Aggregations

AccessDeniedException (org.alfresco.repo.security.permissions.AccessDeniedException)46 NodeRef (org.alfresco.service.cmr.repository.NodeRef)30 HashMap (java.util.HashMap)17 IOException (java.io.IOException)8 AlfrescoRuntimeException (org.alfresco.error.AlfrescoRuntimeException)8 InvalidNodeRefException (org.alfresco.service.cmr.repository.InvalidNodeRefException)8 ArrayList (java.util.ArrayList)7 WebScriptException (org.springframework.extensions.webscripts.WebScriptException)7 FacesContext (javax.faces.context.FacesContext)6 FileNotFoundException (org.alfresco.service.cmr.model.FileNotFoundException)6 JSONObject (org.json.simple.JSONObject)6 Serializable (java.io.Serializable)5 EntityNotFoundException (org.alfresco.rest.framework.core.exceptions.EntityNotFoundException)5 FileExistsException (org.alfresco.service.cmr.model.FileExistsException)5 SocketException (java.net.SocketException)4 Map (java.util.Map)4 FileInfo (org.alfresco.service.cmr.model.FileInfo)4 ContentIOException (org.alfresco.service.cmr.repository.ContentIOException)4 QName (org.alfresco.service.namespace.QName)4 ResourceBundle (java.util.ResourceBundle)3