1 package org.cacert.gigi.output.template;
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.GigiApiException;
12 import org.cacert.gigi.localisation.Language;
13 import org.cacert.gigi.pages.Page;
14 import org.cacert.gigi.util.RandomToken;
16 public abstract class Form implements Outputable {
18 public static final String CSRF_FIELD = "csrf";
20 private final String csrf;
22 private final String action;
24 public Form(HttpServletRequest hsr) {
28 public Form(HttpServletRequest hsr, String action) {
29 csrf = RandomToken.generateToken(32);
31 HttpSession hs = hsr.getSession();
32 hs.setAttribute("form/" + getClass().getName() + "/" + csrf, this);
35 public abstract boolean submit(PrintWriter out, HttpServletRequest req) throws GigiApiException;
37 protected String getCsrfFieldName() {
42 public void output(PrintWriter out, Language l, Map<String, Object> vars) {
44 out.println("<form method='POST'>");
46 out.println("<form method='POST' action='" + action + "'>");
49 outputContent(out, l, vars);
50 out.print("<input type='hidden' name='" + CSRF_FIELD + "' value='");
51 out.print(getCSRFToken());
52 out.println("'></form>");
55 protected abstract void outputContent(PrintWriter out, Language l, Map<String, Object> vars);
59 protected void outputError(PrintWriter out, ServletRequest req, String text, Object... contents) {
62 out.println("<div class='formError'>");
65 if (contents.length == 0) {
66 out.print(Page.translate(req, text));
68 out.print(String.format(Page.translate(req, text), contents));
70 out.println("</div>");
73 protected void outputErrorPlain(PrintWriter out, String text) {
76 out.println("<div class='formError'>");
80 out.println("</div>");
83 public boolean isFailed(PrintWriter out) {
85 out.println("</div>");
90 protected String getCSRFToken() {
94 public static <T extends Form> T getForm(HttpServletRequest req, Class<T> target) throws CSRFException {
95 String csrf = req.getParameter(CSRF_FIELD);
97 throw new CSRFException();
99 HttpSession hs = req.getSession();
101 throw new CSRFException();
103 Form f = (Form) hs.getAttribute("form/" + target.getName() + "/" + csrf);
105 throw new CSRFException();
110 public static class CSRFException extends IOException {