Search in sources :

Example 1 with AuthorizationManager

use of org.apache.wiki.auth.AuthorizationManager in project jspwiki by apache.

the class MetaWeblogHandler method checkPermissions.

/**
 *  Does a quick check against the current user
 *  and does he have permissions to do the stuff
 *  that he really wants to.
 *  <p>
 *  If there is no authentication enabled, returns normally.
 *
 *  @throw XmlRpcException with the correct error message, if auth fails.
 */
private void checkPermissions(WikiPage page, String username, String password, String permission) throws XmlRpcException {
    try {
        AuthenticationManager amm = m_context.getEngine().getAuthenticationManager();
        AuthorizationManager mgr = m_context.getEngine().getAuthorizationManager();
        if (amm.login(m_context.getWikiSession(), m_context.getHttpRequest(), username, password)) {
            if (!mgr.checkPermission(m_context.getWikiSession(), PermissionFactory.getPagePermission(page, permission))) {
                throw new XmlRpcException(1, "No permission");
            }
        } else {
            throw new XmlRpcException(1, "Unknown login");
        }
    } catch (WikiSecurityException e) {
        throw new XmlRpcException(1, e.getMessage(), e);
    }
    return;
}
Also used : AuthenticationManager(org.apache.wiki.auth.AuthenticationManager) WikiSecurityException(org.apache.wiki.auth.WikiSecurityException) AuthorizationManager(org.apache.wiki.auth.AuthorizationManager) XmlRpcException(org.apache.xmlrpc.XmlRpcException)

Example 2 with AuthorizationManager

use of org.apache.wiki.auth.AuthorizationManager in project jspwiki by apache.

the class BasicSearchProvider method findPages.

private Collection findPages(QueryItem[] query, WikiContext wikiContext) {
    TreeSet<SearchResult> res = new TreeSet<SearchResult>(new SearchResultComparator());
    SearchMatcher matcher = new SearchMatcher(m_engine, query);
    Collection allPages = null;
    try {
        allPages = m_engine.getPageManager().getAllPages();
    } catch (ProviderException pe) {
        log.error("Unable to retrieve page list", pe);
        return null;
    }
    AuthorizationManager mgr = m_engine.getAuthorizationManager();
    Iterator it = allPages.iterator();
    while (it.hasNext()) {
        try {
            WikiPage page = (WikiPage) it.next();
            if (page != null) {
                PagePermission pp = new PagePermission(page, PagePermission.VIEW_ACTION);
                if (wikiContext == null || mgr.checkPermission(wikiContext.getWikiSession(), pp)) {
                    String pageName = page.getName();
                    String pageContent = m_engine.getPageManager().getPageText(pageName, WikiPageProvider.LATEST_VERSION) + attachmentNames(page, " ");
                    SearchResult comparison = matcher.matchPageContent(pageName, pageContent);
                    if (comparison != null) {
                        res.add(comparison);
                    }
                }
            }
        } catch (ProviderException pe) {
            log.error("Unable to retrieve page from cache", pe);
        } catch (IOException ioe) {
            log.error("Failed to search page", ioe);
        }
    }
    return res;
}
Also used : ProviderException(org.apache.wiki.api.exceptions.ProviderException) WikiPage(org.apache.wiki.WikiPage) IOException(java.io.IOException) TreeSet(java.util.TreeSet) Iterator(java.util.Iterator) Collection(java.util.Collection) AuthorizationManager(org.apache.wiki.auth.AuthorizationManager) PagePermission(org.apache.wiki.auth.permissions.PagePermission)

Example 3 with AuthorizationManager

use of org.apache.wiki.auth.AuthorizationManager in project jspwiki by apache.

the class PermissionTag method checkPermission.

/**
 *  Checks a single permission.
 *
 *  @param permission
 *  @return true if granted, false if not
 */
private boolean checkPermission(String permission) {
    WikiSession session = m_wikiContext.getWikiSession();
    WikiPage page = m_wikiContext.getPage();
    AuthorizationManager mgr = m_wikiContext.getEngine().getAuthorizationManager();
    boolean gotPermission = false;
    if (CREATE_GROUPS.equals(permission) || CREATE_PAGES.equals(permission) || EDIT_PREFERENCES.equals(permission) || EDIT_PROFILE.equals(permission) || LOGIN.equals(permission)) {
        gotPermission = mgr.checkPermission(session, new WikiPermission(page.getWiki(), permission));
    } else if (VIEW_GROUP.equals(permission) || EDIT_GROUP.equals(permission) || DELETE_GROUP.equals(permission)) {
        Command command = m_wikiContext.getCommand();
        gotPermission = false;
        if (command instanceof GroupCommand && command.getTarget() != null) {
            GroupPrincipal group = (GroupPrincipal) command.getTarget();
            String groupName = group.getName();
            String action = "view";
            if (EDIT_GROUP.equals(permission)) {
                action = "edit";
            } else if (DELETE_GROUP.equals(permission)) {
                action = "delete";
            }
            gotPermission = mgr.checkPermission(session, new GroupPermission(groupName, action));
        }
    } else if (ALL_PERMISSION.equals(permission)) {
        gotPermission = mgr.checkPermission(session, new AllPermission(m_wikiContext.getEngine().getApplicationName()));
    } else if (page != null) {
        // 
        if (EDIT.equals(permission)) {
            WikiPage latest = m_wikiContext.getEngine().getPage(page.getName());
            if (page.getVersion() != WikiProvider.LATEST_VERSION && latest.getVersion() != page.getVersion()) {
                return false;
            }
        }
        Permission p = PermissionFactory.getPagePermission(page, permission);
        gotPermission = mgr.checkPermission(session, p);
    }
    return gotPermission;
}
Also used : WikiSession(org.apache.wiki.WikiSession) GroupCommand(org.apache.wiki.ui.GroupCommand) Command(org.apache.wiki.ui.Command) GroupCommand(org.apache.wiki.ui.GroupCommand) GroupPrincipal(org.apache.wiki.auth.GroupPrincipal) WikiPage(org.apache.wiki.WikiPage) WikiPermission(org.apache.wiki.auth.permissions.WikiPermission) AllPermission(org.apache.wiki.auth.permissions.AllPermission) Permission(java.security.Permission) GroupPermission(org.apache.wiki.auth.permissions.GroupPermission) AllPermission(org.apache.wiki.auth.permissions.AllPermission) GroupPermission(org.apache.wiki.auth.permissions.GroupPermission) AuthorizationManager(org.apache.wiki.auth.AuthorizationManager) WikiPermission(org.apache.wiki.auth.permissions.WikiPermission)

Example 4 with AuthorizationManager

use of org.apache.wiki.auth.AuthorizationManager in project jspwiki by apache.

the class AttachmentServlet method doGet.

/**
 *  Serves a GET with two parameters: 'wikiname' specifying the wikiname
 *  of the attachment, 'version' specifying the version indicator.
 */
// FIXME: Messages would need to be localized somehow.
public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {
    WikiContext context = m_engine.createContext(req, WikiContext.ATTACH);
    String version = req.getParameter(HDR_VERSION);
    String nextPage = req.getParameter("nextpage");
    String msg = "An error occurred. Ouch.";
    int ver = WikiProvider.LATEST_VERSION;
    AttachmentManager mgr = m_engine.getAttachmentManager();
    AuthorizationManager authmgr = m_engine.getAuthorizationManager();
    String page = context.getPage().getName();
    if (page == null) {
        log.info("Invalid attachment name.");
        res.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }
    OutputStream out = null;
    InputStream in = null;
    try {
        log.debug("Attempting to download att " + page + ", version " + version);
        if (version != null) {
            ver = Integer.parseInt(version);
        }
        Attachment att = mgr.getAttachmentInfo(page, ver);
        if (att != null) {
            // 
            // Check if the user has permission for this attachment
            // 
            Permission permission = PermissionFactory.getPagePermission(att, "view");
            if (!authmgr.checkPermission(context.getWikiSession(), permission)) {
                log.debug("User does not have permission for this");
                res.sendError(HttpServletResponse.SC_FORBIDDEN);
                return;
            }
            // 
            if (HttpUtil.checkFor304(req, att.getName(), att.getLastModified())) {
                log.debug("Client has latest version already, sending 304...");
                res.sendError(HttpServletResponse.SC_NOT_MODIFIED);
                return;
            }
            String mimetype = getMimeType(context, att.getFileName());
            res.setContentType(mimetype);
            // 
            // We use 'inline' instead of 'attachment' so that user agents
            // can try to automatically open the file.
            // 
            res.addHeader("Content-Disposition", "inline; filename=\"" + att.getFileName() + "\";");
            res.addDateHeader("Last-Modified", att.getLastModified().getTime());
            if (!att.isCacheable()) {
                res.addHeader("Pragma", "no-cache");
                res.addHeader("Cache-control", "no-cache");
            }
            // If a size is provided by the provider, report it.
            if (att.getSize() >= 0) {
                // log.info("size:"+att.getSize());
                res.setContentLength((int) att.getSize());
            }
            out = res.getOutputStream();
            in = mgr.getAttachmentStream(context, att);
            int read = 0;
            byte[] buffer = new byte[BUFFER_SIZE];
            while ((read = in.read(buffer)) > -1) {
                out.write(buffer, 0, read);
            }
            if (log.isDebugEnabled()) {
                msg = "Attachment " + att.getFileName() + " sent to " + req.getRemoteUser() + " on " + HttpUtil.getRemoteAddress(req);
                log.debug(msg);
            }
            if (nextPage != null) {
                res.sendRedirect(validateNextPage(nextPage, m_engine.getURL(WikiContext.ERROR, "", null, false)));
            }
        } else {
            msg = "Attachment '" + page + "', version " + ver + " does not exist.";
            log.info(msg);
            res.sendError(HttpServletResponse.SC_NOT_FOUND, msg);
        }
    } catch (ProviderException pe) {
        msg = "Provider error: " + pe.getMessage();
        log.debug("Provider failed while reading", pe);
        // 
        try {
            res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg);
        } catch (IllegalStateException e) {
        }
    } catch (NumberFormatException nfe) {
        log.warn("Invalid version number: " + version);
        res.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid version number");
    } catch (SocketException se) {
        // 
        // These are very common in download situations due to aggressive
        // clients.  No need to try and send an error.
        // 
        log.debug("I/O exception during download", se);
    } catch (IOException ioe) {
        // 
        // Client dropped the connection or something else happened.
        // We don't know where the error came from, so we'll at least
        // try to send an error and catch it quietly if it doesn't quite work.
        // 
        msg = "Error: " + ioe.getMessage();
        log.debug("I/O exception during download", ioe);
        try {
            res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg);
        } catch (IllegalStateException e) {
        }
    } finally {
        IOUtils.closeQuietly(in);
        // 
        // Quite often, aggressive clients close the connection when they have
        // received the last bits.  Therefore, we close the output, but ignore
        // any exception that might come out of it.
        // 
        IOUtils.closeQuietly(out);
    }
}
Also used : SocketException(java.net.SocketException) WikiContext(org.apache.wiki.WikiContext) ProviderException(org.apache.wiki.api.exceptions.ProviderException) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) IOException(java.io.IOException) Permission(java.security.Permission) AuthorizationManager(org.apache.wiki.auth.AuthorizationManager)

Example 5 with AuthorizationManager

use of org.apache.wiki.auth.AuthorizationManager in project jspwiki by apache.

the class WeblogPlugin method execute.

/**
 *  {@inheritDoc}
 */
@SuppressWarnings("unchecked")
public String execute(WikiContext context, Map<String, String> params) throws PluginException {
    Calendar startTime;
    Calendar stopTime;
    int numDays = DEFAULT_DAYS;
    WikiEngine engine = context.getEngine();
    AuthorizationManager mgr = engine.getAuthorizationManager();
    // 
    // Parse parameters.
    // 
    String days;
    DateFormat entryFormat;
    String startDay = null;
    boolean hasComments = false;
    int maxEntries;
    String weblogName;
    if ((weblogName = params.get(PARAM_PAGE)) == null) {
        weblogName = context.getPage().getName();
    }
    if ((days = context.getHttpParameter("weblog." + PARAM_DAYS)) == null) {
        days = params.get(PARAM_DAYS);
    }
    if ((params.get(PARAM_ENTRYFORMAT)) == null) {
        entryFormat = Preferences.getDateFormat(context, TimeFormat.DATETIME);
    } else {
        entryFormat = new SimpleDateFormat(params.get(PARAM_ENTRYFORMAT));
    }
    if (days != null) {
        if (days.equalsIgnoreCase("all")) {
            numDays = Integer.MAX_VALUE;
        } else {
            numDays = TextUtil.parseIntParameter(days, DEFAULT_DAYS);
        }
    }
    if ((startDay = params.get(PARAM_STARTDATE)) == null) {
        startDay = context.getHttpParameter("weblog." + PARAM_STARTDATE);
    }
    if (TextUtil.isPositive(params.get(PARAM_ALLOWCOMMENTS))) {
        hasComments = true;
    }
    maxEntries = TextUtil.parseIntParameter(params.get(PARAM_MAXENTRIES), Integer.MAX_VALUE);
    // 
    // Determine the date range which to include.
    // 
    startTime = Calendar.getInstance();
    stopTime = Calendar.getInstance();
    if (startDay != null) {
        SimpleDateFormat fmt = new SimpleDateFormat(DEFAULT_DATEFORMAT);
        try {
            Date d = fmt.parse(startDay);
            startTime.setTime(d);
            stopTime.setTime(d);
        } catch (ParseException e) {
            return "Illegal time format: " + startDay;
        }
    }
    // 
    // Mark this to be a weblog
    // 
    context.getPage().setAttribute(ATTR_ISWEBLOG, "true");
    // 
    // We make a wild guess here that nobody can do millisecond
    // accuracy here.
    // 
    startTime.add(Calendar.DAY_OF_MONTH, -numDays);
    startTime.set(Calendar.HOUR, 0);
    startTime.set(Calendar.MINUTE, 0);
    startTime.set(Calendar.SECOND, 0);
    stopTime.set(Calendar.HOUR, 23);
    stopTime.set(Calendar.MINUTE, 59);
    stopTime.set(Calendar.SECOND, 59);
    StringBuilder sb = new StringBuilder();
    try {
        List<WikiPage> blogEntries = findBlogEntries(engine, weblogName, startTime.getTime(), stopTime.getTime());
        Collections.sort(blogEntries, new PageDateComparator());
        sb.append("<div class=\"weblog\">\n");
        for (Iterator<WikiPage> i = blogEntries.iterator(); i.hasNext() && maxEntries-- > 0; ) {
            WikiPage p = i.next();
            if (mgr.checkPermission(context.getWikiSession(), new PagePermission(p, PagePermission.VIEW_ACTION))) {
                addEntryHTML(context, entryFormat, hasComments, sb, p);
            }
        }
        sb.append("</div>\n");
    } catch (ProviderException e) {
        log.error("Could not locate blog entries", e);
        throw new PluginException("Could not locate blog entries: " + e.getMessage());
    }
    return sb.toString();
}
Also used : ProviderException(org.apache.wiki.api.exceptions.ProviderException) Calendar(java.util.Calendar) WikiPage(org.apache.wiki.WikiPage) PluginException(org.apache.wiki.api.exceptions.PluginException) Date(java.util.Date) SimpleDateFormat(java.text.SimpleDateFormat) DateFormat(java.text.DateFormat) AuthorizationManager(org.apache.wiki.auth.AuthorizationManager) ParseException(java.text.ParseException) WikiEngine(org.apache.wiki.WikiEngine) SimpleDateFormat(java.text.SimpleDateFormat) PagePermission(org.apache.wiki.auth.permissions.PagePermission)

Aggregations

AuthorizationManager (org.apache.wiki.auth.AuthorizationManager)8 ProviderException (org.apache.wiki.api.exceptions.ProviderException)6 WikiPage (org.apache.wiki.WikiPage)5 IOException (java.io.IOException)4 PagePermission (org.apache.wiki.auth.permissions.PagePermission)3 File (java.io.File)2 Permission (java.security.Permission)2 Date (java.util.Date)2 WikiContext (org.apache.wiki.WikiContext)2 WikiEngine (org.apache.wiki.WikiEngine)2 PluginException (org.apache.wiki.api.exceptions.PluginException)2 InputStream (java.io.InputStream)1 OutputStream (java.io.OutputStream)1 StringReader (java.io.StringReader)1 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 SocketException (java.net.SocketException)1 DateFormat (java.text.DateFormat)1 ParseException (java.text.ParseException)1 SimpleDateFormat (java.text.SimpleDateFormat)1 ArrayList (java.util.ArrayList)1