firebase.auth().signInWithPhoneNumber + express on Node.js - javascript

I've got a trouble when trying to implement backend firebase Authorization.
After I had read carefully the docs (https://firebase.google.com/docs/auth/web/phone-auth), I figured out that Authorization need to be proceded by two steps:
send phone
send code
I divided Google's example on two promises, but can't understand how to store current user and whether or not I've done everything in an appropriate way.
app.post("/appSignInByPhone", (req, res) => {
let {phoneNumber, applicationVerifier} = req.body;
firebase.auth().signInWithPhoneNumber(phoneNumber, applicationVerifier)
.then(() => res.end("Waiting for code"))
.catch(
error => res.json(error)
);
});
app.post("/appSignInPhoneVerify", (req, res) => {
let {verificationCode} = req.body;
firebase.auth.ConfirmationResult.confirm(verificationCode)
.then( user => res.json(user))
.catch(
error => res.json(error)
);
});
Maybe there are some ways of merging these to request to one...

Try the following:
In step #1 either store or send back the confirmationResult you get from the fulfillment handler:
firebase.auth().signInWithPhoneNumber(phoneNumber, applicationVerifier)
.then((confirmationResult) => {
// either store confirmationResult
// or send it to the client and ask for it in step #2)
}).catch(
error => res.json(error)
);
then in step #2:
// get the confirmationResult from the client or from some storage
// in the server
// for example let { verificationCode, confirmationResult } = req.body;
confirmationResult.confirm(verificationCode)
.then( user => res.json(user))
.catch(
error => res.json(error)
);

Related

why I am getting undefined when I try to access on my property in node js

I have sent data from frontend to backend when I console what type of requests I have gotten I can see the data is showing into the console but when I try to access those properties I got undefined. I have also tried with a query, body but both get undefined when I try to access the property.
Backend code:
// DELETE SHORT URL
app.delete('/delete/:shortUrl', async (res, req) => {
console.log(req);
console.log(req.params, 'req.params');
})
Frontend:
// DELETE
const deleteUrl = (id) => {
fetch(`http://localhost:5000/delete/${id}`, {
method: 'DELETE'
}).then(res => res.json())
.then(data => {
console.log(data);
if (data.deletedCount) {
alert('Order Deleted')
// const remainingOrders = orders.filter(order => order._id !== id)
// setOrders(remainingOrders)
}
})
.finally(() => setLoadings(false))
}
Based on the Express documentation, the route callback's parameters (req & res) are reversed, so you should have:
app.delete('/delete/:shortUrl', (req, res) => {
console.log(req);
console.log(req.params, 'req.params');
})

Gets an error using the post function in firebase using react

I joined the site a few days ago.
I'm new here.
I have a problem that I can not solve. I built a function in Nodejs, every time I run the function I want to get information from the server.
On the client side I have this function, which I run, and then save the data, here no problem.
export const getRealtimeConversations = (user) => (dispatch) => {
axios.post('/realtimeConversations', user)
.then((res) => {
dispatch({
type: userConstants.GET_REALTIME_MESSAGES,
payload: res.data
});
})
.catch((err) => console.log(err))
}
I have a series of axios, when I use this line, I run a server-side function.
app.post('/realtimeConversations', FBAuth, getRealtimeConversations);
This is the function on the server side, I have a collection, which I want to access according to details I send from the client. After I have done the calculations I want, I want to return the end result.
exports.getRealtimeConversations = (req, res) => {
db.collection('conversations')
.where('user_uid_1', 'in', [req.body.uid_1, req.body.uid_2])
.orderBy('createdAt', 'asc')
.onSnapshot((querySnapshot) => {
const conversations = [];
querySnapshot.forEach(doc => {
if (
(doc.data().user_uid_1 == req.body.uid_1 && doc.data().user_uid_2 == req.body.uid_2)
||
(doc.data().user_uid_1 == req.body.uid_2 && doc.data().user_uid_2 == req.body.uid_1)
) {
conversations.push(doc.data())
}
});
console.log(conversations);
return res.json(conversations);
})
}
I do not know why but I get that I have a 404 error, I am completely new to it, I think I have a logical error in the server side function, but I'm not sure what I'm doing wrong.

RestException [Error]: Too many requests status: 429, code: 20429,

helper function
below is my helper function which do two things.
1.generateotp function will send otp to mobile from req.body(here i pass two parametr mobile number and channel. channel is mode of sending otp means sms or otp here it is sms)
2.secon function will verify the otp which user recived. here also we take 2 parameter mobile number and otp
var db = require('../config/connection');
const config= require('../config/config');
const collection = require('../config/connection');
const client = require("twilio")(config.accountSID,config.authToken)
module.exports={
generateOtp:(userNumber,channel) => {
client
.verify
.services(config.serviceID)
.verifications
.create({
to:`+91${userNumber}`,
channel:channel
})
.then((data) => {
console.log(data)
// return callback(null, 'success');
})
.catch((error) => {
console.log(error);
});
},
verifyOtp:(userNumber,userOtp) => {
client
.verify
.services(config.serviceID)
.verificationChecks
.create({
to:`+91$${userNumber}`,
code:userOtp
})
.then((data) => {
console.log(data);
})
.catch((error) => {
console.llog(error);
})
}
}
Route
/Generate Otp
router.post('/signup',(req,res) => {
const {userNumber, channel} = req.body;
userhelper.generateOtp(userNumber,channel)
return res.redirect('/verify');
});
//Verify Otp
router.post('/verify',(req,res) => {
const {userNumber,userOtp} = req.body;
console.log(req.body);
// userhelper.verifyOtp(userNumber,userOtp)
})
I am using twilio verify api for mobile number verification the above code worked perfectly till yesterday now when is test code i am getting an error.
RestException [Error]: Too many requests
at success (C:\Users\Alfas Ahmed\Desktop\whatsapp-ecom\node_modules\twilio\lib\base\Version.js:135:15)
at Promise_then_fulfilled (C:\Users\Alfas Ahmed\Desktop\whatsapp-ecom\node_modules\q\q.js:766:44)
at Promise_done_fulfilled (C:\Users\Alfas Ahmed\Desktop\whatsapp-ecom\node_modules\q\q.js:835:31)
at Fulfilled_dispatch [as dispatch] (C:\Users\Alfas Ahmed\Desktop\whatsapp-ecom\node_modules\q\q.js:1229:9)
at Pending_become_eachMessage_task (C:\Users\Alfas Ahmed\Desktop\whatsapp-ecom\node_modules\q\q.js:1369:30)
at RawTask.call (C:\Users\Alfas Ahmed\Desktop\whatsapp-ecom\node_modules\asap\asap.js:40:19)
at flush (C:\Users\Alfas Ahmed\Desktop\whatsapp-ecom\node_modules\asap\raw.js:50:29)
at processTicksAndRejections (internal/process/task_queues.js:75:11) {
status: 429,
code: 20429,
moreInfo: 'https://www.twilio.com/docs/errors/20429',
details: undefined
}
How to test Twilio Verify without getting rate limited
https://www.twilio.com/blog/test-verify-no-rate-limits
Above what happened is, in development time I just tested many time with same mobile number. Twilio just blocked service. So I just created new Service id , now the code working perfectly fine.

Telegram Bot API: Server down when use getUserProfilePhotos()

Context
I am using telegraf.js for more than 3 bots which run very well in plenty of groups.
Currently one of the bots needs to request for Display Picture of the user who does not have a display picture.
It works very well as expected but unfortunately the bot throws an error and the server goes down
Current Code
// Request for display picture
const requestDP = async (ctx, next) => {
const { from, chat } = ctx.message;
const { can_delete_messages:canDelete } = await deletePermision(ctx);
let totalDPs = 1;
totalDPs = await ctx.telegram.getUserProfilePhotos(ctx.message.from.id)
.then((result) => result.total_count)
.catch((err) => {
console.log(err);
});
if (totalDPs != 0) return next();
if ((chat.id === -1001341734527 || chat.id === -1001083711103 ) && canDelete) {
await ctx.deleteMessage().then((response) => response, ({ response }) => response.ok);
await ctx.replyWithMarkdown(`[${from.first_name||''} ${from.last_name||''}](tg://user?id=${from.id}), പ്രൊഫൈൽ ഫോട്ടോ ഇല്ലാത്തവർക്ക് ഗ്രൂപിൽ മെസേജ് അയക്കാൻ സാധ്യമല്ല`)
.then(({ message_id }) => setTimeout(() => ctx.deleteMessage(message_id), 5 * 60 * 1000))
.catch((err) => console.log("Error in prevencontacts: " + err));
}
}
module.exports = requestDP;
Failure Information (for bugs)
let totalDPs = 1;
totalDPs = await ctx.telegram.getUserProfilePhotos(ctx.message.from.id)
.then((result) => result.total_count)
.catch((err) => {
console.log(err);
});
The functions seem to be working well. But unfortunately sometimes they get an error the and server goes down.
Error message 👇
Error: 400: Bad Request: request for new profile photos has already been sent
It is really hard to refresh the server occasionally :-(
Is there any solution to manage this error ?

Twilio SMS message keeps resending the same message

So I'm trying to send notifications to users phones with Twilio, however, the same message is sent three times. I do have three phone numbers hardcoded into an array (providerNumbers) so I think it's looping through three times because of this.
What I'm trying to do is eventually populate the phone numbers array from user-provided phone numbers they store on Firebase for each user. So a different user will receive the same notification to let them know to visit the website.
Here's my Node.js code:
var providerNumbers = ['number1', 'number2', 'number3'];
var body = "..."
app.get('/testtwilio', function(req, res){
Promise.all(
providerNumbers.map(number => {
return twilio.messages.create({
to: number,
from: '+15704058347',
body: body
});
})
).then(messages => {
console.log('Messages Sent!');
}).catch(err => console.error(err));
});
Anyone know how I can prevent the message sending three times to all the users?
There is nothing wrong with the code you posted.
.map calls the callback function once for each element in your providerNumbers array.
The callback function sends only one message when executed.
You can verify this if you log the index with something like this:
app.get('/testtwilio', function(req, res){
Promise.all(
providerNumbers.map((number, index) => {
console.log(index);
return twilio.messages.create({
to: number,
from: '+15704058347',
body: body
});
})
).then(messages => {
console.log('Messages Sent!');
}).catch(err => console.error(err));
});
In conclusion, something must be hitting your endpoint '/testtwilio' three times.
I hope this helps.
Your example seems to work, try checking the logs to see if multiple requests are being made to the same endpoint. A more concise method of mapping an array of primitives to promises would be using Promise.map. Reducing the usage of complex unit structures reduces the number of procedures your code has to perform, makes it easier to debug and to rule out false positives.
const providerNumbers = ['number1', 'number2', 'number3']
const from = '+15704058347'
const body = "..."
app.get('/testtwilio', (req, res, next) => {
Promise.map(
providerNumbers,
to => twilio.messages.create({to, from, body})
).then(res => {
console.log('Messages sent')
res.json({success: true})
}).catch(next)
})
I solved the problem by changing app.get to app.post.

Categories