/*
 * Copyright 1997-2013
 *
 * http://www.pconline.com.cn
 *
 */
package cn.pconline.pcgeli.web;

import java.io.IOException;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.gelivable.auth.GeliAuthFacade;
import org.gelivable.auth.entity.GeliFunction;
import org.gelivable.web.AbstractAuthFilter;
import org.gelivable.web.Env;
import org.gelivable.web.EnvUtils;

/**
 *
 * @author chenxiaohu
 */
public class AuthFilter extends AbstractAuthFilter {
    Log LOG = LogFactory.getLog(AuthFilter.class);

    static final String CREATE_DO = "create.do";
    static final String UPDATE_DO = "update.do";
    static final String DELETE_DO = "delete.do";

    @Override
    public void init(FilterConfig filterConfig) throws ServletException { }

    @Override
    public void destroy() { }

    @Override
    public void sendAuthFail(HttpServletResponse resp, boolean json) throws IOException {
        if (json) {
            resp.setCharacterEncoding("UTF-8");
            resp.setContentType("text/json");
            resp.getWriter().println("{\"statusCode\":300, \"message\":\"没有权限！\"}");
        } else {
            resp.setCharacterEncoding("UTF-8");
            resp.setContentType("text/html");
            resp.getWriter().print("<div class=\"pageContent\">"
                    + "<div style='padding-top:200px;text-align:center;"
                    + "font-size:24px;color:red;'>"
                    + "没有权限!</div></div>");
        }
    }

    @Override
    public int hasRight(HttpServletRequest req) {
        Env env = EnvUtils.getEnv();
        GeliAuthFacade authFacade = env.getBean(GeliAuthFacade.class);

        // examples...
        if (matchActions("sales", req, CREATE_DO, UPDATE_DO, DELETE_DO)) {
            return authFacade.hasRight(GeliFunction.read("sales_maint")) ? HAS_RIGHT : HAS_NOT_RIGHT;
        }
        return DEFAULT_RIGHT;
    }

    // check request uri match ${contextPath}/admin/${entityName}/${one of actions}
    boolean matchActions(String entityName, HttpServletRequest req, String ... actions) {
        String uri = req.getRequestURI();
        Env env = EnvUtils.getEnv();
        String uriPrefix = env.getServletContext().getContextPath() + "/admin/" + entityName.toLowerCase() + '/';
        for (String action : actions) {
            if (uri.startsWith(uriPrefix + action)) {
                return true;
            }
        }
        return false;
    }
}
