How to verify google captcha - node.js

Client side code
<script src='https://www.google.com/recaptcha/api.js'></script>
<script>
var verified = function() {
document.getElementById("loginform").submit();
};
</script>
<form action="www.example.com/" method="POST" id="loginform" onsubmit=" return validation()">
<input id="email" maxlength="80" name="email" size="20" type="text" placeholder="Enter Your Email" style="margin-bottom: 30px;"/><br>
<div id="captchadiv">
<div class="g-recaptcha" data-sitekey="site key" data-callback="verified"></div>
</div>
<button type="submit" value="Submit" id="reg_submit" style=" display:block;margin: 0 auto;"><img src="/favicon.png" style="width: 20px;float: left;" />Sign in</button>
</form>
Server Side code
reCAPTCHA=require('recaptcha2')
recaptcha=new reCAPTCHA({
siteKey:'site key',
secretKey:'secretKey'
})
I am working on node js.I am using google recaptcha2 and when i see lots of example and all example verify recaptcha using form submit. They define in action but my action method use in other navigation so i can use get, post request. I don't have any idea for how to use get, post request for recaptcha.I want to verify recaptcha on server side using get,post request.
I need help on back-end verification work.
Thanks advance!

Please try this code
Client side code not more secure so please use both side code
Client side
function validateform(){
var captcha_response = grecaptcha.getResponse();
if(captcha_response.length == 0 || grecaptcha != undefined )
{
// Captcha is not Passed
return ' Please verify you are not a robot.';
}else{
$.get('/captchaTest',{'response':captcha_response},function(response){
if(response == undefined && response.responseCode == undefined && response.responseDesc == undefined && response.responseCode !== 0 && response.responseDesc !== 'Sucess' ){
return ' You are a robot.';
}
grecaptcha.reset();
});
}
}
Server side
app.get('/captchaTest',function(req,res){
var requestQuery = req.query;
if( requestQuery != undefined && requestQuery != '' && requestQuery != null && requestQuery.response != undefined && requestQuery.response != '' && requestQuery.response != null ){
var response = requestQuery.response;
var verificationUrl = "https://www.google.com/recaptcha/api/siteverify?secret="+ secret_key +"&response=" +response;
// Hitting GET request to the URL, Google will respond with success or error scenario.
request(verificationUrl,function(error,response,body) {
body = JSON.parse(body);
// Success will be true or false depending upon captcha validation.
if(body.success !== undefined && !body.success) {
res.send({"responseCode" : 1,"responseDesc" : "Failed captcha verification"});
}else{
res.send({"responseCode" : 0,"responseDesc" : "Sucess"});
}
});
}else{
res.send({"responseCode" : 1,"responseDesc" : "Failed captcha verification"});
}
});

Related

Angular 10: service undefined error when doing click function from other component

I am facing a service undefined error. I am doing a click function from a shared component and after that, I called a service but that service showing undefined in the component.
I added the service in the app module and in providers also. Still, I am facing the issue. Anyone help me to sort that issue.
Method:
approveReject(data,action,type){
console.log(data, action, type);
let endpoint;
let reqData;
if( type.toLowerCase() == 'advertiser'){
if(action.toLowerCase() == 'approve'){
endpoint = 'advActivate';
}else{
endpoint = 'advReject';
}
reqData = {
guid:data.guid,
userid:data.userid,
id:data.id,
}
}else if(type.toLowerCase() == 'publisher'){
if(action.toLowerCase() == 'approve'){
endpoint = 'pubActivate';
}else{
endpoint = 'pubReject';
}
}
console.log('**********');
console.log(this.apiservice);
this.apiservice.fullLoader(true);
this.apiservice.post(endpoint, reqData).subscribe((res) => {
this.apiservice.fullLoader(false)
console.log("res->",res)
if(res.msg.toLowerCase() == 'ok' && res.error_code == 0){
this.apiservice.alertMessage('success', type.toLowerCase()+''+action.toLowerCase()+'ed Successfully');
}
},err => {
this.apiservice.fullLoader(false)
this.apiservice.alertMessage('danger', 'Failed to '+action.toLowerCase()+''+type.toLowerCase()+'Please Try again');
})
}
Click component html in shared component:
<ng-template pTemplate="body" let-data let-columns="columns">
<tr>
<td *ngFor="let col of columns">
<ng-container *ngIf="col.field != 'actions';else alink">
{{data[col.field]}}
</ng-container>
<ng-container *ngIf="col.field == 'actions'" #alink>
<a *ngFor="let linkData of data[col.field]" href="javascript:;" title="{{linkData.name}}" [appHasRole]="linkData.hasRole" (click)="linkData.action(data,linkData.name,linkData.type)"><i class="{{linkData.icon}}"></i>
</a>
</ng-container>
</td>
</tr>
</ng-template>
Error:
TypeError: Cannot read property 'fullLoader' of undefined

validating bootstrap datepicker using Qunit

I have a bootstrap calendar on my page that lets the user pick a date. I have a start time and endtime. I would like to test to do the following.
If the user leaves the date selector empty, the test will fail with a message like cannot leave fields empty.
If the user enters an endtime that is less than the startime the test will fail and throw a message like Cannot have endtime less than starttime.
I will paste the code that works with the datepicker. I am using Qunit for testing purposes and Bootstrap 4.
button.js
// Runs date picker plugin
$('input.date').datepicker();
// Gets data
var data;
fetch('/reportSaver', {
// data: dates,
method: 'POST'
}).then(function (response) {
return response.json();
}).then(function (json) {
data = json;
});
// Form submit
$('form').on('submit', function (event) {
event.preventDefault();
var dates = {
startdate: new Date($('.startdate').val()),
enddate: new Date($('.enddate').val())
};
// Minimum validation for dates
if ((dates.startdate && dates.startdate > dates.enddate) ||
(dates.enddate && dates.enddate < dates.startdate)) {
return alert('Use valid dates!');
}
// Filter rows
var rows = data.filter(function (register) {
var date = new Date(register.receivedDateTime);
return (
(!dates.startdate || date > dates.startdate) &&
(!dates.enddate || date < dates.enddate)
);
// Convert to HTML
}).map(function (row) {
return `
<tr>
<td> </td>
<td>${row.subject || '-'}</td>
<td>${row.receivedDateTime || '-'}</td>
<td>${row.isRead || '-'}</td>
<td>${row.sendDateTime || '-'}</td>
</tr>
`;
});
// Show content
$('table tbody').html(rows.join(''));
});
// Clear click
$('.clear-table').on('click', function () {
// Clears table
$('table tbody').html('<tr><td colspan="5">Make a search</td></tr>');
// Clears inputs
$('input').val('');
});
form.html
{{!-- Post form for Date Picker --}}
<form id="post_form" method="GET" action="/routes/reportSaver.js">
<div class="date-picker">
<h3>Date</h3>
<input placeholder="Initial date" type="text" class="date startdate"> -
<input placeholder="End date" type="text" class="date enddate">
</div>
<hr>
{{!-- Button to save the Report --}}
<button id="bt1" type="submit" class="btn btn-danger">Click to Get Reports</button>
<button id="bt2" type="submit" class="btn btn-danger clear-table">Clear</button>
</form>
Qunit Test Example
QUnit.test("Datepicker Test", function (assert) {
var datepicker = $("#startDate");
var event = $.Event("onSelect");
datepicker.on("onSelect"),
function () {
alert("Test");
};
// Trigger the key event
datepicker.trigger(event);
});

Reactjs error, objects are not valid as react child?

I'm using reactjs in front end and nodejs as backend. I'm calling my backend (localhost:3001/api/tunes) through this code :
componentDidMount(){
fetch("/api/itunes")
.then((results)=>{
this.setState({queryResult:results});
})
}
This code is supposed to return a single string value which I'm assigning to local state variable queryResult. I can't understand why the code gives error - objects are not valid react child.
My render function :
render(){
return(
<div>
<form class="form-inline my-2 my-lg-0">
<input class="form-control mr-sm-2" type="search" placeholder="Search"
value={this.state.queryValue} onChange={this.handleQueryChange} />
<button class="btn btn-outline-success my-2 my-sm-0" type="submit"
onClick={this.submitQuery}></button>
</form>
<div>{this.state.queryResult}</div>
</div>
);
}
this is what I'm getting from my server:
router.get('/api/itunes',(req,res,next)=>{
request('https://itunes.apple.com/search?term=jack+johnson',
function (error, response, body) {
if (!error && response.statusCode == 200) {
// console.log(body) // Print the google web page.
var result =JSON.parse(body);
res.send(result.results[0].artistName);
}
});
});
You are trying to render whole object which is this.state.queryResult .
React cannot render objects.You must convert this to String or have to extract each value from the object.
You can easily check this using {console.log(this.state.queryResult)}

Data validation in server by socket.io and node.js then POST a from

I have a form like this:
<form method='post' action='next' onsubmit="return validateMyForm();" >
<input type="text" id="data" />
<input type="submit" />
<p id="result"></p>
and this code for interact with node.js:
socket = io.connect();
function vlidateMyForm(){
var data = $('data').val();
socket.emit('login',{data: data}); // check dataBase in server
return false;
}
socket.on('responseLogin',function(result){
if(result){ // if data is valid
// submit form
}
else{ // data invalid
$('#result').html('field is not valid')
}
});
I want to submit my form, when the result is true. What should I do to solve this problem?
Change socket.on('responseLogin',function(result){... to socket.on('login',function(result){... should fix your problem
You can use Jquery submit to submit the form :
$("form#formID").submit();
Your form must have action attribute like action='url_to_post_to' for this.
Or if you like to use AJAX so that you can process the data, you can do :
$.ajax({
type: "POST",
url: 'url_to_post_to',
data: $("#formID").serialize(),
success: function(data)
{
alert(data);
}
});

Sometimes tabs.getSelected callback doesn't run

I've written a Google Chrome extension (https://chrome.google.com/webstore/detail/fhmcfamnddgoloojehbeokifhaiiebfm), and I'm noticing that the extension works on my Linux desktop, but not my Linux laptop (both running the Chromium 13.0.782.107~r94237-1 in Debian unstable)
It seems that the callback I'm passing to chrome.tabs.getSelected doesn't run on my laptop, except when I have this popup page open in the debugger. (But it works perfectly on my desktop) Any idea what's going on?
Here's the code in question:
<html>
<head>
<script type="text/javascript">
function goTo(url){
if (url.search("://") == -1 &&
url.search("#") != -1 &&
url.search("mailto:") == -1 ) url = "mailto:"+url;
else if (url.search("://") == -1 ) url = "http://" + url;
url = url.replace(/\s/g,"");
console.log(url);
chrome.tabs.getSelected(null,function(tab){
chrome.tabs.update(tab.id,{"url":url});
});
window.close();
}
function pasteHandler(e) {
var t = e.target.type;
if (t == "textarea" || t == "text" || t == "password"
|| e.target.isContentEditable) {
return;
}
var url = e.clipboardData.getData("text/plain").replace(/^\s+|\s+$/g, '');
goTo(url)
}
function textBoxEnterPressed(e){
if(e.keyCode == 13){
goTo(document.getElementById('edit').value);
return false;
}
return true;
}
</script>
</head>
<body onpaste="pasteHandler(event)">
<table border="0" cellpadding="0" cellspacing="0" style="float:left">
<tr><td>
Paste in the text box to edit the URL first,
or paste outside the box to go straight there.
</td></tr>
<tr><td>
<input type="text" name="edit" id="edit" size="100"
onkeypress="return textBoxEnterPressed(event)"/>
</td></tr>
</table>
</body>
</html>
I think you are closing window before callback finishes running. Try:
function goTo(url){
...
chrome.tabs.getSelected(null,function(tab){
chrome.tabs.update(tab.id,{"url":url});
window.close();
});
}

Resources