1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package org.apache.myfaces.tobago.webapp;
21
22 import org.apache.commons.codec.binary.Base64;
23 import org.apache.myfaces.tobago.renderkit.html.HtmlAttributes;
24 import org.apache.myfaces.tobago.renderkit.html.HtmlElements;
25 import org.apache.myfaces.tobago.renderkit.html.HtmlInputTypes;
26
27 import javax.faces.context.FacesContext;
28 import javax.servlet.http.HttpSession;
29 import java.io.IOException;
30 import java.io.Serializable;
31 import java.security.SecureRandom;
32 import java.util.Map;
33
34 public class Secret implements Serializable {
35
36 private static final long serialVersionUID = 1L;
37
38 private static final String KEY = Secret.class.getName();
39
40 private static final SecureRandom RANDOM = new SecureRandom();
41
42 private static final int SECRET_LENGTH = 16;
43
44 private static final boolean COMMONS_CODEC_AVAILABLE = commonsCodecAvailable();
45
46 private static boolean commonsCodecAvailable() {
47 try {
48 Base64.encodeBase64URLSafeString(new byte[0]);
49 return true;
50 } catch (Error e) {
51 return false;
52 }
53 }
54
55 private String secret;
56
57 private Secret() {
58 byte[] bytes = new byte[SECRET_LENGTH];
59 RANDOM.nextBytes(bytes);
60 secret = COMMONS_CODEC_AVAILABLE ? encodeBase64(bytes) : encodeHex(bytes);
61 }
62
63 private String encodeBase64(byte[] bytes) {
64 return Base64.encodeBase64URLSafeString(bytes);
65 }
66
67 private String encodeHex(byte[] bytes) {
68 StringBuilder builder = new StringBuilder(SECRET_LENGTH * 2);
69 for (byte b : bytes) {
70 builder.append(String.format("%02x", b));
71 }
72 return builder.toString();
73 }
74
75
76
77
78
79 public static boolean check(FacesContext facesContext) {
80 Map requestParameterMap = facesContext.getExternalContext().getRequestParameterMap();
81 String fromRequest = (String) requestParameterMap.get(Secret.KEY);
82 Map sessionMap = facesContext.getExternalContext().getSessionMap();
83 Secret secret = (Secret) sessionMap.get(Secret.KEY);
84 return secret != null && secret.secret.equals(fromRequest);
85 }
86
87
88
89
90 public static void encode(FacesContext facesContext, TobagoResponseWriter writer) throws IOException {
91 writer.startElement(HtmlElements.INPUT, null);
92 writer.writeAttribute(HtmlAttributes.TYPE, HtmlInputTypes.HIDDEN, false);
93 writer.writeAttribute(HtmlAttributes.NAME, Secret.KEY, false);
94 writer.writeAttribute(HtmlAttributes.ID, Secret.KEY, false);
95 Map sessionMap = facesContext.getExternalContext().getSessionMap();
96 Secret secret = (Secret) sessionMap.get(Secret.class.getName());
97 writer.writeAttribute(HtmlAttributes.VALUE, secret.secret, false);
98 writer.endElement(HtmlElements.INPUT);
99 }
100
101
102
103
104
105 public static void create(HttpSession session) {
106 session.setAttribute(Secret.KEY, new Secret());
107 }
108 }