Mercurial Hosting > nabble
diff 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 |
line wrap: on
line diff
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/nabble/view/lib/Recaptcha.java Thu Mar 21 19:15:52 2019 -0600 @@ -0,0 +1,57 @@ +package nabble.view.lib; + +import java.io.IOException; +import java.net.InetAddress; +import java.net.UnknownHostException; +import java.util.Map; +import javax.servlet.http.HttpServletRequest; +import luan.lib.json.JsonParser; +import luan.lib.parser.ParseException; +import fschmidt.util.java.IoUtils; +import nabble.model.ModelException; +import nabble.view.lib.Jtp; + + +public final class Recaptcha { + + public static final String JS = "<script src='https://www.google.com/recaptcha/api.js'></script>"; + + public static final String DIV = "<div class='g-recaptcha' data-sitekey='6Lf12z4UAAAAAKFG8EczAb6BjVvaFM2rqHswrCP7'></div>"; + + private static final String SECRET = "6Lf12z4UAAAAAChAhLaE4-pxoY7z9LAWkSJnif4s"; + private static final String URL = "https://www.google.com/recaptcha/api/siteverify"; + private static final String PARAMS = "secret="+SECRET+"&response="; + + private static String getDomainIP(String domain) + throws UnknownHostException + { + int i = domain.indexOf(":"); + if( i > 0 ) + domain = domain.substring(0,i); + return InetAddress.getByName(domain).getHostAddress(); + } + + public static void check(HttpServletRequest request) + throws ModelException.InvalidRecaptcha, IOException + { + String response = request.getParameter("g-recaptcha-response"); + String json = IoUtils.post( URL, PARAMS+response ); +//System.out.println(json); + Map map; + try { + map = (Map)JsonParser.parse(json); + } catch(ParseException e) { + throw new RuntimeException(e); + } + boolean success = (Boolean)map.get("success"); + if( !success ) + throw new ModelException.InvalidRecaptcha(); + String hostname = (String)map.get("hostname"); + String hostIP = getDomainIP(hostname); + String nabbleIP = getDomainIP(Jtp.getDefaultHost()); + if( !nabbleIP.equals(hostIP) ) + throw new RuntimeException("invalid host"); + } + + private Recaptcha() {} // never +}