X-Git-Url: https://code.wpia.club/?a=blobdiff_plain;f=src%2Forg%2Fcacert%2Fgigi%2Foutput%2FForm.java;h=7cad69e7343b422d34369490452e4dc7f7ed2615;hb=76e3ad5851967bea57005ec9858625d4a7071d7c;hp=1aa356ab7caeb8816ea5abb6062858975db497ed;hpb=d463b3c42abe2f8edda3951580cf339dca6bb58e;p=gigi.git diff --git a/src/org/cacert/gigi/output/Form.java b/src/org/cacert/gigi/output/Form.java index 1aa356ab..7cad69e7 100644 --- a/src/org/cacert/gigi/output/Form.java +++ b/src/org/cacert/gigi/output/Form.java @@ -1,10 +1,103 @@ package org.cacert.gigi.output; +import java.io.IOException; import java.io.PrintWriter; +import java.util.Map; +import javax.servlet.ServletRequest; import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpSession; -public interface Form extends Outputable { - public boolean submit(PrintWriter out, HttpServletRequest req); +import org.cacert.gigi.GigiApiException; +import org.cacert.gigi.localisation.Language; +import org.cacert.gigi.pages.Page; +import org.cacert.gigi.util.RandomToken; +public abstract class Form implements Outputable { + + public static final String CSRF_FIELD = "csrf"; + + private String csrf; + + public Form(HttpServletRequest hsr) { + csrf = RandomToken.generateToken(32); + HttpSession hs = hsr.getSession(); + hs.setAttribute("form/" + getClass().getName() + "/" + csrf, this); + + } + + public abstract boolean submit(PrintWriter out, HttpServletRequest req) throws GigiApiException; + + protected String getCsrfFieldName() { + return CSRF_FIELD; + } + + @Override + public void output(PrintWriter out, Language l, Map vars) { + out.println("
"); + failed = false; + outputContent(out, l, vars); + out.print("
"); + } + + protected abstract void outputContent(PrintWriter out, Language l, Map vars); + + boolean failed; + + protected void outputError(PrintWriter out, ServletRequest req, String text, Object... contents) { + if ( !failed) { + failed = true; + out.println("
"); + } + out.print("
"); + if (contents.length == 0) { + out.print(Page.translate(req, text)); + } else { + out.print(String.format(Page.translate(req, text), contents)); + } + out.println("
"); + } + + protected void outputErrorPlain(PrintWriter out, String text) { + if ( !failed) { + failed = true; + out.println("
"); + } + out.print("
"); + out.print(text); + out.println("
"); + } + + public boolean isFailed(PrintWriter out) { + if (failed) { + out.println("
"); + } + return failed; + } + + protected String getCSRFToken() { + return csrf; + } + + public static T getForm(HttpServletRequest req, Class target) throws CSRFException { + String csrf = req.getParameter(CSRF_FIELD); + if (csrf == null) { + throw new CSRFException(); + } + HttpSession hs = req.getSession(); + if (hs == null) { + throw new CSRFException(); + } + Form f = (Form) hs.getAttribute("form/" + target.getName() + "/" + csrf); + if (f == null) { + throw new CSRFException(); + } + return (T) f; + } + + public static class CSRFException extends IOException { + + } }