1 4 package xpetstore.web.filter; 5 6 import java.io.IOException ; 7 8 import java.util.HashMap ; 9 import java.util.StringTokenizer ; 10 11 import javax.servlet.Filter ; 12 import javax.servlet.FilterChain ; 13 import javax.servlet.FilterConfig ; 14 import javax.servlet.ServletException ; 15 import javax.servlet.ServletRequest ; 16 import javax.servlet.ServletResponse ; 17 import javax.servlet.http.HttpServletRequest ; 18 import javax.servlet.http.HttpSession ; 19 20 import org.apache.commons.logging.Log; 21 import org.apache.commons.logging.LogFactory; 22 23 import xpetstore.web.webwork.action.BaseAction; 24 25 26 47 public class SignOnFilter 48 implements Filter 49 { 50 52 private static final Log __log = LogFactory.getLog( SignOnFilter.class ); 53 54 56 private String _signon; 57 private HashMap _protectedUris = new HashMap ( ); 58 private FilterConfig _config; 59 60 62 65 public void init( FilterConfig config ) 66 throws ServletException 67 { 68 __log.info( "init()" ); 69 70 _config = config; 71 72 73 _signon = config.getInitParameter( "signon.action" ); 74 __log.info( "...signon.action=" + _signon ); 75 76 77 String uri = config.getInitParameter( "protected.uri" ); 78 StringTokenizer tok = new StringTokenizer ( uri, "," ); 79 80 while ( tok.hasMoreTokens( ) ) 81 { 82 String url = tok.nextToken( ); 83 _protectedUris.put( url, url ); 84 85 __log.info( "...Adding URI to protect: " + url ); 86 } 87 } 88 89 92 public void doFilter( ServletRequest request, 93 ServletResponse response, 94 FilterChain chain ) 95 throws IOException , 96 ServletException 97 { 98 HttpServletRequest req = ( HttpServletRequest ) request; 99 100 101 String uri = req.getRequestURI( ); 102 103 if ( uri.startsWith( "/" ) ) 104 { 105 uri = uri.substring( 1 ); 106 } 107 108 int i = uri.indexOf( "/" ); 109 110 if ( i >= 0 ) 111 { 112 uri = uri.substring( i + 1 ); 113 } 114 else {} 115 116 117 if ( isProtected( uri ) && !isSignedIn( req ) ) 118 { 119 String forward = _signon + "?redirectUri=" + uri; 120 _config.getServletContext( ).getRequestDispatcher( forward ).forward( request, response ); 121 } 122 else 123 { 124 chain.doFilter( request, response ); 125 } 126 } 127 128 131 public void destroy( ) 132 { 133 _protectedUris.clear( ); 134 } 135 136 public boolean isProtected( String uri ) 137 { 138 return ( _protectedUris.get( uri ) != null ); 139 } 140 141 public boolean isSignedIn( HttpServletRequest request ) 142 { 143 HttpSession session = request.getSession( false ); 144 145 return ( session == null ) 146 ? false 147 : ( session.getAttribute( BaseAction.USERID_KEY ) != null ); 148 } 149 } 150 | Popular Tags |