package com.n2bb.security;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.ServletRequestWrapper;
import javax.servlet.ServletRequest;

import com.n2bb.action.AbstractAction;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForm;

/**
 * Forwards user appropriately upon not authorized.
 *
 * @author kmatsuoka
 * @version $Id: NotAuthorizedAction.java,v 1.1 2006/06/17 00:48:49 rao Exp $
 */
public class NotAuthorizedAction extends AbstractAction {
    protected ActionForward executeAction(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        if (request.getUserPrincipal() != null &&
                request.getUserPrincipal().getName().startsWith(
                        ChangeExpiredPasswordAction.CHPASS_PREFIX
                )) {
            /* Hacktacular: when user's password is expired, his principal is
               set to a dynamically created principal with name = "chpass_<username>",
               where <username> is his usual username.
               Since this user has no priveleges, the request ends up here. */
            String originalURI = null;
            if (request instanceof ServletRequestWrapper) {
                ServletRequest servletRequest = ((ServletRequestWrapper) request).getRequest();
                if (servletRequest instanceof HttpServletRequest) {
                    originalURI = ((HttpServletRequest) servletRequest).getRequestURI();
                }
            }
            if (originalURI != null &&
                    // filter out direct requests for change expired password pages,
                    // which wouldn't make sense  
                    originalURI.indexOf("ExpiredPassword") == -1) {
                request.getSession().setAttribute("originalURI", originalURI);
            }

            return mapping.findForward("changeExpiredPassword");
        }
        else {
            return mapping.findForward("notAuthorized");
        }
    }
}
