X-Git-Url: https://code.wpia.club/?a=blobdiff_plain;f=src%2Forg%2Fcacert%2Fgigi%2Foutput%2Ftemplate%2FForm.java;fp=src%2Forg%2Fcacert%2Fgigi%2Foutput%2Ftemplate%2FForm.java;h=f469c21c68bf53080d4f40863cb1e67a85dedc36;hb=cd14b85c60f736a643842b421b11f41d8fca86c7;hp=0000000000000000000000000000000000000000;hpb=1db93167c35304e1d56e99dae6aa1cfa83842a2e;p=gigi.git diff --git a/src/org/cacert/gigi/output/template/Form.java b/src/org/cacert/gigi/output/template/Form.java new file mode 100644 index 00000000..f469c21c --- /dev/null +++ b/src/org/cacert/gigi/output/template/Form.java @@ -0,0 +1,103 @@ +package org.cacert.gigi.output.template; + +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; + +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 { + + } +}