Firebase Phone Auth not working in deployment - javascript

Phone Auth is working locally but when the app is deployed the phone auth isnt working. When i enter my number and click to receive otp , i run into a error.
POST https://identitytoolkit.googleapis.com/v1/accounts:sendVerificationCode?key=AIzaSyDAcA6ooS6Rzg0jlAItTbWxM3ADJqCX2lE 400
this is my code:
getOTP(){
this.recaptchaVerifier = new RecaptchaVerifier('phone-verify',
{size: 'invisible'}, this.local_auth)
let vnumber = this.verify.value.number.slice(1)
vnumber = '+27' + vnumber
console.log(vnumber)
signInWithPhoneNumber(this.local_auth, vnumber, this.recaptchaVerifier)
.then((confirmation) => {
localStorage.setItem('verificationId',JSON.stringify(confirmation.verificationId))
}).then((response) => {
console.log(response)
})
.catch((err) => {
console.log(err.messge)
setTimeout(() => {
window.location.reload()}, 5000)
})
}
any ideas or advice or solutions would be welcomed...

Related

Twillio : before building the app, what is the base URL?

I wrote Twillio code to get phone verification in frontend.
And here PRACTICE_BASE_URL was my IP address like below since I just test it on expo.
Whenever IP address I changed it.
const PRACTICE_BASE_URL = "http://172.30.1.18:4000";
const sendCode = async () => {
setPhoneInserted(true);
setwaitMessage(true);
// send verfication code to phone number
await fetch(`${PRACTICE_BASE_URL}/verify/${phone}`, {
method: "GET",
headers: {
"Content-Type": "application/json",
},
})
.then((res) => res.json())
.then((res) => {
if (res.status === "pending") {
setcheckedNumber(phone);
setwaitMessage(false);
}
})
.catch((err) => {
setPhoneInserted(false);
setwaitMessage(false);
setphone("");
console.log(err);
setDisableConfirm(true);
goDownY.start();
setVeriBox(true);
setVerimessage("잘못된 휴대전화번호입니다.");
reset();
setretry(true);
});
};
I want to build the app in real or beta version from expo now.
So how do I change BASE_URL here?
I searched but not found in Twillio homepage. please help me.
The usual base URL for the Twilio API is:
https://api.twilio.com/2010-04-01/
The base URL for the Twilio Verify API is:
https://verify.twilio.com/v2/

AppCheck tokens are not recognised only when using mobile

I'm developing a webapp authentication system using Firebase. When I login and use the webapp from my computer everything works fine but when I use it on mobile appcheck does not work anymore and it gives me the following error in the console:
https://content-firebaseappcheck.googleapis.com/v1/projects/nameoftheproject/apps/1:784721317237:web:5db5892bc06253ab6b173c:exchangeRecaptchaEnterpriseToken?key=myKey
Failed to load resource: the server responded with a status of 403 ()
This is the code I'm using to create initialise appCheck in my webapp:
const appCheck = initializeAppCheck(app, {
provider: new ReCaptchaEnterpriseProvider(config[process.env.REACT_APP_ENV]['recaptcha-key']),
isTokenAutoRefreshEnabled: true
});
export const getAppCheckToken = async () => {
let appCheckTokenResponse;
try {
appCheckTokenResponse = await getToken(appCheck, false);
} catch(err) {
console.log(err);
}
return appCheckTokenResponse.token;
}
So a typical use case for that function is this:
//This is the code from one of my functions, it's just an example to show you how I use appcheck tokens
if (querySnapshot.docs.length === 0) {
headerAPI.headers['X-Firebase-AppCheck'] = await getAppCheckToken();
await axios.post(signupAPI, {
email: email,
username: displayName
}, headerAPI);
await sendEmailVerification(auth.currentUser, {
url: config[process.env.REACT_APP_ENV]['url-used-to-send-mail-auth-signup'],
handleCodeInApp: true
})
props.cookieAlert('Info', 'Cookies', 'Informations here...');
} else {
window.location.href = '/dashboard/home';
}
Now, I can't understand why it doesn't work on mobile...I hope my code is clear enough to let you understand my troubles, thank you in advance.

Angular Firebase Phone Authentication gives an error of wrong OTP, even it is correct

I've implemented firebase phone authentication in my angular app, everything is just correct but when I verify phone number and after sending otp for verification it gives an error of wrong OTP code even it is correct. This happens for the first attempt after second attempt it verifies OTP and start behaving as it should be.
This is geOTP method.
getOTP() {
this.showPhoneLoading = true;
this.reCaptchaVerifier = new firebase.auth.RecaptchaVerifier
('sign-in-button',
{size: 'invisible'},)
// this.timer(1);
debugger
this.payload = {
phoneNumber: `+${this.countryCode}`+this.phoneNumber
}
firebase
.auth()
.signInWithPhoneNumber(this.payload, this.reCaptchaVerifier)
.then((res)=> {
console.log(res);
localStorage.setItem('verificationId', JSON.stringify(res.verificationId))
// debugger
this.myStepper.next();
this.cf.detectChanges();
this.showPhoneLoading = false;
this.toastr.success('We have sent an otp. Please fill in the below fields to continue.', 'Verify')
}).catch((error)=> {
this.toastr.error(error.message)
setTimeout(() => {
window.location.reload()
},2000);
})
}
this is my verification code.
handleClick() {
debugger
this.showVerifyOtp = true;
debugger
const otp = this.otp.replace(/\s/g,'');
const credentials = firebase.auth.PhoneAuthProvider.credential(this.verify, otp);
debugger
firebase
.auth()
.signInWithCredential(credentials)
.then((res)=> {
this.toastr.success('Your phone number is verified.', 'Success!')
this.myStepper.next();
this.showVerifyOtp = false;
localStorage.setItem('user_data',JSON.stringify(res))
})
.catch((error) => {
debugger
if (error) {
firebase.auth().signInWithCredential(credentials)
this.myStepper.next();
}
})
}
currently im catching error and calling function again. please help me out.

React socket.io-client not re-rendering component after response from server to a particular room (Python backend)

I have a server backend written in Python with Flask-SocketIO. I'm utilizing it's room feature to make private conversations. Upon a join room event the server fires the following function to let the frontend know where to send messages to specific user:
socketio.emit('room name response', {'roomName': room_name, 'recipient': recipient}, to=sid)
where sid is the private room created only for the user when connecting to a socket. Then I want to keep this information in React state in a map, like this:
function ChatWindow({ username, token }) {
const [responses, setResponses] = useState([]);
const [roomsMap, setRoomsMap] = useState(new Map());
const [currentRoom, setCurrentRoom] = useState("");
const [messageValue, setMessageValue] = useState("");
var socket = null;
useEffect(() => {
socket = socketIOClient(ENDPOINT);
});
useEffect(() => {
socket.on("global response", (data) => {
setResponses((responses) => [...responses, data]);
});
socket.on("room name response", (data) => {
console.log(`joined ${data.roomName} with ${data.recipient}`);
setCurrentRoom((currentRoom) => data.roomName);
setRoomsMap((roomsMap) => roomsMap.set(data.recipient, data.roomName));
});
return () => socket.close();
}, []);
const sendMessage = () => {
if (messageValue.length < 1) {
return;
}
socket.emit("global message", {
user_name: username,
message: messageValue,
timestamp: Date.now(),
});
setMessageValue("");
};
const joinRoom = (recipient) => {
socket.emit("join", {
token: token,
username: username,
recipient: recipient,
});
// setCurrentRoom(() => roomsMap.get(recipient));
};
const leaveRoom = (recipient) => {
socket.emit("leave", {
token: token,
username: username,
recipient: recipient,
});
const newRooms = roomsMap;
newRooms.delete(recipient);
console.log(`left room with ${recipient}`);
newRooms.forEach((val, key) => console.log(`${val}:${key}`));
setRoomsMap(newRooms);
};
const checkUser = (userToCheck) => {
if (userToCheck === username) {
return styles.chatFromUser;
} else {
return styles.chatToUser;
}
};
return (...);
}
export default ChatWindow;
Sadly, React doesnt react to the socket emitting message, even though it can be seen in network tab in developer tools. The global response works fine.
When I alter the backend function to:
socketio.emit('room name response', {'roomName': room_name, 'recipient': recipient})
React suddenly works as expected. I'm trying to understand why it happens, especially when the browser seems to see the incoming messages as stated above, so it's most likely my bad coding or some React/Javascript thing.
Thank You for any help in advance.
The problem was that socket sometimes was created multiple times, therefore, the socket that useEffect was currently listening wasn't necessarily the one in the room. So I made one, global socket to fix this and whole thing now works.

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.

Categories