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 {
16 public static final String CSRF_FIELD = "csrf";
19 public Form(HttpServletRequest hsr) {
20 csrf = RandomToken.generateToken(32);
21 HttpSession hs = hsr.getSession();
22 hs.setAttribute("form/" + getClass().getName() + "/" + csrf, this);
26 public abstract boolean submit(PrintWriter out, HttpServletRequest req);
29 public final void output(PrintWriter out, Language l, Map<String, Object> vars) {
30 out.println("<form method='POST' autocomplete='off'>");
31 outputContent(out, l, vars);
32 out.print("<input type='hidden' name='" + CSRF_FIELD + "' value='");
33 out.print(getCSRFToken());
34 out.println("'></form>");
37 protected abstract void outputContent(PrintWriter out, Language l, Map<String, Object> vars);
39 protected void outputError(PrintWriter out, ServletRequest req, String text) {
41 out.print(Page.translate(req, text));
42 out.println("</div>");
45 protected String getCSRFToken() {
49 public static <T extends Form> T getForm(HttpServletRequest req, Class<T> target) throws CSRFException {
50 String csrf = req.getParameter(CSRF_FIELD);
52 throw new CSRFException();
54 HttpSession hs = req.getSession();
56 throw new CSRFException();
58 Form f = (Form) hs.getAttribute("form/" + target.getName() + "/" + csrf);
60 throw new CSRFException();
65 public static class CSRFException extends IOException {