Mercurial Hosting > nabble
comparison src/nabble/view/lib/Recaptcha.java @ 0:7ecd1a4ef557
add content
author | Franklin Schmidt <fschmidt@gmail.com> |
---|---|
date | Thu, 21 Mar 2019 19:15:52 -0600 |
parents | |
children |
comparison
equal
deleted
inserted
replaced
-1:000000000000 | 0:7ecd1a4ef557 |
---|---|
1 package nabble.view.lib; | |
2 | |
3 import java.io.IOException; | |
4 import java.net.InetAddress; | |
5 import java.net.UnknownHostException; | |
6 import java.util.Map; | |
7 import javax.servlet.http.HttpServletRequest; | |
8 import luan.lib.json.JsonParser; | |
9 import luan.lib.parser.ParseException; | |
10 import fschmidt.util.java.IoUtils; | |
11 import nabble.model.ModelException; | |
12 import nabble.view.lib.Jtp; | |
13 | |
14 | |
15 public final class Recaptcha { | |
16 | |
17 public static final String JS = "<script src='https://www.google.com/recaptcha/api.js'></script>"; | |
18 | |
19 public static final String DIV = "<div class='g-recaptcha' data-sitekey='6Lf12z4UAAAAAKFG8EczAb6BjVvaFM2rqHswrCP7'></div>"; | |
20 | |
21 private static final String SECRET = "6Lf12z4UAAAAAChAhLaE4-pxoY7z9LAWkSJnif4s"; | |
22 private static final String URL = "https://www.google.com/recaptcha/api/siteverify"; | |
23 private static final String PARAMS = "secret="+SECRET+"&response="; | |
24 | |
25 private static String getDomainIP(String domain) | |
26 throws UnknownHostException | |
27 { | |
28 int i = domain.indexOf(":"); | |
29 if( i > 0 ) | |
30 domain = domain.substring(0,i); | |
31 return InetAddress.getByName(domain).getHostAddress(); | |
32 } | |
33 | |
34 public static void check(HttpServletRequest request) | |
35 throws ModelException.InvalidRecaptcha, IOException | |
36 { | |
37 String response = request.getParameter("g-recaptcha-response"); | |
38 String json = IoUtils.post( URL, PARAMS+response ); | |
39 //System.out.println(json); | |
40 Map map; | |
41 try { | |
42 map = (Map)JsonParser.parse(json); | |
43 } catch(ParseException e) { | |
44 throw new RuntimeException(e); | |
45 } | |
46 boolean success = (Boolean)map.get("success"); | |
47 if( !success ) | |
48 throw new ModelException.InvalidRecaptcha(); | |
49 String hostname = (String)map.get("hostname"); | |
50 String hostIP = getDomainIP(hostname); | |
51 String nabbleIP = getDomainIP(Jtp.getDefaultHost()); | |
52 if( !nabbleIP.equals(hostIP) ) | |
53 throw new RuntimeException("invalid host"); | |
54 } | |
55 | |
56 private Recaptcha() {} // never | |
57 } |