Skip to content

Instantly share code, notes, and snippets.

@aflansburg
Last active September 15, 2020 13:26
Show Gist options
  • Save aflansburg/086761fde55b4fc5f16efd01abd20618 to your computer and use it in GitHub Desktop.
Save aflansburg/086761fde55b4fc5f16efd01abd20618 to your computer and use it in GitHub Desktop.
Creating a China friendly captcha w/ Jquery & Rails view
function getCnNumber(x){
if (x > 10 && x <= 20){
const ch = '零一二三四五六七八九十'.split('').map((c, i) => x === i && c).find(s => s);
return '十' + ch;
}
else
return '零一二三四五六七八九十'.split('').map((c, i) => x === i && c).find(s => s);
}
function solveHuman(ans){
const s = '<input type="submit" value="Submit Registration" class="btn requisLime fs-24" style="height:60px;width:300px;"/>';
const humanSolution = $('#human-solution').val();
const solution = parseInt(ans);
const cnSolution = getCnNumber(ans);
if (parseInt(humanSolution) === solution || humanSolution === cnSolution){
$('#q-block').remove();
$("#prob-canvas").remove();
$("#asimov-gate").html(s);
}
}
function asimovGate(){
$('[data-js-prove-humanity]').click(function(event){
$("#prove-it").hide();
$("#prob-canvas").show();
const data = $(this).attr('button-func');
$('#prompt').remove();
eval(data);
$('#solve-button').click(function(){
const data = $(this).attr('button-func');
eval(data);
});
const a = Math.floor(Math.random() * Math.floor(10));
const b = Math.floor(Math.random() * Math.floor(10));
// chinese simplified numbers
const c = getCnNumber(a);
const d = getCnNumber(b);
const answer = `${a + b}`;
const verify = `<div id="q-block"><div id="human-question"></div><input id="human-solution"></input><br/><button type="button" class="btn requisLime" style="margin-top:12px;padding:0 15px"id="solve-button" onclick="solveHuman(${answer})">Solve - 具求解此方程</button></div>`
let canvas = document.getElementById('prob-canvas');
let canvasText = canvas.getContext("2d");
const textString = `${a} + ${b}\n${c} 加 ${d}`;
let lines = textString.split('\n');
canvasText.font = "36px san-serif";
for (let i = 0; i < lines.length; i++)
canvasText.fillText(lines[i], 50, 50 + (i*31) );
$('#asimov-gate').append(verify);
$('#prove-it').remove();
event.preventDefault;
})
}
<%= form_with model: @user, local: true do |f|%>
<%# other form elements here %>
<canvas id="prob-canvas" width="200" height="100" style="border:1px solid #d3d3d3;display:none;">
Your browser does not support the canvas element.
</canvas>
<div class="actions py-4" id="asimov-gate"/>
<% end %>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment