/*
 * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved.
 *
 * The contents of this file are subject to the CCM Public
 * License (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.redhat.com/licenses/ccmpl.html.
 *
 * Software distributed under the License is distributed on an
 * "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express
 * or implied. See the License for the specific language
 * governing rights and limitations under the License.
 *
 */
package com.arsdigita.kernel.security;

import javax.servlet.http.HttpServletRequest;

/**
 *  Default implementation of
 * SecurityHelper interface.
 *
 * @author Sameer Ajmani
 * @see SecurityHelper
 **/
public class DefaultSecurityHelper implements SecurityHelper {

    public static final String versionId = "$Id: //core-platform/dev/src/com/arsdigita/kernel/security/DefaultSecurityHelper.java#8 $ by $Author: dennis $, $DateTime: 2004/04/07 16:07:11 $";
    /**
     * Determines whether the request is secure by calling
     * <code>req.isSecure()</code>.
     *
     * @return req.isSecure().
     **/
    public boolean isSecure(HttpServletRequest req) {
        return req.isSecure();
    }

    private static String[] allowedPages = new String[] {
        Initializer.LOGIN_PAGE_KEY,
        Initializer.LOGOUT_PAGE_KEY,
        Initializer.COOKIES_PAGE_KEY,
        Initializer.RECOVER_PAGE_KEY,
        Initializer.EXPIRED_PAGE_KEY,
    };

    /**
     * Determines whether the current request requires that the user be
     * logged in.
     *
     * @return <code>true</code> if the request is secure and the page is
     * not on a list of allowed pages (such as the login page and the
     * bad-password page), <code>false</code> otherwise.
     **/
    public boolean requiresLogin(HttpServletRequest req) {
        // don't require login if request not secure
        if (!isSecure(req)) {
            return false;
        }
        // don't require login if page on allowed list
        String url = req.getRequestURI();
        for (int i = 0; i < allowedPages.length; i++) {
            if (url.equals(Initializer.getFullURL(allowedPages[i], req))) {
                return false;
            }
        }
        // otherwise require login
        return true;
    }

    /**
     * Returns the full URL of the login page stored in the page map.
     *
     * @return the full URL of the login page.
     **/
    public String getLoginURL(HttpServletRequest req) {
        return Initializer.getFullURL(Initializer.LOGIN_PAGE_KEY, req);
    }
}
