Meteor issue with recaptcha Google : verifyCaptcha is not a function - javascript

I use a package (appshore:recaptcha) to use the Google recaptcha system and I have trouble using it. I have an error that say verifyCaptcha is not a function.
I call my method from client side :
//get the captcha data
var captchaData = $('#g-recaptcha-response').val();
var resultCaptcha = Utils.captchaCheck(captchaData);
And I defined it in a Utils section in server side :
captchaCheck: function (captchaData) {
var ip = "0.0.0.0";
if(Meteor.isServer) {
if(!this.connection.clientAddress)
throw new Meteor.Error(403, "Server Error: You must be connected.");
else
ip = this.connection.clientAddress;
}
var verifyCaptchaResponse = reCAPTCHA.verifyCaptcha(ip, captchaData);
if (!verifyCaptchaResponse.success) {
throw new Meteor.Error('422', 'reCAPTCHA Failed: ' + verifyCaptchaResponse.error);
}
else {
return true;
}
}
But when I submit my form I have the error above mentioned...

Related

NodeJs Assertion failed on HTTP call (Mac)

var client = require('http');
var endpoint = apiEndpoint;
var request = client.get(endpoint, function(responseFromApi) {
var responseString = '';
responseFromApi.setEncoding('utf-8');
responseFromApi.on('data', function(data) {
responseString += data;
});
// To reformat the string response into Json...
responseFromApi.on('end', function() {
var jsonResponse = JSON.parse(responseString);
callback(jsonResponse);
});
});
I am making API calls using the method above, however on random instances my call fails due to the Assertion fail like below. Anyone has any idea how to fix this?
Assertion failed: (handle->type == UV_TCP || handle->type == UV_TTY || handle->type == UV_NAMED_PIPE), function uv___stream_fd, file ../deps/uv/src/unix/stream.c, line 1568.
Environment: Mac, Nodejs
Note: I have tested the same code on an AWS lambda server and never faced this issue. I am guessing this is a Mac only instance. Lord Google informed me that it is a Mac desync issue.
Same is true if trying to get data from a dynamoDB sitting on Amazon server using the code below...
// To get userID.
var userId = getUserIdFromContext(this);
if (!userId) {
callback('userId is not set.');
}
// To get table name.
var table = constants.dynamoDBTableName;
if(!table) {
callback('DynamoDB Table name is not set.');
}
// To set the DocumentClient.
if(!doc) {
doc = new aws.DynamoDB.DocumentClient({apiVersion: '2012-08-10'});
}
// To set the params.
var params = {
Key: {
CustomerId: userId
},
TableName: table,
ConsistentRead: true
};
// To get data from table.
var skillContext = this;
doc.get(params, function(err, data){
if(err) {
console.log('get error: ' + JSON.stringify(err, null, 4));
callback(err);
} else {
if(isEmptyObject(data)) {
callback('The object is empty.');
} else {
var userData = JSON.parse(data.Item['Data']);
extractUserData(skillContext, userData, callback);
}
}
});
}

Get subdomain and query database for results - Meteor

I am pretty new to Meteor now.
I want to:
get the sub-domain of the url
check if a client exists matching the sub-domain
if client exists query the database and get some results (say client settings) from the database.
I am sure that this would be a piece of cake if we use MongoDB, however, we have to move an existing application (built on PHP) that has MySQL backend.
I have found a package numtel:mysql for meteor and I have added it to the project.
Here is the source code written so far:
if(!Session.get('client_details')) {
var hostnameArray = document.location.hostname.split('.');
if(hostnameArray[1] === "localhost" && hostnameArray[2] === "local") {
var subdomain = hostnameArray[0];
}
if(subdomain) {
currentClientDetails = new MysqlSubscription('getClientDetailsFromUrl', subdomain).reactive();
Tracker.autorun(function() {
if(currentClientDetails.ready()) {
if(currentClientDetails.length > 0) {
var clientDetails = currentClientDetails[0];
Session.setPersistent('client_details', clientDetails);
var clientId = clientDetails.id;
if(!Session.get('client_settings')) {
clientSettings = new MysqlSubscription('clientSettings', clientId).reactive();
Tracker.autorun(function() {
if(clientSettings.ready()) {
if(clientSettings.length > 0)
Session.setPersistent('client_settings', clientSettings[0]);
else
Session.setPersistent('client_settings', {});
}
});
}
}
}
});
}
}
the session.setPersistent comes from u2622:persistent-session to store Sessions on client side
and here is the publish statement:
Meteor.publish("getClientDetailsFromUrl", function(url) {
if(typeof url === undefined) {
return;
}
var clientDetails = Meteor.readLiveDb.select(
'select * from clients where client_url = "'+ url +'"',
[{table: 'clients'}]
);
return clientDetails;
});
Meteor.publish("clientSettings", function(clientId) {
if(typeof clientId === undefined) {
throw new error('ClientId cannot be null');
return;
}
var clientSettings = Meteor.readLiveDb.select(
'select * from client_settings where client_id = ' + clientId, [{
table: 'client_settings'
}]);
return clientSettings;
});
and the database is initiated as
Meteor.readLiveDb = new LiveMysql(<MySQL Settings like host, user, passwords, etc>);
Problem
I get client_details into the session successfully, however, cannot get client_settings into the session. End up with an error:
Exception from Tracker recompute function:
Error: Subscription failed!
at Array.MysqlSubscription (MysqlSubscription.js:40)
at app.js?6d4a99f53112f9f7d8eb52934c5886a2b7693aae:28
at Tracker.Computation._compute (tracker.js:294)
at Tracker.Computation._recompute (tracker.js:313)
at Object.Tracker._runFlush (tracker.js:452)
at onGlobalMessage (setimmediate.js:102)
I know the code is messy and could get a lot better, please suggestions welcome

How to handle invalid URL / IP's in websockets?

I'm using HTML / Javascript web sockets to communicate with a python server program. Now I have the option to change the server's IP via clean UI and I have a .onerror function that handles with connection errors, however this doesn't handle initial errors. What I mean by this is if I were to enter a completely invalid address, it wont even attempt to connect with it (which is fine) and spit out and error like: [Error] WebSocket network error: The operation couldn’t be completed. (kCFErrorDomainCFNetwork error 2.). How can I handle this error so I can say, popup a message for example?
Here's a brief overview of my JS script.
function updateDevice(id, ipUI){
if ("WebSocket" in window){
var ws = new WebSocket(serverIP);
// Here is where I need to handle the bad address right?
ws.onopen = function(){
ws.send(id);
};
ws.onmessage = function (evt){
var received_msg = evt.data;
};
// This function ws.onerror doesnt handle bad addresses.
ws.onerror = function(){
document.getElementById("error_msg").style.display='block';
};
}else{
alert("This site doesnt support your browser...");
};
};
You could wrap the new WebSocket in a try/catch:
try {
new WebSocket(serverIP);
} catch (e) {
if (e instanceof DOMException) {
alert('Invalid address!');
} else {
throw e;
}
}

WebSockets using Fleck. WSS

I try to create simple chat application using secure layer WSS. Without wss it works. Here is my code:
FleckLog.Level = LogLevel.Info;
var allsockets = new List<IWebSocketConnection>();
var server = new WebSocketServer("wss://localhost:8181");
server.Certificate = new X509Certificate2(#"C:\Users\user\Desktop\sharpchat-master\server\Sharpchat\Certificate.pfx", "123");
server.Start(socket =>
{
socket.OnOpen = () =>
{ //See socket.ConnectionInfo.* for additional informations
Console.WriteLine(String.Empty);
Console.WriteLine("[NEW CLIENT CONNECTION]======================");
Console.WriteLine("GUID: " + socket.ConnectionInfo.Id);
Console.WriteLine("IP: " + socket.ConnectionInfo.ClientIpAddress);
Console.WriteLine("Port: " + socket.ConnectionInfo.ClientPort);
Console.WriteLine("=============================================");
Console.WriteLine(String.Empty);
allsockets.Add(socket);
};
socket.OnClose = () =>
{
Console.WriteLine(String.Empty);
Console.WriteLine("[DISCONNECTED CLIENT]=======================");
Console.WriteLine("GUID: " + socket.ConnectionInfo.Id);
Console.WriteLine("IP: " + socket.ConnectionInfo.ClientIpAddress);
Console.WriteLine("Port: " + socket.ConnectionInfo.ClientPort);
Console.WriteLine("=============================================");
Console.WriteLine(String.Empty);
allsockets.Remove(socket);
};
socket.OnMessage = (message) =>
{
//TODO: Json.Net Deserialize
Console.WriteLine("[JSON MESSAGE] " + message);
allsockets.ToList().ForEach(s => s.Send(message));
};
});
var input = Console.ReadLine();
while (input != "exit")
{
foreach (var socket in allsockets.ToList())
{
socket.Send(input);
}
input = Console.ReadLine();
}
When client connects to server there is an exception:
[Warn] Failed to Authenticate System.AggregateEx
ception: One or more errors occurred. ---> System.IO.IOException: The handshake
failed due to an unexpected packet format.
at System.Net.Security.SslState.InternalEndProcessAuthentication(LazyAsyncRes
ult lazyResult)
at System.Net.Security.SslState.EndProcessAuthentication(IAsyncResult result)
at System.Net.Security.SslStream.EndAuthenticateAsServer(IAsyncResult asyncRe
sult)
at System.Threading.Tasks.TaskFactory`1.FromAsyncCoreLogic(IAsyncResult iar,
Func`2 endFunction, Action`1 endAction, Task`1 promise, Boolean requiresSynchron
ization)
--- End of inner exception stack trace ---
---> (Inner Exception #0) System.IO.IOException: The handshake failed due to an
unexpected packet format.
at System.Net.Security.SslState.InternalEndProcessAuthentication(LazyAsyncRes
ult lazyResult)
at System.Net.Security.SslState.EndProcessAuthentication(IAsyncResult result)
at System.Net.Security.SslStream.EndAuthenticateAsServer(IAsyncResult asyncRe
sult)
at System.Threading.Tasks.TaskFactory`1.FromAsyncCoreLogic(IAsyncResult iar,
Func`2 endFunction, Action`1 endAction, Task`1 promise, Boolean requiresSynchron
ization)<---
Here is client code in JavaScript:
// Websocket Endpoint url
var URL = 'wss://localhost:8181';
var chatClient = null;
function connect () {
chatClient = new WebSocket(URL);
chatClient.onmessage = function (event) {
var messagesArea = document.getElementById("messages");
var jsonObj = JSON.parse(event.data);
var message = "<"+ jsonObj.user + "> " + jsonObj.message + "\r\n";
messagesArea.value = messagesArea.value + message;
messagesArea.scrollTop = messagesArea.scrollHeight;
};
}
function disconnect () {
chatClient.close();
}
function sendMessage() {
var user = document.getElementById("userName").value.trim();
if (user === "")
alert ("Please enter your name!");
var inputElement = document.getElementById("messageInput");
var message = inputElement.value.trim();
if (message !== "") {
var jsonObj = {"user" : user, "message" : message};
chatClient.send(JSON.stringify(jsonObj));
inputElement.value = "";
}
inputElement.focus();
}
Can anyone help me fix this problem?
Thank you very much!
Use full domain name in URL i.e. var URL = 'wss://localhost.company.com:8181';
Allow invalid certificates for resources loaded from localhost # Enable.
More Details are here

Meteor.http.get request -> Error: Hostname/IP doesn't match certificate's altnames

I'm trying to use meteor.http module and I'm getting the following error on the server side.
"Error: Hostname/IP doesn't match certificate's altnames" since I'm new in Meteor and in Node.js and its javaScript debugging is hard (btw how can I debug server side scripts ? client side it's easy), I'm using MAC OS X 10.9 not sure if it's relevent...
Thanks
Ronen
client side code:
'click #buildButton' : function () {
console.log("Jenkins job request");
$('#buildButton').attr('disabled','true').val('loading...');
var userName = "Ronen";
Meteor.call('jenkinsServiceBuild', function(err, respJson) {
if(err) {
window.alert("Error: " + err.reason);
console.log("error occured on receiving data on server. ", err );
} else {
window.alert("Success: ");
console.log("respJson: ", respJson);
//window.alert(respJson.length + ' tweets received.');
Session.set("recentTweets",respJson);
}
$('#buildButton').removeAttr('disabled').val('build');
});
}
Server Side Code:
Meteor.methods({jenkinsServiceBuild: function(userName) {
var url = "https://www.ynet.co.il";
//synchronous GET
var result = Meteor.http.get(url, {timeout:30000});
if(result.statusCode==200) {
var respJson = JSON.parse(result.content);
console.log("response received.");
return respJson;
} else {
console.log("Response issue: ", result.statusCode);
var errorJson = JSON.parse(result.content);
throw new Meteor.Error(result.statusCode, errorJson.error);
}
}
});
The site 'https://www.ynet.co.il' has an incorrectly installed SSL certficate for that domain. It's using akamai's certificate.
If you know and trust the site and its for nothing too secure just remove the s in https
var url = "http://www.ynet.co.il";
Also I'm not sure the code will work, looking at the site it serves html content but this line:
var respJson = JSON.parse(result.content);
Suggests it serves JSON content. If it does server json content use this instead:
var respJson = result.data;

Categories

Resources