import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class customAuthSnoop extends HttpServlet
{
        Hashtable users = new Hashtable();
	
        public void init(ServletConfig config) throws ServletException
        {
                super.init(config);
                users.put("rajneesh:garg","allowed");
                users.put("garg:rajneesh","allowed");
                users.put("garg:Rajneesh","allowed");
                users.put("rajneesh:Garg","allowed");
        }

        public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException
        {
                res.setContentType("text/plain");
                PrintWriter out = res.getWriter();
        	
                String auth = req.getHeader("Authorization");
        	
                if(!allowUser(auth))
                {
                        res.sendError(res.SC_UNAUTHORIZED);
                        res.setHeader("WWW-Authenticate","BASIC realm=\"users\"");
                }
                else
                {
                        out.println("TOP SECRET STUFF, Mr."+req.getRemoteUser());
                }
        }
	
        protected boolean allowUser(String auth) throws IOException
        {
                if(auth==null)
                {
                        return false;
                }
                if(!auth.toUpperCase().startsWith("BASIC"))
                {
                        return false;
                }
                	
                String userPassEncoded = auth.substring(6);
                	
                sun.misc.BASE64Decoder dec = new sun.misc.BASE64Decoder();
                String userPassDecoded = new String(dec.decodeBuffer(userPassEncoded));
                if("allowed".equals(users.get(userPassDecoded)))
                {
                        return true;
                }
                else
                        return false;
        }	
}