/*
 * Copyright 2006-2007 Queplix Corp.
 *
 * Licensed under the Queplix Public License, Version 1.1.1 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.queplix.com/solutions/commercial-open-source/queplix-public-license/
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 *
 */

package com.queplix.core.modules.security.www;

import com.queplix.core.integrator.security.SessionExpiredException;
import com.queplix.core.jxb.error.QwException;
import com.queplix.core.utils.www.ParametrizedFilter;
import com.queplix.core.utils.www.ServletHelper;
import com.queplix.core.utils.xml.XMLHelper;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * Filter, that checks for the attribute in the session and send error (as an
 * XML packet) if the check has failed.
 *
 * @author [DAG] Dmitry Gaponenko
 * @author [ALB] Baranov Andrey
 * @author Kozmin Sergey
 * @version $Revision: 1.1.1.1 $ $Date: 2005/09/12 15:30:57 $
 */
public class SecurityXMLFilter
        extends ParametrizedFilter {

    // Filter method
    public boolean doFilterParam(ServletRequest request,
                                 ServletResponse response,
                                 FilterChain chain,
                                 String paramName,
                                 String paramValue)
            throws IOException, ServletException {

        // Get session (create it necessary).
        HttpServletRequest req = (HttpServletRequest) request;

        boolean isLoggedIn = com.queplix.core.integrator.security
                .WebLoginManager.getLogonSession(req) != null;

        // check permissions
        if(!isLoggedIn) {
            SessionExpiredException se = new SessionExpiredException();
            ErrorServletHelper esh = new ErrorServletHelper(
                    (HttpServletRequest) request);
            QwException qe = esh.process(se, null, ServletHelper.getRequestURL(
                    req));

            response.setContentType(ServletHelper.CONTENT_TYPE_XML);
            response.getWriter().write(XMLHelper.writeObject(qe));

            // Don't chain the next filter.
            return true;

        } else {

            // Chain the next filter.
            return false;
        }
    }
}
