package mit.login;

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

/**
 * A simple Servlet that demonstrates how to use the login server.
 */

public class DemoServlet extends HttpServlet {

    private static byte [] key = { (byte) 0x78, (byte) 0x23, (byte) 0x90, (byte) 0x23,
				   (byte) 0xA4, (byte) 0x87, (byte) 0x18, (byte) 0x2D,
				   (byte) 0x32, (byte) 0x3C, (byte) 0xF7, (byte) 0x89,
				   (byte) 0x92, (byte) 0x3F, (byte) 0x28, (byte) 0x37 };

    public void doGet(HttpServletRequest request, HttpServletResponse response) {
	doPost(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) {
	try {
	    String auth = request.getParameter("auth");
	    if (auth == null) {
		sendMessage("Auth parameter not specified", response);
		return;
	    }

	    AuthObj a = new AuthObj(auth, key, false);
	    if (a.timely()) {
		sendMessage("Timely authentication of " + a.getLogin(), response);
		return;
	    } else {
		sendMessage("Expired authentication of " + a.getLogin(), response);
	    }
	} catch (Exception e) {
	    sendMessage(e.toString() + " while verifying authentication", response);
	}
    }

    protected void sendMessage(String message, HttpServletResponse response) {
	try {
	    PrintWriter w = response.getWriter();
	    w.print(message);
	    w.flush();
	} catch (Exception e) {
	    e.printStackTrace();
	    // should do better, but OK for demo
	}
    }
}
