Search in sources :

Example 21 with XWikiException

use of com.xpn.xwiki.XWikiException in project xwiki-platform by xwiki.

the class DeleteAction method deleteToRecycleBin.

protected boolean deleteToRecycleBin(EntityReference entityReference, XWikiContext context) throws XWikiException {
    Job deleteJob = startDeleteJob(entityReference, context);
    // If the user have asked for an asynchronous delete action...
    if (isAsync(context.getRequest())) {
        List<String> jobId = deleteJob.getRequest().getId();
        // We don't redirect to the delete action because by the time the redirect request reaches the server the
        // specified entity may be already deleted and the current user may not have the delete right anymore (e.g.
        // the current user is no longer the creator).
        sendRedirect(context.getResponse(), Utils.getRedirect("view", "xpage=delete&jobId=" + serializeJobId(jobId), context));
        // A redirect has been performed.
        return true;
    }
    // Otherwise...
    try {
        deleteJob.join();
    } catch (InterruptedException e) {
        throw new XWikiException(String.format("Failed to delete [%s]", entityReference), e);
    }
    // No redirect has been performed.
    return false;
}
Also used : Job(org.xwiki.job.Job) XWikiException(com.xpn.xwiki.XWikiException)

Example 22 with XWikiException

use of com.xpn.xwiki.XWikiException in project xwiki-platform by xwiki.

the class DeleteAttachmentAction method action.

@Override
public boolean action(XWikiContext context) throws XWikiException {
    // CSRF prevention
    if (!csrfTokenCheck(context)) {
        return false;
    }
    XWikiRequest request = context.getRequest();
    XWikiResponse response = context.getResponse();
    XWikiDocument doc = context.getDoc();
    XWikiAttachment attachment = null;
    XWiki xwiki = context.getWiki();
    String filename;
    // Delete from the trash
    if (request.getParameter("trashId") != null) {
        long trashId = NumberUtils.toLong(request.getParameter("trashId"));
        DeletedAttachment da = xwiki.getAttachmentRecycleBinStore().getDeletedAttachment(trashId, context, true);
        // don't try to delete it and instead redirect to the attachment list.
        if (da != null) {
            com.xpn.xwiki.api.DeletedAttachment daapi = new com.xpn.xwiki.api.DeletedAttachment(da, context);
            if (!daapi.canDelete()) {
                throw new XWikiException(XWikiException.MODULE_XWIKI_ACCESS, XWikiException.ERROR_XWIKI_ACCESS_DENIED, "You are not allowed to delete an attachment from the trash " + "immediately after it has been deleted from the wiki");
            }
            if (!da.getDocName().equals(doc.getFullName())) {
                throw new XWikiException(XWikiException.MODULE_XWIKI_APP, XWikiException.ERROR_XWIKI_APP_URL_EXCEPTION, "The specified trash entry does not match the current document");
            }
            // TODO: Add a confirmation check
            xwiki.getAttachmentRecycleBinStore().deleteFromRecycleBin(trashId, context, true);
        }
        sendRedirect(response, Utils.getRedirect("attach", context));
        return false;
    }
    if (context.getMode() == XWikiContext.MODE_PORTLET) {
        filename = request.getParameter("filename");
    } else {
        // Note: We use getRequestURI() because the spec says the server doesn't decode it, as
        // we want to use our own decoding.
        String requestUri = request.getRequestURI();
        filename = getFileName();
    }
    XWikiDocument newdoc = doc.clone();
    // An attachment can be indicated either using an id, or using the filename.
    if (request.getParameter("id") != null) {
        int id = NumberUtils.toInt(request.getParameter("id"));
        if (newdoc.getAttachmentList().size() > id) {
            attachment = newdoc.getAttachmentList().get(id);
        }
    } else {
        attachment = newdoc.getAttachment(filename);
    }
    // No such attachment
    if (attachment == null) {
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        ScriptContext scriptContext = getCurrentScriptContext();
        if (scriptContext != null) {
            scriptContext.setAttribute("message", localizePlainOrKey("core.action.deleteAttachment.failed", filename), ScriptContext.ENGINE_SCOPE);
            scriptContext.setAttribute("details", localizePlainOrKey("platform.core.action.deleteAttachment.noAttachment"), ScriptContext.ENGINE_SCOPE);
        }
        return true;
    }
    newdoc.setAuthorReference(context.getUserReference());
    // Set "deleted attachment" as the version comment.
    String comment;
    if (attachment.isImage(context)) {
        comment = localizePlainOrKey("core.comment.deleteImageComment", filename);
    } else {
        comment = localizePlainOrKey("core.comment.deleteAttachmentComment", filename);
    }
    try {
        newdoc.removeAttachment(attachment);
        xwiki.saveDocument(newdoc, comment, context);
    } catch (Exception ex) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        ScriptContext scriptContext = getCurrentScriptContext();
        if (scriptContext != null) {
            scriptContext.setAttribute("message", localizePlainOrKey("core.action.deleteAttachment.failed", filename), ScriptContext.ENGINE_SCOPE);
            scriptContext.setAttribute("details", ExceptionUtils.getRootCauseMessage(ex), ScriptContext.ENGINE_SCOPE);
        }
        return true;
    }
    // forward to attach page
    if (!((Boolean) context.get("ajax")).booleanValue()) {
        String redirect = Utils.getRedirect("attach", context);
        sendRedirect(response, redirect);
    }
    return false;
}
Also used : XWiki(com.xpn.xwiki.XWiki) ScriptContext(javax.script.ScriptContext) XWikiAttachment(com.xpn.xwiki.doc.XWikiAttachment) DeletedAttachment(com.xpn.xwiki.doc.DeletedAttachment) XWikiException(com.xpn.xwiki.XWikiException) XWikiDocument(com.xpn.xwiki.doc.XWikiDocument) XWikiException(com.xpn.xwiki.XWikiException)

Example 23 with XWikiException

use of com.xpn.xwiki.XWikiException in project xwiki-platform by xwiki.

the class XWikiAuthServiceImpl method checkAuth.

/**
 * Method to authenticate and set the cookie from a username and password passed as parameters
 *
 * @return null if the user is not authenticated properly
 */
@Override
public XWikiUser checkAuth(String username, String password, String rememberme, XWikiContext context) throws XWikiException {
    HttpServletRequest request = null;
    HttpServletResponse response = context.getResponse();
    if (context.getRequest() != null) {
        request = context.getRequest().getHttpServletRequest();
    }
    if (request == null) {
        return null;
    }
    XWikiAuthenticator auth = getAuthenticator(context);
    SecurityRequestWrapper wrappedRequest = new SecurityRequestWrapper(request, null, null, auth.getAuthMethod());
    try {
        if (!auth.processLogin(username, password, rememberme, wrappedRequest, response, context)) {
            return null;
        }
        Principal principal = wrappedRequest.getUserPrincipal();
        if (LOGGER.isInfoEnabled()) {
            if (principal != null) {
                LOGGER.info("User " + principal.getName() + " is authentified");
            }
        }
        if (principal == null) {
            return null;
        }
        return new XWikiUser(getContextUserName(principal, context));
    } catch (Exception e) {
        LOGGER.error("Failed to authenticate", e);
        return null;
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) XWikiUser(com.xpn.xwiki.user.api.XWikiUser) SecurityRequestWrapper(org.securityfilter.filter.SecurityRequestWrapper) HttpServletResponse(javax.servlet.http.HttpServletResponse) Principal(java.security.Principal) SimplePrincipal(org.securityfilter.realm.SimplePrincipal) XWikiException(com.xpn.xwiki.XWikiException) IOException(java.io.IOException)

Example 24 with XWikiException

use of com.xpn.xwiki.XWikiException in project xwiki-platform by xwiki.

the class XWikiRightServiceImpl method addMemberGroups.

private void addMemberGroups(String wiki, String prefixedFullName, DocumentReference userOrGroupDocumentReference, Collection<String> grouplist, XWikiContext context) throws XWikiException {
    XWikiGroupService groupService = context.getWiki().getGroupService(context);
    Map<String, Collection<String>> grouplistcache = (Map<String, Collection<String>>) context.get("grouplist");
    if (grouplistcache == null) {
        grouplistcache = new HashMap<String, Collection<String>>();
        context.put("grouplist", grouplistcache);
    }
    // the key is for the entity <code>prefixedFullName</code> in current wiki
    String key = wiki + ":" + prefixedFullName;
    Collection<String> tmpGroupList = grouplistcache.get(key);
    if (tmpGroupList == null) {
        String currentWiki = context.getWikiId();
        try {
            context.setWikiId(wiki);
            Collection<DocumentReference> groupReferences = groupService.getAllGroupsReferencesForMember(userOrGroupDocumentReference, 0, 0, context);
            tmpGroupList = new ArrayList<String>(groupReferences.size());
            for (DocumentReference groupReference : groupReferences) {
                tmpGroupList.add(this.entityReferenceSerializer.serialize(groupReference));
            }
        } catch (Exception e) {
            LOGGER.error("Failed to get groups for user or group [{}] in wiki [{}]", prefixedFullName, wiki, e);
            tmpGroupList = Collections.emptyList();
        } finally {
            context.setWikiId(currentWiki);
        }
        grouplistcache.put(key, tmpGroupList);
    }
    grouplist.addAll(tmpGroupList);
}
Also used : Collection(java.util.Collection) HashMap(java.util.HashMap) Map(java.util.Map) DocumentReference(org.xwiki.model.reference.DocumentReference) XWikiException(com.xpn.xwiki.XWikiException) XWikiRightNotFoundException(com.xpn.xwiki.user.api.XWikiRightNotFoundException) XWikiGroupService(com.xpn.xwiki.user.api.XWikiGroupService)

Example 25 with XWikiException

use of com.xpn.xwiki.XWikiException in project xwiki-platform by xwiki.

the class XWikiRightServiceImpl method checkRight.

public boolean checkRight(String userOrGroupName, XWikiDocument doc, String accessLevel, boolean user, boolean allow, boolean global, XWikiContext context) throws XWikiRightNotFoundException, XWikiException {
    if (!global && ("admin".equals(accessLevel))) {
        // Admin rights do not exist at document level.
        throw new XWikiRightNotFoundException();
    }
    EntityReference rightClassReference = global ? GLOBALRIGHTCLASS_REFERENCE : RIGHTCLASS_REFERENCE;
    String fieldName = user ? "users" : "groups";
    boolean found = false;
    // Here entity is either a user or a group
    DocumentReference userOrGroupDocumentReference = this.currentMixedDocumentReferenceResolver.resolve(userOrGroupName);
    String prefixedFullName = this.entityReferenceSerializer.serialize(userOrGroupDocumentReference);
    String shortname = userOrGroupName;
    int i0 = userOrGroupName.indexOf(":");
    if (i0 != -1) {
        shortname = userOrGroupName.substring(i0 + 1);
    }
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Checking right: [{}], [{}], [{}], [{}], [{}], [{}]", userOrGroupName, doc.getFullName(), accessLevel, user, allow, global);
    }
    List<BaseObject> rightObjects = doc.getXObjects(rightClassReference);
    if (rightObjects != null) {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Checking objects [{}]", rightObjects.size());
        }
        for (int i = 0; i < rightObjects.size(); i++) {
            LOGGER.debug("Checking object [{}]", i);
            BaseObject bobj = rightObjects.get(i);
            if (bobj == null) {
                LOGGER.debug("Bypass object [{}]", i);
                continue;
            }
            String users = bobj.getStringValue(fieldName);
            String levels = bobj.getStringValue("levels");
            boolean allowdeny = (bobj.getIntValue("allow") == 1);
            if (allowdeny == allow) {
                LOGGER.debug("Checking match: [{}] in [{}]", accessLevel, levels);
                String[] levelsarray = StringUtils.split(levels, " ,|");
                if (ArrayUtils.contains(levelsarray, accessLevel)) {
                    LOGGER.debug("Found a right for [{}]", allow);
                    found = true;
                    LOGGER.debug("Checking match: [{}] in [{}]", userOrGroupName, users);
                    String[] userarray = GroupsClass.getListFromString(users).toArray(new String[0]);
                    for (int ii = 0; ii < userarray.length; ii++) {
                        String value = userarray[ii];
                        if (value.indexOf(".") == -1) {
                            userarray[ii] = "XWiki." + value;
                        }
                    }
                    if (LOGGER.isDebugEnabled()) {
                        LOGGER.debug("Checking match: [{}] in [{}]", userOrGroupName, StringUtils.join(userarray, ","));
                    }
                    // name is requested
                    if (doc.getWikiName().equals(userOrGroupDocumentReference.getWikiReference().getName())) {
                        if (ArrayUtils.contains(userarray, shortname)) {
                            LOGGER.debug("Found matching right in [{}] for [{}]", users, shortname);
                            return true;
                        }
                        // We should also allow to skip "XWiki." from the usernames and group
                        // lists
                        String veryshortname = shortname.substring(shortname.indexOf(".") + 1);
                        if (ArrayUtils.contains(userarray, veryshortname)) {
                            LOGGER.debug("Found matching right in [{}] for [{}]", users, shortname);
                            return true;
                        }
                    }
                    if ((context.getWikiId() != null) && (ArrayUtils.contains(userarray, userOrGroupName))) {
                        LOGGER.debug("Found matching right in [{}] for [{}]", users, userOrGroupName);
                        return true;
                    }
                    LOGGER.debug("Failed match: [{}] in [{}]", userOrGroupName, users);
                }
            } else {
                LOGGER.debug("Bypass object [{}] because wrong allow/deny", i);
            }
        }
    }
    LOGGER.debug("Searching for matching rights at group level");
    // Didn't found right at this level.. Let's go to group level
    Map<String, Collection<String>> grouplistcache = (Map<String, Collection<String>>) context.get("grouplist");
    if (grouplistcache == null) {
        grouplistcache = new HashMap<String, Collection<String>>();
        context.put("grouplist", grouplistcache);
    }
    Collection<String> grouplist = new HashSet<String>();
    // Get member groups from document's wiki
    addMemberGroups(doc.getWikiName(), prefixedFullName, userOrGroupDocumentReference, grouplist, context);
    // Get member groups from member's wiki
    if (!context.getWikiId().equalsIgnoreCase(userOrGroupDocumentReference.getWikiReference().getName())) {
        addMemberGroups(userOrGroupDocumentReference.getWikiReference().getName(), prefixedFullName, userOrGroupDocumentReference, grouplist, context);
    }
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Searching for matching rights for [{}] groups: [{}]", grouplist.size(), grouplist);
    }
    for (String group : grouplist) {
        try {
            // We need to construct the full group name to make sure the groups are
            // handled separately
            boolean result = checkRight(group, doc, accessLevel, false, allow, global, context);
            if (result) {
                return true;
            }
        } catch (XWikiRightNotFoundException e) {
        } catch (Exception e) {
            LOGGER.error("Failed to check right [{}] for group [{}] on document [ΒΆ}]", accessLevel, group, doc.getPrefixedFullName(), e);
        }
    }
    LOGGER.debug("Finished searching for rights for [{}]: [{}]", userOrGroupName, found);
    if (found) {
        return false;
    } else {
        throw new XWikiRightNotFoundException();
    }
}
Also used : XWikiException(com.xpn.xwiki.XWikiException) XWikiRightNotFoundException(com.xpn.xwiki.user.api.XWikiRightNotFoundException) BaseObject(com.xpn.xwiki.objects.BaseObject) EntityReference(org.xwiki.model.reference.EntityReference) Collection(java.util.Collection) HashMap(java.util.HashMap) Map(java.util.Map) XWikiRightNotFoundException(com.xpn.xwiki.user.api.XWikiRightNotFoundException) DocumentReference(org.xwiki.model.reference.DocumentReference) HashSet(java.util.HashSet)

Aggregations

XWikiException (com.xpn.xwiki.XWikiException)442 XWikiContext (com.xpn.xwiki.XWikiContext)156 XWikiDocument (com.xpn.xwiki.doc.XWikiDocument)147 DocumentReference (org.xwiki.model.reference.DocumentReference)98 BaseObject (com.xpn.xwiki.objects.BaseObject)88 IOException (java.io.IOException)57 QueryException (org.xwiki.query.QueryException)57 ArrayList (java.util.ArrayList)56 ComponentLookupException (org.xwiki.component.manager.ComponentLookupException)51 XWiki (com.xpn.xwiki.XWiki)48 XWikiRestException (org.xwiki.rest.XWikiRestException)44 Session (org.hibernate.Session)42 Document (com.xpn.xwiki.api.Document)38 InitializationException (org.xwiki.component.phase.InitializationException)36 WebApplicationException (javax.ws.rs.WebApplicationException)32 SQLException (java.sql.SQLException)31 ObjectNotFoundException (org.hibernate.ObjectNotFoundException)30 MigrationRequiredException (com.xpn.xwiki.store.migration.MigrationRequiredException)29 UnexpectedException (org.xwiki.store.UnexpectedException)29 XWikiAttachment (com.xpn.xwiki.doc.XWikiAttachment)25