I've been googling for 2 days for html and JavaScript code for adding firebase phone number authentication in my website.
I saw the firebaseui doing this job.
But it has their own form elements.
I haven't found any articles or videos showing "how to make Firebase web auth with phone number, without using Firebaseui/nodejs.
Is it really possible to do this with my own textbox and other buttons?
I had written a code for this and it's not working.
Please do a checkup or prefer any best articles, showing the exact thing I want.
The code:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Untitled</title>
<script src="https://www.gstatic.com/firebasejs/4.6.2/firebase.js"></script>
<script>
// Initialize Firebase
var config = {
apiKey: "*****",
authDomain: "********.firebaseapp.com",
databaseURL: "https://********.firebaseio.com",
projectId: "*******",
storageBucket: "*********.appspot.com",
messagingSenderId: "**********"
};
firebase.initializeApp(config);
</script>
</head>
<body>
<script>
var phoneNumber = getPhoneNumberFromUserInput();
var appVerifier = window.recaptchaVerifier;
firebase.auth().signInWithPhoneNumber(phoneNumber, appVerifier)
.then(function (confirmationResult) {
alert('sms sent');
// SMS sent. Prompt user to type the code from the message, then sign the
// user in with confirmationResult.confirm(code).
window.confirmationResult = confirmationResult;
}).catch(function (error) {
// Error; SMS not sent
// ...
alert('sms not send');
});
</script>
<form>
<input type="tel" id="number">
<input type="number" id="otp_code">
<input type="submit">
</form>
</body>
</html>
Thanks in advance.
There are a lot of examples including the Firebase GitHub sample quick start apps: https://github.com/firebase/quickstart-js/blob/master/auth/phone-invisible.html
Also check the official docs on this: https://firebase.google.com/docs/auth/web/phone-auth
Here is a quick snippet on signing in a user with phone number:
firebase.auth().signInWithPhoneNumber("+xxxxxxxx", window.recaptchaVerifier)
.then((confirmationResult) => {
// At this point SMS is sent. Ask user for code.
let code = window.prompt('Please enter the 6 digit code');
return confirmationResult.confirm(code);
})
.then((result) {
// User is now signed in and accessible via result.user.
});
.catch((error) => {
// Error occurred.
});
# Try This Code. I have only add js/jquery code#
<script>
// Paste the config your copied earlier
var firebaseConfig = {
apiKey: "############################",
authDomain: "############################",
databaseURL: "############################",
projectId: "############################",
storageBucket: "############################",
messagingSenderId: "############################",
appId: "############################",
measurementId: "############################"
};
firebase.initializeApp(firebaseConfig);
// Create a Recaptcha verifier instance globally
// Calls submitPhoneNumberAuth() when the captcha is verified
//set size: "normal" to add recaptcha
window.recaptchaVerifier = new firebase.auth.RecaptchaVerifier(
"recaptcha-container",
{
size: "invisible",
callback: function(response) {
submitPhoneNumberAuth();
}
}
);
// This function runs when the 'sign-in-button' is clicked
// Takes the value from the 'phoneNumber' input and sends SMS to that phone number
function submitPhoneNumberAuth() {
$("#wait").css("display", "block");
$("#sign-in-button").attr("disabled", true);
var userPhone = document.getElementById("phoneNumber").value;
if(userPhone.length != 11){
$("#message").removeClass("alert-info");
$("#message").addClass("alert-danger");
$("#message").html("Please Insert 11 digit Phone Number!!!");
$("#message").css("display", "block");
$("#wait").css("display", "none");
$("#sign-in-button").attr("disabled", false);
return false;
}
var phoneNumber = "+88"+userPhone;
//+88 only for bangladesh.Add your own country code
var appVerifier = window.recaptchaVerifier;
firebase
.auth()
.signInWithPhoneNumber(phoneNumber, appVerifier)
.then(function(confirmationResult) {
document.getElementById('codeDiv').style.display='block';
document.getElementById('getCodeButton').style.display='none';
window.confirmationResult = confirmationResult;
$("#message").html("Please check your inbox and insert code!!!");
$("#message").css("display", "block");
$("#wait").css("display", "none");
})
.catch(function(error) {
$("#sign-in-button").attr("disabled", false);
$("#wait").css("display", "none");
console.log(error.code);
if(error.code == 'auth/invalid-phone-number'){
$("#message").removeClass("alert-info");
$("#message").addClass("alert-danger");
$("#message").html("Invalid Phone Number!! Try Another Number!!!");
$("#message").css("display", "block");
document.getElementById('getCodeButton').style.display='block';
document.getElementById('codeDiv').style.display='none';
}
else if(error.code == 'auth/too-many-requests'){
$("#message").removeClass("alert-info");
$("#message").addClass("alert-danger");
$("#message").html("Too many request from this number. Try Another Number!!");
$("#message").css("display", "block");
document.getElementById('getCodeButton').style.display='block';
document.getElementById('codeDiv').style.display='none';
}
});
}
// This function runs when the 'confirm-code' button is clicked
// Takes the value from the 'code' input and submits the code to verify the phone number
// Return a user object if the authentication was successful, and auth is complete
function submitPhoneNumberAuthCode() {
$("#wait").css("display", "block");
$('#confirm-code').attr("disabled", true);
var code = document.getElementById("code").value;
confirmationResult
.confirm(code)
.then(function(result) {
var user = result.user;
$("#wait").css("display", "block");
$("#message").removeClass("alert-danger");
$("#message").addClass("alert-info");
$("#message").html("Thank you!!Code Matched!!");
$("#message").css("display", "block");
})
.catch(function(error) {
$("#wait").css("display", "none");
$('#confirm-code').attr("disabled", false);
console.log(error);
$("#message").removeClass("alert-info");
$("#message").addClass("alert-danger");
$("#message").html("Code Not Matched!!!");
$("#message").css("display", "block");
});
}
//This function runs everytime the auth state changes. Use to verify if the user is logged in
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
//You are logged IN from firebase
$("#message").removeClass("alert-danger");
$("#message").addClass("alert-info");
$("#message").html("Congratulations!!!Logging...");
$("#message").css("display", "block");
var phone = user.phoneNumber;
firebase.auth().signOut().then(function() {
////You are logged Out from firebase
console.log("Firebase Signout");
}).catch(function(error) {
console.log("Firebase Signout Problem!!");
});
}
Related
I am doing a small contact form on my personal website. I have a problem with integration of firebase database with form. I read the documentation and watched some YT tutorials and I cannot find the mistake. Could you please take a look? I get a 'db is undefined' error in console.
window.onload = function() {
var firebaseConfig = {
apiKey: "sampleValue",
authDomain: "sampleValue",
databaseURL: "sampleValue",
projectId: "sampleValue",
storageBucket: "sampleValue",
messagingSenderId: "sampleValue",
appId: "sampleValue",
measurementId: "sampleValue"
};
firebase.initializeApp(firebaseConfig);
let db = firebase.firestore;
function submitForm() {
// e.preventDefault();
let nameEl = document.getElementById("InputName");
let emailEl = document.getElementById("InputEmail");
let subjectEl = document.getElementById("InputSubject");
let messageEl = document.getElementById("InputMessage");
let nameValue = nameEl.value;
let emailValue = emailEl.value;
let subjectValue = subjectEl.value;
let messageValue = messageEl.value;
db.collection("contact").doc().set({
name: nameValue,
email: emailValue,
subject: subjectValue,
message: messageValue
})
.then(function() {
alert("dataSaved");
})
.catch(function() {
alert("error");
});
}
document.getElementById("submit").addEventListener("click", submitForm());
};
Edit
I have managed to solve the problem thanks to fellow users #Kevin Peña and #Phix help by:
putting the missing firebase-firestore.js script in index.html
<script defer src="https://www.gstatic.com/firebasejs/7.12.0/firebase-firestore.js"></script>
I had realized that settings in my DB disallowed me to push anything from my form so I have changed the rules to
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if true;
}
}
}
Expanding a bit on Phix's comment. Right here:
firebase.initializeApp(firebaseConfig);
let db = firebase.firestore; // <- here
It should be
let db = firebase.firestore()
You can find this on the Guides and on the Reference.
Also, here:
document.getElementById("submit").addEventListener("click", submitForm() /* <-over here */);
You should not call the function, instead pass it to addEventListener (i.e. just its name)
document.getElementById("submit").addEventListener("click", submitForm);
Otherwise the form will be submitted empty when the page loads. And nothing will happen on button click.
I'm logging in users via firebase-auth and need to pass their user uid to the redirected page. How can the user-uid be passed?
I've tried using the docs on firebase auth but cant quite solve it
loginForm.addEventListener('submit', (e) => {
e.preventDefault();
const email = loginForm['email'].value;
const password = loginForm['password'].value;
console.log(email, password);
firebase.initializeApp(config);
firebase.auth().signInWithEmailAndPassword(email, password)
.then(cred => {
if(email ==='admin#mombasa.com' && password ==='adminMomb') {
window.location = './admin-map.php';
}
else if(email ==='admin#nairobi.com' && password ==='adminNai') {
window.location = './admin-map.php';
}
else if(email ==='admin#eldoret.com' && password ==='adminEld') {
window.location = './admin-map.php';
}
else firebase.auth().onAuthStateChanged(function(user) {
window.user = user;
console.log('logged in ', user);
window.location = './dailyreports.php';
console.log('logged in ', user);
});
}).catch(
function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// ...
console.log(errorMessage, errorCode);
}
)
;
});
On navigation to the next page, I expected to see the user-uid output in the console but it returns blank
Instead of passing the UID, it's better to pick up the state in the next page with a so-called authentication state listener.
As shown in the documentation on getting the currently signed in user:
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
} else {
// No user is signed in.
}
});
There will be no delay in picking up the user account this way on the new page, as the Firebase SDK will be able to restore the state from the information it stored in local storage.
I have a problem with firebase and php for push notifications the push notification appears on the user mobile but the push itself if clicked on the user mobile does nothing.
I expect it to lead to the page of the content but the push doesnt get to the user
var config = {
apiKey: "AIzaSyAXavmNUsgT7UgRIQEdweFXIhBrYTGPvOY",
authDomain: "tech-miz.firebaseapp.com",
databaseURL: "https://tech-miz.firebaseio.com",
projectId: "tech-miz",
storageBucket: "tech-miz.appspot.com",
messagingSenderId: "942114086591"
};
firebase.initializeApp(config);
// Retrieve Firebase Messaging object.
const messaging = firebase.messaging();
messaging.requestPermission()
.then(function() {
console.log('Notification permission granted.');
// TODO(developer): Retrieve an Instance ID token for use with FCM.
/*if(isTokenSentToServer()){
console.log("Token already saved");
} else {
getRegToken();
}*/
getRegToken();
})
.catch(function(err) {
console.log('Unable to get permission to notify.', err);
});
function getRegToken() {
// Get Instance ID token. Initially this makes a network call, once retrieved
// subsequent calls to getToken will return from cache.
messaging.getToken()
.then(function(currentToken) {
if (currentToken) {
//sendTokenToServer(currentToken);
// console.log(currentToken);
saveToken(currentToken);
setTokenSentToServer(true);
//updateUIForPushEnabled(currentToken);
} else {
// Show permission request.
console.log('No Instance ID token available. Request permission to generate one.');
// Show permission UI.
setTokenSentToServer(false);
}
})
.catch(function(err) {
console.log('An error occurred while retrieving token. ', err);
// showToken('Error retrieving Instance ID token. ', err);
setTokenSentToServer(false);
});
}
function setTokenSentToServer(sent) {
window.localStorage.setItem('sentToServer', sent ? 1 : 0);
}
function isTokenSentToServer() {
return window.localStorage.getItem('sentToServer') == 1;
}
function saveToken(currentToken){
$.ajax({
type: "POST",
url: "blog/ajax/save.push.notification.php",
data: "token=" + currentToken,
success: function (response) {
console.log(response);
}
});
}
I need the push notification to be clickable and lead the user to the page where the push notification is notifying the user about
I am having a problem with my current firebase html and javascript setup that is leading to not getting users registered to my firebase database of users. I am not receiving any error alerts in the browser when I run the below code. I have also tried running the site by running 'firebase serve' and I am not getting any errors logged to the console.
The html source includes and javascript file are below. I have tested to make sure that I am able to access the username and password fields from the Document and that is working fine. Let me know if you need to see any additional information. Thank you!
Right after the Body tag in my html I include the following scripts:
<script src="https://www.gstatic.com/firebasejs/5.0.3/firebase.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.0.3/firebase-auth.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="register.js"></script>
Then in my register.js file:
// Initialize Firebase
var config = {
apiKey: "mykey",
authDomain: "mydomain",
databaseURL: "myurl",
projectId: "myid",
storageBucket: "mybucket",
messagingSenderId: "mysenderid"
};
firebase.initializeApp(config);
$(document).ready(function(){
$("form").submit(function(){
var email = $('user').val();
var password = $('#password').val();
firebase.auth().createUserWithEmailAndPassword(email, password)
.then(function(val) {
alert("Success!!");
console.log(val);
})
.catch(function(error) {
// Handle Errors here.
alert("ERROR");
var errorCode = error.code;
var errorMessage = error.message;
// [START_EXCLUDE]
if (errorCode == 'auth/weak-password') {
alert('The password is too weak.');
} else {
alert(errorMessage);
}
console.log(error);
// [END_EXCLUDE]
}).success(function(json) {
console.log(json);
alert("TESTER");
})
// [END createwithemail]
});
});
A couple of remarks:
1/ For initialization you just need to do
<script src="https://www.gstatic.com/firebasejs/5.0.3/firebase.js"></script>
OR
<script src="https://www.gstatic.com/firebasejs/5.0.3/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.0.3/firebase-auth.js"></script>
See https://firebase.google.com/docs/web/setup
2/ Don't call the submit method of your form. Just get the values of the email and password fields (e.g. var email = $('user').val();) and call the Firebase createUserWithEmailAndPassword(email, password) function as you do, without submitting the form.
Note that if you want to handle a succesful registration you should add a then(), as follows, since the function returns a promise (see doc here)
firebase.auth().createUserWithEmailAndPassword(email, password)
.then(function(val) {
//Success!!
console.log(val);
})
.catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
if (errorCode == 'auth/weak-password') {
alert('The password is too weak.');
} else {
alert(errorMessage);
}
console.log(error);
});
Add a success function callback and see the response
$("form").submit(function(){
var email = $('user').val();
var password = $('#password').val();
firebase.auth().createUserWithEmailAndPassword(email, password).catch(function(error) {
// Handle Errors here.
alert("ERROR");
var errorCode = error.code;
var errorMessage = error.message;
// [START_EXCLUDE]
if (errorCode == 'auth/weak-password') {
alert('The password is too weak.');
} else {
alert(errorMessage);
}
console.log(error);
// [END_EXCLUDE]
}).success(function(json) {
console.log(json);
});
// [END createwithemail]
});
I am using Firebase as a signaling intermediary between two tabs in google chrome on my local computer. I am using the most recent build on the simple-peer github repo: simplepeer.min.js. The full error is
Uncaught DOMException: Error processing ICE candidate
My netcode is as follows:
const roomId = extractQueryString('roomId');
firebase.auth().onAuthStateChanged((user) => {
if (user && roomId) {
// User is signed in.
const isAnonymous = user.isAnonymous;
const uid = user.uid;
const sessionId = Math.floor(Math.random()*1000000000);
const testLocation = firebase.database().ref();
console.log(uid);
//doesRoomExist(roomId);
const p2pConnection = new SimplePeer({
initiator: document.location.hash === '#initiator'
});
p2pConnection.on( 'signal', (signal) => {
console.log(signal);
testLocation.child(roomId).child(uid).set({
sender: sessionId,
signal: signal
});
});
testLocation.child(roomId).on('child_added', (snapshot) =>{
if( snapshot.val().sender !== sessionId ) {
p2pConnection.signal( snapshot.val().signal );
}
});
/*
* We'll send a message to the other side as soon as
* the connection is established
*/
p2pConnection.on( 'connect', () => {
console.log( 'webrtc datachannel connected' );
p2pConnection.send( 'Hello from user ' + userName );
});
p2pConnection.on( 'close', () => {
console.log( 'webrtc datachannel closed' );
});
p2pConnection.on( 'data', (data) => {
console.log( 'received data <b>' + data + '</b>' );
});
//db.ref().child('ergh').set({ID:uid});
} else {
// Do stuff if they inputted an invalid room or fb is down
}
});
The error occurs when I open the second browser window and the code:
testLocation.child(roomId).on('child_added', (snapshot) =>{
if( snapshot.val().sender !== sessionId ) {
p2pConnection.signal( snapshot.val().signal );
}
});
executes.
In case I am missing anything, here is my Index.html:
<!DOCTYPE html>
<html>
<script src="https://www.gstatic.com/firebasejs/4.6.2/firebase.js">
</script>
<script>
// Initialize Firebase
var config = {
apiKey: "AIzaSyAUEtS1zEakv0a1TIlsTobQwwTyvlUzQGc",
authDomain: "simple-whiteboard.firebaseapp.com",
databaseURL: "https://simple-whiteboard.firebaseio.com",
projectId: "simple-whiteboard",
storageBucket: "simple-whiteboard.appspot.com",
messagingSenderId: "272918396058"
};
firebase.initializeApp(config);
firebase.auth().signInAnonymously().catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
});
</script>
<script src="js/simplepeer.min.js"></script>
<script src="js/draw.js"></script>
<script src="js/RTC-networking.js"></script>
<body onload="init()">
<canvas id="myCanvas" width="400" height="400"
style="position:absolute;top:10%;left:10%;border:2px solid;">
</canvas>
</body>
Any help will be much appreciated. Thank you.
Your code here:
p2pConnection.on( 'signal', (signal) => {
console.log(signal);
testLocation.child(roomId).child(uid).set({
sender: sessionId,
signal: signal
});
});
Will get the 'sender' overwritten each time you get an 'Offer' or 'Candidate' (different types of signals).
As your error says "Error processing ICE candidate" it means you use trickle: true option.
You have to consider this facts:
Without trickle-
you get one signal, "Offer" and "Answer" on host and on client, respectively.
With trickle-
you get as above PLUS many more 'candidate' signals per each.
So instead of overwriting the signals u get, you should keep a reference to the initial "Offer" and "Answer" and a list of all candidates per each side. And try to "signal" back to each one of them (host will try to signal all client's candidates and vise versa).