Firebase Authentication setup in Java Script - javascript

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]
});

Related

Create user with Phone number Firebase [duplicate]

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!!");
});
}

How to pass user uid from login page to a different page in a web app

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.

How to add user's extra information such as display name in firebase using javascript?

Using createUserWithEmailAndPassword function of firebase I am able to sign users up but how to add extra information such as display name and picture URL?
This is what I have done.
const signup = document.querySelector('#signup-form');
signup.addEventListener('submit', e=>{
e.preventDefault();
//get user info
const first_name = signup['firstname'].value;
const last_name = signup['lastname'].value;
const email = signup['email1'].value;
const password = signup['pswd1'].value;
//sigup the user
firebase.auth().createUserWithEmailAndPassword(email, password).then(()=>{
firebase.auth().onAuthStateChanged(function(user){
if(user){
user.updateProfile({
displayName: first_name
})
}
})
signup.reset();
}).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
window.alert("Error: " + errorMessage);
// ...
});
});
Once you have created the user, you can access user object provided by firebase. Using its updateProfile function, you can pass an object containing the properties you want the user object to have, like the code below:
var user = firebase.auth().currentUser;
user.updateProfile({
displayName: "Jane Q. User",
photoURL: "https://example.com/jane-q-user/profile.jpg"
}).then(function() {
// Update successful.
}).catch(function(error) {
// An error happened.
});
This worked for me.
firebase.auth().createUserWithEmailAndPassword(email, password).then(cred=>{
cred.user.updateProfile({
displayName: first_name + " " + last_name
})
})
.catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
window.alert("Error: " + errorMessage);
// ...
});

How to save user information (userName) firebase new angular 2

I need to save in my Firebase UserName and get it when he is LogIn, but I cant figure out it. What should I add in code?
signUp(userEmail , userPassword){
firebase.auth().createUserWithEmailAndPassword(userEmail, userPassword).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// ...
});
signIn(userEmail , userPassword){
firebase.auth().signInWithEmailAndPassword(userEmail, userPassword).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// ...
});
Thank you for answers.
I have solved this problem . You just chain function then it will look like
firebase.auth().createUserWithEmailAndPassword(userEmail, userPassword).then(function (result) {
firebase.database().ref('/users/' + result.uid).set({
username: 'someOne',
email:userEmail,
});
console.log(result);
}).catch(function (error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// ...
});

Google Firebase forget password

How do you implement forget password method in my method. I am creating a HTML project which is due soon. My code:
function toggleSignIn() {
if (!firebase.auth().currentUser) {
// [START createprovider]
var provider = new firebase.auth.GoogleAuthProvider();
// [END createprovider]
// [START addscopes]
provider.addScope('https://www.googleapis.com/auth/plus.login');
// [END addscopes]
// [START signin]
firebase.auth().signInWithPopup(provider).then(function(result) {
// This gives you a Google Access Token. You can use it to access the Google API.
var token = result.credential.accessToken;
// The signed-in user info.
var user = result.user;
// [START_EXCLUDE]
document.getElementById('quickstart-oauthtoken').textContent = token;
// [END_EXCLUDE]
}).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// The email of the user's account used.
var email = error.email;
// The firebase.auth.AuthCredential type that was used.
var credential = error.credential;
// [START_EXCLUDE]
if (errorCode === 'auth/account-exists-with-different-credential') {
alert("You have already signed up with a different auth provider for that email.");
// If you are using multiple auth providers on your app you should handle linking
// the user's accounts here.
}
else if (errorCode === 'auth/auth-domain-config-required') {
alert("An auth domain configuration is required");
}
else if (errorCode === 'auth/cancelled-popup-request') {
alert("Popup Google sign in was canceled");
}
else if (errorCode === 'auth/operation-not-allowed') {
alert("Operation is not allowed");
}
else if (errorCode === 'auth/operation-not-supported-in-this-environment') {
alert("Operation is not supported in this environment");
}
else if (errorCode === 'auth/popup-blocked') {
alert("Sign in popup got blocked");
}
else if (errorCode === 'auth/popup-closed-by-user') {
alert("Google sign in popup got cancelled");
}
else if (errorCode === 'auth/unauthorized-domain') {
alert("Unauthorized domain");
}
else {
console.error(error);
}
// [END_EXCLUDE]
});
// [END signin]
} else {
// [START signout]
firebase.auth().signOut();
// [END signout]
}
// [START_EXCLUDE]
document.getElementById('quickstart-sign-ing').disabled = false;
// [END_EXCLUDE]
}
Here is a link to give you guidance:
https://firebase.google.com/docs/auth/web/manage-users#set_a_users_password
Please can you help me
To implement a forgot password button, you have to call:
firebase.auth().sendPasswordResetEmail('user#example.com')
Check the documentation for more details:
https://firebase.google.com/docs/reference/js/firebase.auth.Auth#sendPasswordResetEmail
The easiest way to implement recover forgot password functionality is to call
import { AngularFireAuth } from "#angular/fire/auth";
constructor(
public afAuth: AngularFireAuth
) { }
// Reset Forggot password
ForgotPassword(passwordResetEmail) {
return this.afAuth.auth.sendPasswordResetEmail(passwordResetEmail)
.then(() => {
window.alert('Password reset email sent, check your inbox.');
}).catch((error) => {
window.alert(error)
})
}
To implement firebase reset you first need to send email to the user and for that we use sendPasswordResetEmail method. after that if user gonna click on the email, it will be redirected to a default page provided by firebase from there user can reset their password.
But if you want to have custom page for the password reset you can do that too, to do that you need to change the action url in the email template of your firebase project then you need to setup that custom action url, for this you can read this offical doc page: https://firebase.google.com/docs/auth/custom-email-handler?hl=en&authuser=0

Categories