/*
 * 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.utils.www.ParametrizedFilter;
import com.queplix.core.utils.www.ServletHelper;

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

/**
 * Filter, that checks for the attribute in the session and redirects to
 * the given URL if the check has failed.
 *
 * @author [DAG] Dmitry Gaponenko
 * @author [ALB] Baranov Andrey
 * @version $Revision: 1.1.1.1 $ $Date: 2005/09/12 15:30:57 $
 */
public class SecurityHTMLFilter
        extends ParametrizedFilter {

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

        HttpServletRequest req = (HttpServletRequest) request;

        // Get session (create if necessary).
        HttpSession session = req.getSession(true);

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

            // Can`t find this parameter in session, so redirect to given URL.

            // remember last URL
            // later forward on it in LoginServlet
            String rUrl = ServletHelper.getRequestURL(req);
            session.setAttribute("login.successUrl", rUrl);

            HttpServletResponse res = (HttpServletResponse) response;
            res.sendRedirect(paramValue);

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

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

}
