/*
 * Copyright
 *   2008 axYus - www.axyus.com
 *   2008 C.Bosquet - charles.bosquet@axyus.com
 *
 * This file is part of XEMELIOS.
 *
 * XEMELIOS is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * XEMELIOS is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with XEMELIOS; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */
package fr.gouv.finances.dgfip.xemelios.web;

import fr.gouv.finances.dgfip.xemelios.auth.XemeliosUser;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.Globals;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.action.RequestProcessor;

/**
 * @author CBO
 * Ce RequestProcessor permet de :
 * <li>Gérer l'expiration de session</li>
 * <li>Gérer les droits en terme de fonctionnalités de l'utilisateur</li>
 */
public class CustomRequestProcessor extends RequestProcessor {

    private static org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(CustomRequestProcessor.class);

    @Override
    protected boolean processRoles(HttpServletRequest request, HttpServletResponse response, ActionMapping mapping) throws IOException, ServletException {
        String roles[] = mapping.getRoleNames();
        if ((roles == null) || (roles.length < 1)) {
            return true;
        }
        XemeliosUser user = AttributeHelper.getUser(request.getSession());
        if (user == null) {
            ActionMessages actionMessages = new ActionMessages();
            actionMessages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("connexion.sessionExpiree"));
            request.getSession().setAttribute(Globals.ERROR_KEY, actionMessages);

            if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) {
                response.sendError(response.SC_FORBIDDEN, request.getContextPath());
            } else {
                response.sendRedirect(request.getContextPath());
            }
            return false;
        } else {
            for (int i = 0; i < roles.length; i++) {
                if (user.hasRole(roles[i])) {
                    return true;
                }
            }
            logger.warn("Tentative d'accés à une fonctionnalité non autorisée, une des fonctionnalités suivantes étaient requises : " + getRolesAsString(roles));
            response.sendRedirect(request.getContextPath() + "/nonAutorise.jsp");
            //response.sendError(HttpServletResponse.SC_FORBIDDEN, getInternal().getMessage("notAuthorized", mapping.getPath()));
            return false;
        }
    }

    private String getRolesAsString(String roles[]) {
        StringBuilder sb = new StringBuilder();
        boolean firstLoop = true;
        for (String role : roles) {
            if (!firstLoop) {
                sb.append(", ");
            }
            sb.append(role);
            firstLoop = false;
        }
        return sb.toString();
    }
}
