1 package org.cacert.gigi.output;
3 import java.io.IOException;
4 import java.io.PrintWriter;
7 import javax.servlet.ServletRequest;
8 import javax.servlet.http.HttpServletRequest;
9 import javax.servlet.http.HttpSession;
11 import org.cacert.gigi.Language;
12 import org.cacert.gigi.pages.Page;
13 import org.cacert.gigi.util.RandomToken;
15 public abstract class Form implements Outputable {
17 public static final String CSRF_FIELD = "csrf";
21 public Form(HttpServletRequest hsr) {
22 csrf = RandomToken.generateToken(32);
23 HttpSession hs = hsr.getSession();
24 hs.setAttribute("form/" + getClass().getName() + "/" + csrf, this);
28 public abstract boolean submit(PrintWriter out, HttpServletRequest req);
31 public final void output(PrintWriter out, Language l, Map<String, Object> vars) {
32 out.println("<form method='POST' autocomplete='off'>");
33 outputContent(out, l, vars);
34 out.print("<input type='hidden' name='" + CSRF_FIELD + "' value='");
35 out.print(getCSRFToken());
36 out.println("'></form>");
39 protected abstract void outputContent(PrintWriter out, Language l, Map<String, Object> vars);
41 protected void outputError(PrintWriter out, ServletRequest req, String text) {
43 out.print(Page.translate(req, text));
44 out.println("</div>");
47 protected String getCSRFToken() {
51 public static <T extends Form> T getForm(HttpServletRequest req, Class<T> target) throws CSRFException {
52 String csrf = req.getParameter(CSRF_FIELD);
54 throw new CSRFException();
56 HttpSession hs = req.getSession();
58 throw new CSRFException();
60 Form f = (Form) hs.getAttribute("form/" + target.getName() + "/" + csrf);
62 throw new CSRFException();
67 public static class CSRFException extends IOException {