]> WPIA git - gigi.git/blob - src/org/cacert/gigi/output/Form.java
dd244d749afc36077bc49e55b5813268b17ddf4c
[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.Language;
12 import org.cacert.gigi.pages.Page;
13 import org.cacert.gigi.util.RandomToken;
14
15 public abstract class Form implements Outputable {
16         public static final String CSRF_FIELD = "csrf";
17         String csrf;
18
19         public Form(HttpServletRequest hsr) {
20                 csrf = RandomToken.generateToken(32);
21                 HttpSession hs = hsr.getSession();
22                 hs.setAttribute("form/" + getClass().getName() + "/" + csrf, this);
23
24         }
25
26         public abstract boolean submit(PrintWriter out, HttpServletRequest req);
27
28         @Override
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>");
35         }
36
37         protected abstract void outputContent(PrintWriter out, Language l, Map<String, Object> vars);
38
39         protected void outputError(PrintWriter out, ServletRequest req, String text) {
40                 out.print("<div>");
41                 out.print(Page.translate(req, text));
42                 out.println("</div>");
43         }
44
45         protected String getCSRFToken() {
46                 return csrf;
47         }
48
49         public static <T extends Form> T getForm(HttpServletRequest req, Class<T> target) throws CSRFException {
50                 String csrf = req.getParameter(CSRF_FIELD);
51                 if (csrf == null) {
52                         throw new CSRFException();
53                 }
54                 HttpSession hs = req.getSession();
55                 if (hs == null) {
56                         throw new CSRFException();
57                 }
58                 Form f = (Form) hs.getAttribute("form/" + target.getName() + "/" + csrf);
59                 if (f == null) {
60                         throw new CSRFException();
61                 }
62                 return (T) f;
63         }
64
65         public static class CSRFException extends IOException {
66
67         }
68 }