001/**
002 * Copyright 2005-2018 The Kuali Foundation
003 *
004 * Licensed under the Educational Community License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.opensource.org/licenses/ecl2.php
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016package org.kuali.rice.krad.web.filter;
017
018import java.io.IOException;
019
020import javax.servlet.Filter;
021import javax.servlet.FilterChain;
022import javax.servlet.FilterConfig;
023import javax.servlet.ServletException;
024import javax.servlet.ServletRequest;
025import javax.servlet.ServletResponse;
026import javax.servlet.http.HttpServletRequest;
027import javax.servlet.http.HttpServletRequestWrapper;
028
029/**
030 * Automatically logs in with the user specified via filter init parameter {@link AutoLoginFilter#USER_PARAM_NAME}
031 *
032 * <p>
033 * There are no guarantees made that the user specified is a valid user in the system.
034 * </p>
035 *
036 * <p>
037 * In rice this Filter can be used via config like that following assuming the bootstrap filter is used: <br />
038 * {@code <param name="filter.login.class">org.kuali.kra.test.infrastructure.AutoLoginFilter</param>} <br />
039 * {@code <param name="filtermapping.login.1">/*</param>} <br />
040 * {@code <param name="filter.login.autouser">admin</param>} <br />
041 * </p>
042 *
043 * @author Kuali Rice Team (rice.collab@kuali.org)
044 */
045public class AutoLoginFilter implements Filter {
046        public static final String USER_PARAM_NAME = "autouser";
047    
048        private FilterConfig filterConfig;
049        
050        /** {@inheritDoc} */
051        public void init(FilterConfig config) throws ServletException {
052            this.filterConfig = config;
053        }
054
055        /** {@inheritDoc} */
056        public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
057                if (filterConfig.getInitParameter(USER_PARAM_NAME) == null) {
058                    throw new IllegalStateException("the " + USER_PARAM_NAME + " param is not set");
059                }
060            
061            chain.doFilter(new HttpServletRequestWrapper((HttpServletRequest) request) {
062            @Override
063            public String getRemoteUser() {
064                return AutoLoginFilter.this.filterConfig.getInitParameter(USER_PARAM_NAME);
065            }
066        }, response);
067        }
068
069        /** {@inheritDoc} */
070        public void destroy() {
071            this.filterConfig = null;
072        }
073}