]> WPIA git - gigi.git/blob - src/org/cacert/gigi/output/template/Form.java
1eb0efa04e5f8ca4a87fc906bf2906f3eb7d3a4d
[gigi.git] / src / org / cacert / gigi / output / template / Form.java
1 package org.cacert.gigi.output.template;
2
3 import java.io.IOException;
4 import java.io.PrintWriter;
5 import java.util.HashMap;
6 import java.util.Map;
7
8 import javax.servlet.http.HttpServletRequest;
9 import javax.servlet.http.HttpSession;
10
11 import org.cacert.gigi.GigiApiException;
12 import org.cacert.gigi.localisation.Language;
13 import org.cacert.gigi.pages.LoginPage;
14 import org.cacert.gigi.util.RandomToken;
15
16 /**
17  * A generic HTML-form that handles CSRF-token creation.
18  */
19 public abstract class Form implements Outputable {
20
21     public static final String CSRF_FIELD = "csrf";
22
23     private final String csrf;
24
25     private final String action;
26
27     /**
28      * Creates a new {@link Form}.
29      * 
30      * @param hsr
31      *            the request to register the form against.
32      */
33     public Form(HttpServletRequest hsr) {
34         this(hsr, null);
35     }
36
37     /**
38      * Creates a new {@link Form}.
39      * 
40      * @param hsr
41      *            the request to register the form against.
42      * @param action
43      *            the target path where the form should be submitted.
44      */
45     public Form(HttpServletRequest hsr, String action) {
46         csrf = RandomToken.generateToken(32);
47         this.action = action;
48         HttpSession hs = hsr.getSession();
49         hs.setAttribute("form/" + getClass().getName() + "/" + csrf, this);
50     }
51
52     /**
53      * Update the forms internal state based on submitted data.
54      * 
55      * @param out
56      *            the stream to the user.
57      * @param req
58      *            the request to take the initial data from.
59      * @return true, iff the form succeeded and the user should be redirected.
60      * @throws GigiApiException
61      *             if internal operations went wrong.
62      */
63     public abstract boolean submit(PrintWriter out, HttpServletRequest req) throws GigiApiException;
64
65     /**
66      * Calls {@link #submit(PrintWriter, HttpServletRequest)} while catching and
67      * displaying errors ({@link GigiApiException}), and re-outputing the form
68      * via {@link #output(PrintWriter, Language, Map)}.
69      * 
70      * @param out
71      *            the target to write the form and errors to
72      * @param req
73      *            the request that this submit originated (for submit and for
74      *            language)
75      * @return as {@link #submit(PrintWriter, HttpServletRequest)}: true, iff
76      *         the form succeeded and the user should be redirected.
77      */
78     public boolean submitProtected(PrintWriter out, HttpServletRequest req) {
79         try {
80             boolean succeeded = submit(out, req);
81             if (succeeded) {
82                 return true;
83             }
84         } catch (GigiApiException e) {
85             e.format(out, LoginPage.getLanguage(req));
86         }
87         output(out, LoginPage.getLanguage(req), new HashMap<String, Object>());
88         return false;
89     }
90
91     protected String getCsrfFieldName() {
92         return CSRF_FIELD;
93     }
94
95     @Override
96     public void output(PrintWriter out, Language l, Map<String, Object> vars) {
97         if (action == null) {
98             out.println("<form method='POST'>");
99         } else {
100             out.println("<form method='POST' action='" + action + "'>");
101         }
102         outputContent(out, l, vars);
103         out.print("<input type='hidden' name='" + CSRF_FIELD + "' value='");
104         out.print(getCSRFToken());
105         out.println("'></form>");
106     }
107
108     /**
109      * Outputs the forms contents.
110      * 
111      * @param out
112      *            Stream to the user.
113      * @param l
114      *            {@link Language} to translate text to.
115      * @param vars
116      *            Variables supplied from the outside.
117      */
118     protected abstract void outputContent(PrintWriter out, Language l, Map<String, Object> vars);
119
120     protected String getCSRFToken() {
121         return csrf;
122     }
123
124     /**
125      * Re-fetches a form e.g. when a Post-request is received.
126      * 
127      * @param req
128      *            the request that is directed to the form.
129      * @param target
130      *            the {@link Class} of the expected form.
131      * @return the form where this request is directed to.
132      * @throws CSRFException
133      *             if no CSRF-token is found or the token is wrong.
134      */
135     @SuppressWarnings("unchecked")
136     public static <T extends Form> T getForm(HttpServletRequest req, Class<T> target) throws CSRFException {
137         String csrf = req.getParameter(CSRF_FIELD);
138         if (csrf == null) {
139             throw new CSRFException();
140         }
141         HttpSession hs = req.getSession();
142         if (hs == null) {
143             throw new CSRFException();
144         }
145         Object f = hs.getAttribute("form/" + target.getName() + "/" + csrf);
146         if (f == null) {
147             throw new CSRFException();
148         }
149         if ( !(f instanceof Form)) {
150             throw new CSRFException();
151         }
152         if ( !target.isInstance(f)) {
153             throw new CSRFException();
154         }
155         // Dynamic Cast checked by previous if statement
156         return (T) f;
157     }
158
159     public static class CSRFException extends IOException {
160
161         private static final long serialVersionUID = 59708247477988362L;
162
163     }
164 }