001/*
002 * (C) Copyright 2006-2010 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 *
016 * Contributors:
017 *     Thierry Delprat
018 */
019package org.nuxeo.apidoc.filter;
020
021import java.io.IOException;
022
023import javax.servlet.FilterChain;
024import javax.servlet.ServletException;
025import javax.servlet.ServletRequest;
026import javax.servlet.ServletResponse;
027import javax.servlet.http.HttpServletRequest;
028import javax.servlet.http.HttpServletResponse;
029
030import org.nuxeo.ecm.core.api.NuxeoPrincipal;
031import org.nuxeo.ecm.platform.web.common.vh.VirtualHostHelper;
032
033public class RedirectFilter extends BaseApiDocFilter {
034
035    protected boolean isUriValidForAnonymous(HttpServletRequest request) {
036        String uri = request.getRequestURI();
037        if (uri.contains("/nxpath/")) {
038            return false;
039        }
040        if (uri.contains("/nxdoc/")) {
041            return false;
042        }
043        if (uri.contains(".faces")) {
044            return false;
045        }
046        if (uri.contains(".xhtml")) {
047            return false;
048        }
049        return true;
050    }
051
052    protected void redirectToWebEngineView(HttpServletRequest httpRequest, HttpServletResponse httpResponse)
053            throws IOException {
054        String base = VirtualHostHelper.getBaseURL(httpRequest);
055        String location = base + "site/distribution/";
056        httpResponse.sendRedirect(location);
057    }
058
059    @Override
060    protected void internalDoFilter(ServletRequest request, ServletResponse response, FilterChain chain)
061            throws IOException, ServletException {
062
063        HttpServletRequest httpRequest = (HttpServletRequest) request;
064        HttpServletResponse httpResponse = (HttpServletResponse) response;
065
066        NuxeoPrincipal nxUser = (NuxeoPrincipal) httpRequest.getUserPrincipal();
067
068        if (nxUser != null && nxUser.isAnonymous()) {
069            if (!isUriValidForAnonymous(httpRequest)) {
070                redirectToWebEngineView(httpRequest, httpResponse);
071            }
072        }
073
074        chain.doFilter(httpRequest, httpResponse);
075    }
076
077}