]> WPIA git - gigi.git/blob - src/org/cacert/gigi/output/Form.java
Merge branch 'master' into csrParse
[gigi.git] / src / org / cacert / gigi / output / Form.java
1 package org.cacert.gigi.output;
2
3 import java.io.IOException;
4 import java.io.PrintWriter;
5 import java.util.Map;
6
7 import javax.servlet.ServletRequest;
8 import javax.servlet.http.HttpServletRequest;
9 import javax.servlet.http.HttpSession;
10
11 import org.cacert.gigi.localisation.Language;
12 import org.cacert.gigi.pages.Page;
13 import org.cacert.gigi.util.RandomToken;
14
15 public abstract class Form implements Outputable {
16
17     public static final String CSRF_FIELD = "csrf";
18
19     String csrf;
20
21     public Form(HttpServletRequest hsr) {
22         csrf = RandomToken.generateToken(32);
23         HttpSession hs = hsr.getSession();
24         hs.setAttribute("form/" + getClass().getName() + "/" + csrf, this);
25
26     }
27
28     public abstract boolean submit(PrintWriter out, HttpServletRequest req);
29
30     protected String getCsrfFieldName() {
31         return CSRF_FIELD;
32     }
33
34     @Override
35     public void output(PrintWriter out, Language l, Map<String, Object> vars) {
36         out.println("<form method='POST' autocomplete='off'>");
37         outputContent(out, l, vars);
38         out.print("<input type='hidden' name='" + CSRF_FIELD + "' value='");
39         out.print(getCSRFToken());
40         out.println("'></form>");
41     }
42
43     protected abstract void outputContent(PrintWriter out, Language l, Map<String, Object> vars);
44
45     protected void outputError(PrintWriter out, ServletRequest req, String text) {
46         out.print("<div>");
47         out.print(Page.translate(req, text));
48         out.println("</div>");
49     }
50
51     protected String getCSRFToken() {
52         return csrf;
53     }
54
55     public static <T extends Form> T getForm(HttpServletRequest req, Class<T> target) throws CSRFException {
56         String csrf = req.getParameter(CSRF_FIELD);
57         if (csrf == null) {
58             throw new CSRFException();
59         }
60         HttpSession hs = req.getSession();
61         if (hs == null) {
62             throw new CSRFException();
63         }
64         Form f = (Form) hs.getAttribute("form/" + target.getName() + "/" + csrf);
65         if (f == null) {
66             throw new CSRFException();
67         }
68         return (T) f;
69     }
70
71     public static class CSRFException extends IOException {
72
73     }
74 }