Firebase phone number authentication on web - javascript

I tried this code for making Firebase phone number authentication:
<!DOCTYPE html>
<html lang="en">
<head>
<title>
Firebase Phone Number Auth
</title>
</head>
<body>
Updated
<script src="https://www.gstatic.com/firebasejs/4.8.1/firebase.js"></script>
<script>
// Initialize Firebase
var config = {
apiKey: "AIzaSyAL8dSTuXb92DWu0l78dtV4m4fC8psKeV4",
authDomain: "groupinger-users.firebaseapp.com",
databaseURL: "https://groupinger-users.firebaseio.com",
projectId: "groupinger-users",
storageBucket: "groupinger-users.appspot.com",
messagingSenderId: "432661298034"
};
firebase.initializeApp(config);
</script>
<script>
window.recaptchaVerifier = new firebase.auth.RecaptchaVerifier('sign- in-button', {
'size': 'invisible',
'callback': function(response) {
// reCAPTCHA solved, allow signInWithPhoneNumber.
onSignInSubmit();
}
}); firebase.auth().signInWithPhoneNumber("+91XXXXXXXXXX", window.recaptchaVerifier)
.then((confirmationResult) => {
// At this point SMS is sent. Ask user for code.
alert('A confirmation message was just sent.');
var code = window.prompt('Please enter the 6 digit code');
return confirmationResult.confirm(code);
}).then((result) => {
console.log(result);
// User is now signed in and accessible via result.user.
}).catch((error) => {
// Error occurred.
});
</script>
</body>
</html>
But it's not working.
I'm a real newbie on Firebase. Please somebody help.
(Note: you can also test it on Localhost.)
The code is live at https://GroupinGer.cu.ma/ph/
Also, I would like to show the user data(Phone number, UID etc.) In another file called details.html.
I tried this code:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Logged in</title>
</head>
<body>
Your details are shown below.
<br>
<script src="https://www.gstatic.com/firebasejs/4.8.1/firebase.js"></script>
<script>
// Initialize Firebase
var config = {
apiKey: "AIzaSyAL8dSTuXb92DWu0l78dtV4m4fC8psKeV4",
authDomain: "groupinger-users.firebaseapp.com",
databaseURL: "https://groupinger-users.firebaseio.com",
projectId: "groupinger-users",
storageBucket: "groupinger-users.appspot.com",
messagingSenderId: "432661298034"
};
firebase.initializeApp(config);
</script>
<script>
var credential = firebase.auth.PhoneAuthProvider.credential(confirmationResult.verificationId, code);
alert(credential);
alert('nope.');
</script>
</body>
</html>
Please have a look at it too.
Again, thanks a lot.

First of all, you need to initialize a recaptchaVerifier like this:
window.recaptchaVerifier = new firebase.auth.RecaptchaVerifier('sign-
in-button', {
'size': 'invisible',
'callback': function(response) {
// reCAPTCHA solved, allow signInWithPhoneNumber.
onSignInSubmit();
}
});
Second, your code has syntax error. Try the following:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Firebase Phone Number Auth</title>
</head>
<body>
<form>
<input type="text" id="verificationcode" value="enter verification">
<input type="button" value="Submit" onclick="myFunction()">
</form>
<div id="recaptcha-container"></div>
<script src="https://www.gstatic.com/firebasejs/4.8.1/firebase.js"></script>
<script type="text/javascript">
// Initialize Firebase
var config = {
apiKey: "AIzaSyAL8dSTuXb92DWu0l78dtV4m4fC8psKeV4",
authDomain: "groupinger-users.firebaseapp.com",
databaseURL: "https://groupinger-users.firebaseio.com",
projectId: "groupinger-users",
storageBucket: "groupinger-users.appspot.com",
messagingSenderId: "432661298034"
};
firebase.initializeApp(config);
</script>
<script type="text/javascript">
window.recaptchaVerifier = new firebase.auth.RecaptchaVerifier('recaptcha-container');
firebase.auth().signInWithPhoneNumber("replace with your phone number with country code, start with +1 if US.", window.recaptchaVerifier)
.then(function(confirmationResult) {
window.confirmationResult = confirmationResult;
console.log(confirmationResult);
});
var myFunction = function() {
window.confirmationResult.confirm(document.getElementById("verificationcode").value)
.then(function(result) {
console.log(result);
}).catch(function(error) {
console.log(error);
});
};
</script>
</body>
</html>
For more details, you can refer to the phone auth part of firebase auth doc.
https://firebase.google.com/docs/auth/web/phone-auth

Related

Uncaught TypeError: firebase.auth is not a function

I try to build an authentification app with firebase (email & password) but i have problem with firebase methods.
When I call firebase.auth, they said "it's not a function". Is it because my project and firebase SDK are not linked ?
Do you have some suggestions ? :)
<!doctype html>
<html lang="fr">
<head>
<meta charset="utf-8">
<!-- The core Firebase JS SDK is always required and must be listed first -->
<script src="https://www.gstatic.com/firebasejs/7.6.0/firebase-app.js"></script>
<!-- TODO: Add SDKs for Firebase products that you want to use
https://firebase.google.com/docs/web/setup#available-libraries -->
<script src="https://www.gstatic.com/firebasejs/7.6.0/firebase-analytics.js"></script>
<script>
// Your web app's Firebase configuration
var firebaseConfig = {
apiKey: "secret",
authDomain: "secret",
databaseURL: "secret",
projectId: "secret",
storageBucket: "secret",
messagingSenderId: "secret",
appId: "secret",
measurementId: "secret"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
firebase.analytics();
</script>
<!--Stylesheet CSS -->
<link rel="stylesheet" href="../css/main.css">
<title>Inscription</title>
</head>
<body>
<form id="formSignUp" method="POST" onsubmit="signUp()">
<input type="text" id="form_input_mail" name="mail" placeholder="E-mail" size= "30">
<input type="password" id="form_input_password" name="password" placeholder="Mot de passe"
size= "30">
<button type="submit" id="button_orange_center"> Suivant</button>
</form>
<script>
function signUp(){
firebase.auth().createUserWithEmailAndPassword(form_input_mail, form_input_password)
.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);
});
}
</script>
</body>
</html>
Firebase products (eg. Auth) also need to be downloaded from the CDN
<script src="https://www.gstatic.com/firebasejs/7.6.0/firebase-auth.js"></script>
Reference: https://firebase.google.com/docs/web/setup
You need to add firebase auth to the js file:
<!-- Add Firebase products that you want to use -->
<script src="https://www.gstatic.com/firebasejs/7.6.0/firebase-auth.js"></script>
You can check here for all available products to add:
https://firebase.google.com/docs/web/setup#available-libraries

Firebase Realtime Database: Can't send or retrieve data from Firebase Database

I need help with Realtime Database: I can't send or retrieve data to Firebase from an HTML Page.
HTML:
<head>
</head>
<body>
<script src="https://www.gstatic.com/firebasejs/6.3.3/firebase-app.js"></script>
<script>
var firebaseConfig = {
apiKey: "AIzaSyAQqSYXa-TRHGQwx_Cz9mpg2dreT38tq6k",
authDomain: "miparada-e0e6c.firebaseapp.com",
databaseURL: "https://miparada-e0e6c.firebaseio.com",
projectId: "miparada-e0e6c",
storageBucket: "miparada-e0e6c.appspot.com",
messagingSenderId: "331834990091",
appId: "1:331834990091:web:a1a7925f63be5faf"
};
firebase.initializeApp(firebaseConfig);
function writeData() {
firebase.database().ref("User").set({
name: document.getElementById("nameField").value,
age: document.getElementById("ageField").value
});
}
</script>
<h1>User Database</h1>
<input type = "text" placeholder = "name" id = "nameField">
<input type = "text" placeholder = "age" id = "ageField">
<button onclick = "writeData">SUBMIT</button>
</body>
I'm not getting any results.
You're using a partial import of the Firebase SDK, you need to import the real time database as well as stated in the documentation , and call the function properly (with parenthesis).
<head>
</head>
<body>
<script src="https://www.gstatic.com/firebasejs/6.3.3/firebase-app.js"></script>
<!-- import the real time database SDK -->
<script src="https://www.gstatic.com/firebasejs/6.3.3/firebase-database.js"></script>
<script>
var firebaseConfig = {
apiKey: "AIzaSyAQqSYXa-TRHGQwx_Cz9mpg2dreT38tq6k",
authDomain: "miparada-e0e6c.firebaseapp.com",
databaseURL: "https://miparada-e0e6c.firebaseio.com",
projectId: "miparada-e0e6c",
storageBucket: "miparada-e0e6c.appspot.com",
messagingSenderId: "331834990091",
appId: "1:331834990091:web:a1a7925f63be5faf"
};
firebase.initializeApp(firebaseConfig)
function writeData() {
firebase.database().ref("User").set({
name: document.getElementById("nameField").value,
age: document.getElementById("ageField").value
});
}
</script>
<h1>User Database</h1>
<input type="text" placeholder="name" id="nameField">
<input type="text" placeholder="age" id="ageField">
<!-- call the function with parenthesis -->
<button onclick="writeData()">SUBMIT</button>
</body>
Hope it helps ;)
Also: watch out for the security rules, right now anybody can read/write anything in your database.
Add this line of code right after the script block
<!-- import the real time database SDK -->
<script src="https://www.gstatic.com/firebasejs/6.3.3/firebase-database.js"></script>
because you didn't connect the real time database to your program

how to integrate firebase in webapp using android firebase database?

android database is create and i want to authenticate it using html page.
it is not working code is given below.
here basically we have a html login page and script to authenticate it from fire-base database.provide with the solution code or what's wrong with my code or something missing in it.
<!DOCTYPE html>
<html>
<head>
<!-- /////////////////firebase method ///////////////////// -->
<title>
the login form
</title>
<script src="https://www.gstatic.com/firebasejs/4.9.1/firebase.js"></script>
<script src="https://www.gstatic.com/firebasejs/4.9.0/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/4.9.0/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/4.9.0/firebase-database.js"></script>
<script src="https://www.gstatic.com/firebasejs/4.9.0/firebase-firestore.js"></script>
<script src="https://www.gstatic.com/firebasejs/4.9.0/firebase-messaging.js"></script>
<script>
// Initialize Firebase
var config = {
apiKey: "AIzaSyBgFUWzUrmLXVuKtGtChe2I2zvf5sYga54",
authDomain: "skool-1083c.firebaseapp.com",
databaseURL: "https://skool-1083c.firebaseio.com",
projectId: "skool-1083c",
storageBucket: "skool-1083c.appspot.com",
messagingSenderId: "911580445409"
};
firebase.initializeApp(config);
</script>
</head>
<body>
<h1>Admin Login</h1>
<form class="form" action="new_blank">
<input type="text" placeholder="username" id="email"autofocus><br>
<input type="password" placeholder="pasword" id="password" ><br></br>
<input type="submit" value="login" id="sign-in">
<br>
</form>
<!-- ///////////////stylesheet///////////// -->
<script>
document.querySelector('#sign-in').addEventListener('click', function(e) {
e.preventDefault();
e.stopPropagation();
var email = document.querySelector('#email').value;
var password = document.querySelector('#password').value
var credential = firebase.auth.EmailAuthProvider.credential(email, password);
window.alert(credential);
var auth = firebase.auth();
var currentUser = auth.currentUser;
// Step 2
// Get a credential with firebase.auth.emailAuthProvider.credential(emailInput.value, passwordInput.value)
// If there is no current user, log in with auth.signInWithCredential(credential)
// If there is a current user an it's anonymous, atttempt to link the new user with firebase.auth().currentUser.link(credential)
// The user link will fail if the user has already been created, so catch the error and sign in.
});
</script>
</body>
</html>
If you want to sign in user with email+password on Firebase Authentication, follow the documentation here. From there, the example to sign in is:
firebase.auth().signInWithEmailAndPassword(email, password).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// ...
});
To detect when a user signs in, follow the documentation here. From there:
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
} else {
// No user is signed in.
}
});
implement firebase auth in app/build.gradle
implementation 'com.google.firebase:firebase-auth:18.1.0'
implementation 'com.google.firebase:firebase-database:18.0.1'
use enterd user id and password with this function
private void login() {
FirebaseAuth firebaseAuth=FirebaseAuth.getInstance();
firebaseAuth.signInWithEmailAndPassword(usrId, usrPass).addOnCompleteListener(loginActivity.this, new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
if (!task.isSuccessful()) {
Toast.makeText(loginActivity.this, "Not sucessfull", Toast.LENGTH_SHORT).show();
} else {
startActivity(new Intent(loginActivity.this, MainActivity.class));
}
}
});

How can i retrieve the data (name,uid,post.....) from the following firebase db for my web application using javascript

This is the code. It contains both HTML and javascript.
This code doesn't have any effect. It's showing nothing.
The DB actually created using the Android app. Now I have to retrieve these data in my web app too.
<html>
<head>
</head>
<body>
<script src="https://www.gstatic.com/firebasejs/live/3.0/firebase.js">
</script>
<script>
var config = {
apiKey: "PlhWdY7OVtZGhBAEI_LrGMP073D5Ra6g",
authDomain: "m-grance.firebaseapp.com",
databaseURL: "https://m-grance.firebaseio.com",
projectId: "m-grievance",
storageBucket: "m-grance.appspot.com",
messagingSenderId: "57976764514788"
};
firebase.initializeApp(config);
function fun(){
var rootRef = firebase.database.ref();
var urlRef = rootRef.child("User/123456788765/name");
urlRef.once("value", function(snapshot) {
snapshot.forEach(function(child) {
console.log(child.key+": "+child.val());
});
});
}
</script>
<input type="button" value="click" onclick="fun()">
</body>
</html>

Unable to initialise firebase in my html file and save any data to realtime database

I am trying to learn firebase. But i am unable to save my input to the firebase database because it is not getting initialized even after adding all the required script that I know. Here is my entire code
PS: authentication to my database was also turned off for learning purpose. So it must not be any issue with authentication.
<!DOCTYPE html>
<html>
<head>
<title>Learning Firebase</title>
<script src="https://www.gstatic.com/firebasejs/4.1.2/firebase.js"></script>
<script type="text/javascript">
var config = {
apiKey: "xxxxxxxx",
authDomain: "xxxxxxxx",
databaseURL: "xxxxxxx",
projectId: "xxxxxx",
storageBucket: "xxxxxxx",
messagingSenderId: "xxxxxxx"
};
firebase.initializeApp(config);
var text=documentgetElementById('text').value;
function validate(){
var database=firebase.database().ref();
database.child("text").set(text);
}
</script>
</head>
<body>
<form onsubmit="validate();">
Text:<input type="text" id='text'/>
<input type='submit' value='save'/>
</form>
</body>
Your problem is not with your Firebase code, it is about your JavaScript code. Replace this code below and try it again:
<!DOCTYPE html>
<html>
<head>
<title>Learning Firebase</title>
<script src="https://www.gstatic.com/firebasejs/4.1.2/firebase.js"></script>
<script type="text/javascript">
var config = {
apiKey: "xxxx",
authDomain: "xxxx",
databaseURL: "xxxx",
projectId: "xxxx",
storageBucket: "",
messagingSenderId: "xxxx"
};
firebase.initializeApp(config);
function validate(){
var yourNewChildValue=document.getElementById('text').value;
var database=firebase.database().ref();
database.child("yourNewChildKey").set(yourNewChildValue);
}
</script>
</head>
<body>
<form>
Text:<input type="text" id='text'/>
<input type='button' onclick="validate();" value='save'/>
</form>
</body>
It must be save your data to Firebase database if your credentials are true. Please let me know.

Categories