package com.atlassian.jira.web.filters;

import com.atlassian.seraph.config.SecurityConfig;
import com.atlassian.seraph.filter.SecurityFilter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.security.Principal;

import org.apache.log4j.Category;

/**
 * Logs JIRA username and request URL via log4j.
 */
public class AccessLogFilter implements Filter
{
    private FilterConfig config;
    Category log = Category.getInstance(AccessLogFilter.class);

    public void init(FilterConfig filterConfig) throws ServletException
    {
        this.config = filterConfig;
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException
    {
        if (log.isInfoEnabled())
        {
            Principal user = ((SecurityConfig) config.getServletContext().getAttribute(SecurityConfig.STORAGE_KEY)).getAuthenticator().getUser((HttpServletRequest)request, (HttpServletResponse)response);
            String url = (String) request.getAttribute(SecurityFilter.ORIGINAL_URL);
            StringBuffer buf = new StringBuffer();

            buf.append(user == null ? "-" : ""+user).append(" ");
            buf.append(url);
            log.info(buf.toString());
        }
        chain.doFilter(request, response);
    }

    public void destroy()
    {
        config = null;
    }
}
