NodeJS: Callback is not a function - Email verification - android

I'm trying to implement a user registration system, on android with node as my backend server.
I'm using Node 4.4.5, on localhost, and using the package "email-verification" - https://www.npmjs.com/package/email-verification
So on request from android, a confirmation email with a verification link is sent, which is working fine.
When the link is clicked, a GET request is made, which confirms the user, adds it to the MongoDB database, and a JSON response is sent.
An email is sent to the user that the account is confirmed.
After sending the confirmation email, the server crashes.
Here's my code--
router.get('/email-verification/:URL', function(req, res, next){
var url = req.params.URL;
console.log('email-verify-start');
nev.confirmTempUser(url, function(err, user) {
console.log('error is :' + err);
if (user) {
nev.sendConfirmationEmail(user.email, function(err, info) {
if (err) {
console.log('sending_conf_email_failed');
return res.json({'email': 'sending_conf_email_failed'});
}
console.log('user_confirmed');
res.json({
'email': 'user_confirmed'
});
console.log('Done, and confirmed');
});
} else {
console.log('conf_temp_ser_failed');
return res.json({'email': 'conf_temp_ser_failed'});
}
});
});
And here's my log--
error is :null
user_confirmed
Done, and confirmed
GET /register/email-verification/SfC9VlnUv91RkFBHDURIbHodnYme0RdfbTYBj0I4oXyywrpW 200 5177.724 ms - 26
h:\myapp\coep_updates\node_modules\email-verification\node_modules\nodemailer\node_modules\nodemailer-smtp-transport\src\smtp-transport.js:136
return callback(null, info);
^
TypeError: callback is not a function
at h:\myapp\coep_updates\node_modules\email-verification\node_modules\nodemailer\node_modules\nodemailer-smtp-transport\src\smtp-transport.js:136:20
at h:\myapp\coep_updates\node_modules\email-verification\node_modules\nodemailer\node_modules\nodemailer-smtp-transport\node_modules\smtp-connection\src\smtp-connection.js:279:20
at SMTPConnection._actionStream (h:\myapp\coep_updates\node_modules\email-verification\node_modules\nodemailer\node_modules\nodemailer-smtp-transport\node_modules\smtp-connection\src\smtp-connection.js:966:16)
at SMTPConnection.<anonymous> (h:\myapp\coep_updates\node_modules\email-verification\node_modules\nodemailer\node_modules\nodemailer-smtp-transport\node_modules\smtp-connection\src\smtp-connection.js:594:14)
at SMTPConnection._processResponse (h:\myapp\coep_updates\node_modules\email-verification\node_modules\nodemailer\node_modules\nodemailer-smtp-transport\node_modules\smtp-connection\src\smtp-connection.js:516:16)
at SMTPConnection._onData (h:\myapp\coep_updates\node_modules\email-verification\node_modules\nodemailer\node_modules\nodemailer-smtp-transport\node_modules\smtp-connection\src\smtp-connection.js:353:10)
at emitOne (events.js:77:13)
at TLSSocket.emit (events.js:169:7)
at readableAddChunk (_stream_readable.js:153:18)
at TLSSocket.Readable.push (_stream_readable.js:111:10)
at TLSWrap.onread (net.js:531:20)
Process finished with exit code 1
Till the server crashes, everything's working fine. I receive all emails and responses are sent properly, I even see the JSON response {"email":"user_confirmed"} on my browser. The only problem is that the server crashes afterwards.
EDIT 1
I tried adding return statements-- Still the same problem. I added them here--
return res.json({
'email': 'user_confirmed'
});
I also tried adding a return--
res.json({
'email': 'user_confirmed'
});
return;
No luck till now...
EDIT 2
Ok. so this is actually an open issue on GitHUB, this is reported as a bug.
https://github.com/whitef0x0/node-email-verification/issues/44

So, I tried the GitHUB the solution this way and it is now working flawlessly, even though an official fix is not released...
In the source folder of the module, in the file 'index.js' -->
Go to line 340 --
You'll see this line
callback = options.shouldSendConfirmation;
Change it to -->
callback = function(){};
Hope this helps...

You could change your nev.sendConfirmationEmail method to include the callback as the third argument:
nev.sendConfirmationEmail(user.email, function(err, info) {
if (err) {
console.log('sending_conf_email_failed');
return res.json({'email': 'sending_conf_email_failed'});
}
console.log('user_confirmed');
res.json({
'email': 'user_confirmed'
});
console.log('Done, and confirmed');
}, function(){});

Related

Pasre server on AWS EC2 giving 141 error on cloud code

I am now using the below cloud code to only update "downloads" column on my parse server running on AWS EC2 instance. But I am getting the error code 141(invalid function)
Parse.Cloud.define("updateDownloads", async (request) => {
const query = new Parse.Query(request.params.className);
query.get(request.params.objectId)
.then((watchFace) => {
downloads = watchFace.get("downloads")
watchFace.set("downloads", downloads + 1);
await watchFace.save(null, { useMasterKey: true });
return "download updated";
}, (error) => {
return "something went wrong";
});
});
I have place my code in /opt/bitnami/cloud/main.js.
I even tried adding “cloud”: “/opt/bitnami/cloud/main.js” in config.json file but then the parse server gives 503 Service Unavailable error. So I removed it.
If you don't add the cloud code main.js file to your parse server configuration, parse server will never find your function, and that's why you get the invalid function error.
If you get error when adding the file, you are either adding it in a wrong way (you need to check your parse server initialization code) or the config.json is in wrong format or the cloud code has a problem.
The best way to figure it out is by checking your logs.
At a first glance, a problem that I see (may have others) is the usage of await in a function that is not async. You are also using a combination of async and then, which is little strange.
I'd recommend you to change the code to something like:
Parse.Cloud.define("updateDownloads", async (request) => {
const query = new Parse.Query(request.params.className);
const watchFace = await query.get(request.params.objectId);
const downloads = watchFace.get("downloads");
watchFace.set("downloads", downloads + 1); // You can use inc function to avoid concurrency problem
await watchFace.save(null, { useMasterKey: true });
return "download updated";
});

REACT Fetch request from mobile device doesn't works

I'm building a pwa based on REACT that fetches the info from an api based on Laravel 8. In this pwa the first action that the user has to do is logging in.
On my pc it works perfect, it makes the post request and returns the response to continue the process. But, when I try to do it on my Android, when I press the submit input, this doesn't do anything... No validation error, no success...
The function that does the fetch is this:
handleSubmit(event){
let component = this;
let headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('Accept', 'application/json');
headers.append('Access-Control-Allow-Origin', '*');
headers.append('Origin','http://192.168.1.132:3000');
fetch('http://127.0.0.1:8000/api/login', {
mode: 'cors',
method: 'post',
headers: headers,
credentials: 'include',
body: JSON.stringify(this.state)
}).then(function(response) {
if (response.status !== 200) {
component.setState({
error: 'Email and/or password are not correct'
});
}else{
component.setState({
error: null
});
return response.json()
}
}).then(function(data) {
component.props.onUserChange(data);
}).catch(error => {
console.log('Something went wrong...');
console.log(component.state.error);
});
event.preventDefault();
}
Do you know the cause of this? Is because the project is in local?
I'll appreciate any idea to solve this.
Thanks in advance!

Find invalid push tokens for ios and android

I am developing a mobile application having push notification feature [Android and iOS].I am using node-gcm and node-apn for sending push.
Is there any way to find tokens are invalid or not (iOS/Android registration token) ,so that I can remove them from my database?
This is how I solved it in my project:
[Android]
If you pass array of tokens to node-gcm in response you'll get an array with length equals tokens count. That array contains response for each token - success or error. Based on error you can decide whether to delete token or not:
// This is response from Google
response.results.map((item,index) => {
if (item.error) {
// If Google doesn't recognize token I don't need to keep it anymore
if (item.error === 'NotRegistered') {
failedTokens.push(androidTokens[index]);
} else {
logger.error(`Push notification was not sent because: ${item.error}`);
}
}
});
failedTokens.map(token => {
this.deleteDeviceToken('android', appName, token);
});
[iOS]
I have something similar for iOS. But worth noting that we use HTTP2 APN. So below solution will work for you only if you use HTTP2 for APN too:
// Response from Apple
response.failed.map(failure => {
if (failure.error) {
logger.error(`Error during sending notification: ${JSON.stringify(failure.error)}`);
} else {
// If APN returned HTTP 400 with status BadDeviceToken or HTTP 410 with status Unregistered
// then delete invalid tokens.
if (failure.response.reason === 'BadDeviceToken' || failure.response.reason === 'Unregistered') {
this.deleteDeviceToken('ios', appName, failure.device);
} else {
logger.error(`Push notification was not sent because: ${failure.response.reason}`);
}
}
});

device user mapping in mobile first platform 7.1 console while log in through adapterbased auhentication

I am trying to create a login module from the tutorial and will be using the login user id as target in my next step :sent_EventBased_Push_notification
https://mobilefirstplatform.ibmcloud.com/tutorials/en/foundation/7.1/authentication-security/adapter-based-authentication/adapter-based-authentication-native-android-applications/
Done no changes just downloaded those sample project from github and run then in mfp and android studio as it is.And they did work wonderfully.
But in mobilefirst console though I saw the the device got registered there is no user id against it..What I mean is I am using a nexus4 to login and login id s 'my-phn-no'.So user Id should be 'my-phn-no'.
below I am pasting my AuthAdapter-impl.js [same as eg.]
function onAuthRequired(headers, errorMessage){
errorMessage = errorMessage ? errorMessage : null;
return {
authStatus: "credentialsRequired",
errorMessage: errorMessage
};
}
function submitAuthentication(username, password){
if (username==="8907870678" && password === "password"){
var userIdentity = {
userId: username,
displayName: username,
attributes: {
foo: "bar"
}
};
//WL.Server.sendMessage("Hello", "hi,gd mg")
WL.Server.setActiveUser("AuthRealm", userIdentity);
return {
authStatus: "complete"
};
}
return onAuthRequired(null, "Invalid login credentials");
}
function getSecretData(){
return {
secretData: "12345 changed for trial"
};
}
function onLogout(){
WL.Logger.debug("Logged out");
}
Can you please point out the part I am missing/how do I implement it. Thank you in advance.
I tried the same code in SIT environment where it have the actual product installed MFP 7.1 . It worked perfectly .
I guess there is some thing going wrong in my eclipse plugin.

Facebook Phonegap plugin - Able to log in (it seems) but cannot get access token

I am having trouble getting the phonegap facebook plugin to work. Did the following steps:
I followed the automatic installation on https://github.com/phonegap/phonegap-facebook-plugin,
added facebook-js-jdk and cdv-plugin-fb-connect to my platforms/android/assets/www folder
replaced a line in the config.xml < feature name="FacebookConnectPlugin" > to < feature name="org.apache.cordova.facebook.Connect" > (otherwise it never worked)
On startup, I get a "Cordova Facebook Connect plugin failed on init". Along with this, when I run my (copied and pasted) login function, in the logcat, a login object is returned with all of my information (name, correct userID, email, education and so on...), it says "User cancelled login or did not fully authorize". What's strange is that my getLoginStatus function seems to work properly, but doesn't return an access token. When it runs, it says that I am connected to Facebook, but in the logcat I see "cannot read property 'userID' of undefined".
I tried what was suggested by java.lang.RuntimeException: Failure delivering result ResultInfo while logging using Facebook (Don't keep activities on) but that didn't work. Any help would be appreciated, I have been trying to get this to work for an embarrassingly long time now... My functions are below:
function testLogin(){
FB.login(function(response) {
if (response.authResponse) {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function(response) {
console.log('Good to see you, ' + response.name + '.');
FB.logout(function(response) {
console.log('Logged out.');
});
});
} else {
console.log('User cancelled login or did not fully authorize.');
}
}, {scope: 'email'});
}
function getLoginStatus() {
FB.getLoginStatus(function(response) {
if (response.status == 'connected') {
alert('You are connected to Fb');
var fbid = response.authResponse.userID;
var token = response.authResponse.accessToken;
//console.log(response.authResponse.userID);
//console.log(response.authResponse.accessToken);
alert(response);
} else {
alert('not connected to FB');
}
});
}
function logout() {
FB.logout(function(response) {
alert('logged out');
});
}
The namespace has changed. Instead of using:
FB.login(...
You should use:
facebookConnectPlugin.login(...
And replace FB with facebookConnectPlugin elsewhere.
Read the read me.md at https://github.com/phonegap/phonegap-facebook-plugin, it might help you to keep everything up-to-date ;)

Categories

Resources