Firebase web app - can't get user.uid when creating new account - javascript

I am working on a small web app and I have hit a roadblock that I can't seem to overcome. I am able to register a new account, but I would like to save additional data to a database right after signing up.
This is what I have that I am confident that works fine.
$("#user-sign-up-button").click(function(){
var firstName = $("#new-user-first-name").val();
var secondName = $("#new-user-surname").val();
var charity = $("#new-user-charity-account").val();
var userEmail = $("#new-user-email").val();
var userPassword = $("#new-user-password").val();
var secondPassword = $("#new-user-repeated").val();
firebase.auth().createUserWithEmailAndPassword(userEmail, userPassword)
.catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// ...
});
});
Now in regards to saving the additional variables to the database I have tried both of the below within .then part of createuserWithEmailAndPassword.
.then(
function(user){
var root = firebase.database().ref();
var uid = user.uid;
alert(uid);
var postData = { firstName: first_name,
secondName: second_name,
email: user_email,
isCharity: charity };
root.child("users").child(uid).set(postData);
}
function writeUserData(first_name, second_name, charity, user_email) {
firebase.database().ref('users/' + user.uid).set({
firstName: first_name,
secondName: second_name,
email: user_email,
isCharity: charity
});
)
Both of the above solutions work within onAuthStateChanged but I want to capture the data at sign up, not every time someone signs in.
Any assistance would be great.

You must use .onAuthStateChanged to get at firebase.auth().currentUser. It's asynchronous and will be empty/null until it resolves. Also, don't forget that new email based accounts will not be .emailValidated:true until they have clicked a verification email link. ...something to consider.

Related

Apps Script: Get user input from HTML form and save them as global variables

The server side script below receives user input from an HTML form and adds these user data/input to the last available row of my Google Sheet. It´s been working pretty fine. But now I want to store some elements of the array that is in this script as global variables, so that I can re-use them later on in other server side functions bound to the same Google Sheet. I am specifically interested in the values inside lastName, email and phone. Any idea how this can be done?
Thank you so much in advance for your hints and help.
function AddUserInputToSheet(gender, firstName, lastName, age, email, phone) {
var url = 'SHEET_URL';
var ss = SpreadsheetApp.openByUrl(url);
var webAppSheet = ss.getSheetByName("SHEET_NAME");
webAppSheet.appendRow([gender, firstName, lastName, age, email, phone]);
}
You can use Properties Service of Apps Script.
This service allows scripts to store strings as key-value pairs scoped
to one script, one user of a script, or one document in which an
editor add-on is used.
In your case, there are 2 options you can choose. Script Properties and User Properties.
The difference between the two is the content of Script Properties are shared to all users while User Properties is only available to the current user of a script, add-on, or web app.
Here I created an example of how to use Properties.
function setProperties(lastName = "Test Last Name", email = "Test Email", phone = "Test Phone"){
var scriptProperties = PropertiesService.getScriptProperties();
scriptProperties.setProperties({'lastName': lastName, 'email': email, 'phone':phone})
}
function readProperties(){
var scriptProperties = PropertiesService.getScriptProperties();
Logger.log(scriptProperties.getProperties());
}
Here I run the readProperties() function first and the result is
Then I run the 'setProperties()' and rerun the readProperties() function again:
I reload the script page and ran the readProperties() function:
To add it in your script, you can set the properties in AddUserInputToSheet() and call it anywhere in your script.
Example:
function AddUserInputToSheet(gender, firstName, lastName, age, email, phone) {
var url = 'SHEET_URL';
var ss = SpreadsheetApp.openByUrl(url);
var webAppSheet = ss.getSheetByName("SHEET_NAME");
webAppSheet.appendRow([gender, firstName, lastName, age, email, phone]);
var scriptProperties = PropertiesService.getScriptProperties();
scriptProperties.setProperties({'lastName': lastName, 'email': email, 'phone':phone})
}
function someFunction(){
var scriptProperties = PropertiesService.getScriptProperties();
var data = scriptProperties.getProperties();
var lastName = data["lastName"];
var email = data["email"];
var phone = data["phone"];
//some operations here
}
Here's an example:
function myfunk1() {
PropertiesService.getScriptProperties().setProperty('Global1',JSON.stringify(SpreadsheetApp.getActive().getSheetByName('Sheet0').getDataRange().getDisplayValues()));
}
function myfunk2() {
const vs = JSON.parse(PropertiesService.getScriptProperties().getProperty('Global1'))
SpreadsheetApp.getActive().getSheetByName('Sheet1').getRange(1,1,vs.length,vs[0].length).setValues(vs);
}

How do i check if an email exist in Firebase using Javascript?

// Initialize Firebase
var config = {
apiKey: "AIzaSyA_kaqHtpvjFeagx0BYKdSCeQVCDvG5ESM",
authDomain: "pilot-860c1.firebaseapp.com",
databaseURL: "https://pilot-860c1.firebaseio.com",
projectId: "pilot-860c1",
storageBucket: "",
messagingSenderId: "897069842460"
};
firebase.initializeApp(config);
// references message collections
var messageRef = firebase.database().ref("messages");
window.onload = form;
// Legg til en addEventListener som ser etter en submit, og kall funksjonen submitForm
function form(){
document.getElementById("signupform").addEventListener("submit", submitForm);
}
function submitForm(e){
e.preventDefault();
// hent values
var fname = getInputValues("fname");
var lname = getInputValues("lname");
var email = getInputValues("email");
var phone = getInputValues("phone");
var pass = getInputValues("p1");
// save form and info
saveForm(fname, lname, email, phone, pass);
// show alert if sent
document.getElementById("formRegistered").style.display = "block";
// hide alert after 3 sec and hide formRegistered span
setTimeout(function(){
document.getElementById('formRegistered').style.display = "none";
}, 3000);
// reset form after
document.getElementById("signupform").reset();
}
function getInputValues(id){
return document.getElementById(id).value;
}
// Save form like this
function saveForm(fname, lname, email, phone, pass){
var newMessageRef = messageRef.push();
newMessageRef.set({
name: fname,
lastname: lname,
email: email,
phone: phone,
pw: pass
});
}
So this is my code, I´ve tried adding if statements but i can´t seem to access my firebase to check if that email exists, I want to basically tell the user the email is already registered if its exisiting in my firebase. I've looked at the documentation too but i dont get it
Try using the Firebase Auth for signing up and authenticating your users, instead of writing them to the DB, because basically to write into the database you will need users, and if you are planning to keep the db open to writes, then its probably a bad idea.
Firebase Auth
Next step using firebase auth you can check if the user exists by using the following method, which returns a non empty List if the user exists/has been signed up
fetch Providers for email

Authenticate user and add them DB simultaneously

I want to signup new users (through auth) and then add them (with their names and other info) to my user list database in realtime DB. I can't figure out what I'm doing wrong. Authentication works great but the new user is not being added to the DB.
var fname = document.getElementById('fname').value;
var lname = document.getElementById('lname').value;
var email = document.getElementById('email').value;
in the code below, I register them then add their names to the DB and then send a verification email.
function handleRegister() {
var ref = firebase.database().ref();
console.log(email);
console.log(fname);
if (email.length < 4) {
alert('Please enter an email address.');
return;
}
if (password.length < 4) {
alert('Please enter a password.');
return;
}
firebase.auth().createUserWithEmailAndPassword(email, password).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
var uid = firebase.auth().currentUser.uid;
// [START_EXCLUDE]
if (errorCode == 'auth/weak-password') {
alert('The password is too weak.');
firebase.auth().onAuthStateChanged(user => {
if(user) {
var postData = {
Fullname: fname + lname,
email: email,
};
// Write the new post's data simultaneously in the posts list and the user's post list.
var updates = {};
updates['/Users/' + uid ] = postData;
return firebase.database().ref().update(updates);
}
})
} else {
console.log(error);
}
})
Authentication and send email verification works fine but names are not being added to the DB. Also if there is a better approach to achieve auth,add to DB and send email verification, please let me know. Please help.
This is the updated addition
var addusertoDB = function(user){
var uid = firebase.getAuth().uid;
var postData = {
Firstname: fname,
Lastname: lname,
email: email,
}
// Get a key for a new Post.
var newPostKey = firebase.database().ref().child('Users').push().uid
// Write the new post's data simultaneously in the posts list and the user's post list.
var updates = {};
updates['/Users/' + newPostKey] = postData;
// updates['/user-posts/' + '/' + newPostKey] = postData;
return firebase.database().ref().update(updates);
}
and handle register has been updated to
firebase.auth().createUserWithEmailAndPassword(email, password).then(
addusertoDB).catch(handleCreateUserError);
it's finally being added to the DB (without the uid) but firebase.getAuth().uid is not getting the uid. the error I'm getting is "firebase.getAuth is not a function"
You are trying to handle both the errors and the user update in the same function you have passed to catch(). This means that any code inside that function is only run when firebase.auth().createUserWithEmailAndPassword(email, password) fails.
From the firebase documentation:
createUserWithEmailAndPassword
createUserWithEmailAndPassword(email, password) returns
firebase.Promise containing non-null firebase.User
Creates a new user account associated with the specified email address
and password.
On successful creation of the user account, this user will also be
signed in to your application.
This means that on the successful creation of a user you will have access to the new user via a callback passed into then().
You probably want something like this:
var doSomethingWithNewUser = function(user) {
// Manipulate the newly created User however you like here.
// You don't have to sign them in again.
};
var handleCreateUserError = function(error) {
var errorCode = error.code;
var errorMessage = error.message;
// Do whatever you want with the error codes.
};
firebase.auth().createUserWithEmailAndPassword(email, password)
.then(doSomethingWithNewUser)
.catch(handleCreateUserError);

How to use variable between functions

I'm having a problem of using variables between functions. As you can see down below User.username is available and good at the sign up page, but when you go to the login page I told it to first alert the value of User.username, and it alerts undefined? I'm confused here. I'm pretty sure I'm missing a concept here. Anyways Thank you so much!:
Here is a plunkr: http://plnkr.co/edit/qB3Gkeq5ji1YQyy0kpGH
Here is my script.js:
app.controller("AuthCtrl", ["$scope", "Auth","$rootScope",
function($scope, Auth, $rootScope) {
var User = {}
$scope.createUser = function(username, email, password) {
$rootScope.usernames = username
User.username = username
$scope.message = null;
$scope.error = null;
var ref2 = new Firebase("https://uniquecoders.firebaseio.com/");
ref2.createUser({
email: $scope.email,
password: $scope.password
}, function(error, userData) {
if (error) {
switch (error.code) {
case "EMAIL_TAKEN":
alert("The new user account cannot be created because the email is already in use. Try to login");
break;
case "INVALID_EMAIL":
alert("The specified email is not a valid email.");
break;
case "INVALID_PASSWORD":
alert("The Specified Passowrd Is not valid.")
break;
default:
alert("Error creating user:", error);
}
} else {
alert("Successfully created user account with username" + User.username);
window.location.hash = "/User"
}
});
};
$scope.logIn = function(){
alert(User.username)
$rootScope.usernames = User.username
$scope.message = null;
$scope.error = null;
var ref2 = new Firebase("https://uniquecoders.firebaseio.com/");
ref2.authWithPassword({
"email" : $scope.logInemail,
"password" : $scope.logInemailpassword
}, function(error, userData){
if(error){
alert("Login Failed Because : " + error)
}
else{
alert("Logged In!")
window.location.hash = "/User"
}
})
}
/* $scope.removeUser = function() {
$scope.message = null;
$scope.error = null;
Auth.$removeUser({
email: $scope.email,
password: $scope.password
}).then(function() {
$scope.message = "User removed";
}).catch(function(error) {
$scope.error = error;
});
};*/
}
]);
When page reloads the entire javascript is re executed. So user object populated in registration process is no longer available in login function because page has reloaded on clicking on signup button.
So we need to store the user name in cookie so that we can access it any time. Even when its removed from javascript runtime it will be there in the browser cache.
Its risky to store passwords in cookies for security issues.
On successful registration save the username in cookie.
Some thing like this
document.cookie ="username =" +username + "; " +"email ="+ email;
In login function get cookie values and check if email of user is same as entered
function getCookie(name ) {
var pairs = document.cookie.split("; "),
count = pairs.length, parts;
while ( count-- ) {
parts = pairs[count].split("=");
if ( parts[0] === name )
return parts[1];
}
return false;
}
var username=getCookie("username");
var email=getCookie("username");
if($scope.logInemail ==email)
{
alert(username);
}
You have to remember that a web application is a communication between the browser the the web server. The browser and the server can be on different machines (even if they aren't when you are testing.)
There are two ways to make this work
While the browser and the server communicate some information is saved and passed back and forth on both ends -- this is called a cookie. This is the most common way to do save data between pages. The browser requests a page. When it get the reply from the server it contains a cookie. The next time the browser requests a page it includes the cookie in it's request. In this way the server knows the request is related to the prior request.
The server is smart enough to keep track of all "sessions" by different browsers. It then saves session data about that communication -- when it gets the next request from the same browser it goes to the session data and retrieves information about that that browser and what it was doing. (Often this is done with cookies.)

Retrieve objectId in Parse

In simple, I am trying to retrieve the objectId for a particular user in parse (using Javascript). I can retrieve any other query in the database, such as username, phone, mailing address but not the objectId, here is how I retrieve the rest of the query:
var objectId = userInfo.get("objectId");
Any assistance would be greatly appreciated.
Below is more lines of the code (everything is retrieved beside objectId)
query.find({ success: function(array) {
// this means the query was a success, but we're not yet certain that we found anything
// the param to find's success is an array of PFObjects, possibly empty
if (array.length > 0) {
var userInfo = array[0];
var address = userInfo.get("address");
$scope.address = address;
var email = userInfo.get("username");
$scope.email = email;
var fullName = userInfo.get("fullName");
$scope.fullName= fullName;
var number = userInfo.get("phoneNumber");
$scope.number= number;
var objectId = userInfo.get("objectId");
$scope.objectId= objectId;
var mailingAddress = userInfo.get("mailingAddress");
$scope.mailingAddress = mailingAddress;
var plan = userInfo.get("plan");
$scope.plan = plan;
Thanks in advance
The js sdk provides an id member, so ...
$scope.objectId = userInfo.id;
As an aside, check out the JS guide on their site. It's a very well written doc. Pay particular attention to the code snippets in the objects and query sections.

Categories

Resources