// 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
Related
I'm using the Stripe API and this is using the customer email address in the database however we've just had an issue where someone is signing in to the page using a different case to their sign up and it is not showing them as subscribed.
Obviously I'd like to convert the Stripe emails to all be lowercase but I'm not sure how to do this after getting the email. I am converting the user input to be all lowercase but that just means that if the email in Stripe is not lowercase they are not showing as subscribed.
Thanks in advance
$(document).ready(function() {
var productIDFull = "prod_key00000";
var email = '#User.Identity.Name';
var emailLower = email.toLowerCase();
// check if user has made a purchase in stripe for this product
var hasPurchasedFull = false;
$.ajax({
type: "GET",
url: 'https://api.stripe.com/v1/customers?email=' + emailLower,
headers: {
'authorization': 'Bearer sk_live_0000'
},
success: function(data) {
var isSubscribed = false;
// loop through each customer returned
$.each(data.data,
function(i, customer) {
console.log(customer);
var subscriptions = customer.subscriptions;
console.log(subscriptions);
// loop through each sub
$.each(subscriptions.data,
function(j, subscription) {
console.log(subscription);
var subData = subscription.items.data;
// loop through each plan
$.each(subData,
function(k, planData) {
console.log(planData);
if (planData.plan.product == 'prod_Kc3e_0000' && planData.plan.usage_type == 'licensed') {
isSubscribed = true;
}
});
});
I am converting the user input to be all lowercase but that just means
that if the email in Stripe is not lowercase they are not showing as
subscribed.
This sounds expected based on Stripe's documentation: https://stripe.com/docs/api/customers/list?lang=curl#list_customers-email
The email value is case sensitive, so customer Test#example.com will not be returned if you list customers with email test#example.com
I think a better way to handle this is to store a mapping of Stripe customer IDs and email addresses in an internal database and compare against this database instead of a customer list call.
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);
}
So I want to submit this web form to firebase using js script and live server that in visual studio code.
But after the submit, there is a child column with random numbers like this. I want to give a value of the name column "lakshan" to that column. How I do that ?
Current result is messages is Object
I want messages as Array
This is the js code
// Initialize Firebase (ADD YOUR OWN DATA)
var firebaseConfig = {
apiKey: "api key here",
authDomain: "test-a137f.firebaseapp.com",
databaseURL: "https://test-a137f.firebaseio.com",
projectId: "test-a137f",
storageBucket: "test-a137f.appspot.com",
messagingSenderId: "id here",
appId: "appId goes here",
measurementId: "the measurementId"
};
firebase.initializeApp(firebaseConfig);
firebase.analytics();
// Reference messages collection
var messagesRef = firebase.database().ref('Admins');
// Listen for form submit
document.getElementById('contactForm').addEventListener('submit', submitForm);
// Submit form
function submitForm(e){
e.preventDefault();
// Get values
var name = getInputVal('name');
var company = getInputVal('company');
var email = getInputVal('email');
var phone = getInputVal('phone');
var message = getInputVal('message');
// Save message
saveMessage(name, company, email, phone, message);
// Show alert
document.querySelector('.alert').style.display = 'block';
// Hide alert after 3 seconds
setTimeout(function(){
document.querySelector('.alert').style.display = 'none';
},3000);
// Clear form
document.getElementById('contactForm').reset();
}
// Function to get get form values
function getInputVal(id){
return document.getElementById(id).value;
}
// Save message to firebase
function saveMessage(name, company, email, phone, message){
var newMessageRef = messagesRef.push();
newMessageRef.set({
name: name,
company:company,
email:email,
phone:phone,
message:message
});
}
The random number you get is a unique key generated by the push() method.
If you want to use your own key you need to use the set() method as follows:
var messagesRef = firebase.database().ref('Admins');
var childNode = 'lakshan';
// Or var childNode = 'Alex';
// Or var childNode = 'Denis';
messagesRef.child(childNode).set({
name: name,
company:company,
email:email,
phone:phone,
message:message
});
This is how I wanted. Thank you Renaud ;)
var childNode = name;
// Or var childNode = 'Alex';
// Or var childNode = 'Denis';
messagesRef.child(childNode).set({
name: name,
company:company,
email:email,
phone:phone,
message:message
});
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.
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);