My problem is to add data to the database by taking the information from a form.
I want to add the information as "name". I can add "email" correctly but not other data.
My code:
buttonsignup.addEventListener('click', error => {
var nameCompany = document.getElementById('nameCompany').value;
var email = document.getElementById('email').value;
});
function add(nameCompany,email) {
firebase.database().ref().child('users_company').push({
nameCompany: nameCompany,
email: email
});
}
function intFirebase () {
/*CURRENT USER*/
firebase.auth().onAuthStateChanged(function(user) {
if (user != null) {
console.log(user);
console.log('El UID es '+user.uid);
add(nameCompany,user.email);
} else {
console.log('No user is signed in.');
}
});
}
window.onload = function() {
intFirebase();
}
Okay, After turning the coffee into code. I found this solution. But ... Is it a good practice?
const database = firebase.database();
var user = firebase.auth().currentUser;
/* BOTON SIGNUP */
buttonsignup.addEventListener('click', error => {
var nameCompany = document.getElementById('nameCompany').value;
var email = document.getElementById('email').value;
var password_1 = document.getElementById('password_1').value;
var password_2 = document.getElementById('password_2').value;
if (password_1 == password_2) {
if (password_1.length < 8) {
console.log('ContraseƱa muy corta');
document.getElementById("errorPassword").innerHTML = "8 characters";
} else {
firebase.auth().createUserWithEmailAndPassword(email, password_1).then (function(result) {
add(nameCompany,email);
}).catch(function (error) {
var errorCode = error.code;
var errorMessage = error.message;
};
});
}
} else{
console.log('errorPassword');
}
});
function add(nameCompany,email) {
firebase.database().ref().child('users_company').push({
nameCompany: nameCompany,
emailCompany: email
});
}
function intFirebase () {
/*CURRENT USER*/
firebase.auth().onAuthStateChanged(function(user) {
if (user != null) {
console.log(user);
console.log('El UID es '+user.uid);
} else {
console.log('No user is signed in.');
}
});
}
window.onload = function() {
intFirebase();
}
And database rules
{
"rules": {
"users_company": {
"$uid": {
".read": "auth != null && auth.uid === $uid",
".write": true,
//Change this code to: I can not do scripts in the database. -> ".write": "auth != null && auth.uid === $uid",
"nameCompany" : {
".validate": "newData.isString() && newData.val().length < 100"
},
"emailCompany" :{
".validate": "newData.isString() && newData.val().length < 100"
}
}
}
}
}
In your intFirebase function you are only calling your database if there is a current user already logged in. The reason your email is working, is only because you are using 'user.email,' after it sees that a user is indeed logged in.
If you are trying to create a new user (which I think that is what your event listener at the top is trying to do), then you should move your add function to fire off when you submit the form.
Related
I have created a Javascript form validator.
What I would like to do if if all the fields are valid, I would like to be able to submit the form.
I am checking the validity of the fields both on entry and onSubmit.
My thoughts are to use an onClick handler.
For example:
document.getElementById("submit-button").addEventListener("click", submitForm);
submitForm(e) {
e.preventDefault();
form.submit();}
But I am unsure on the best way to implement this with the below validator. For example, should this be used outside of the class validator or within it?
Here is my validator code:
class FormValidator {
constructor(form, fields) {
this.form = form;
this.fields = fields;
}
initialize() {
this.validateOnEntry();
this.validateOnSubmit();
}
validateOnSubmit() {
let self = this;
this.form.addEventListener("submit", (e) => {
e.preventDefault();
self.fields.forEach((field) => {
const input = document.querySelector(`#${field}`);
self.validateFields(input);
});
});
}
validateOnEntry() {
let self = this;
this.fields.forEach((field) => {
const input = document.querySelector(`#${field}`);
input.addEventListener("input", (event) => {
self.validateFields(input);
});
});
}
validateFields(field) {
// Check presence of values
if (field.value.trim() === "") {
this.setStatus(
field,
`${field.previousElementSibling.innerText} cannot be blank`,
"error"
);
} else {
this.setStatus(field, null, "success");
}
// check for a valid email address
if (field.type === "email") {
const re = /\S+#\S+\.\S+/;
if (re.test(field.value)) {
this.setStatus(field, null, "success");
} else {
console.log("ERROR", field.value);
this.setStatus(field, "Please enter valid email address!", "error");
}
}
// Check for valid password
if (field.id === "password") {
if (field.value.trim() == "") {
this.setStatus(field, "Password required!", "error");
} else if (field.value.length <= 10) {
this.setStatus(field, "Password too short!", "error");
} else if (field.value.length >= 50) {
this.setStatus(field, "Password too long!", "error");
} else {
this.setStatus(field, null, "success");
}
}
console.log("We're valid");
}
setStatus(field, message, status) {
const successIcon = field.parentElement.querySelector(".icon-success");
const errorIcon = field.parentElement.querySelector(".icon-error");
const errorMessage = field.parentElement.querySelector(".error-message");
if (status === "success") {
if (errorIcon) {
errorIcon.classList.add("hidden");
}
if (errorMessage) {
errorMessage.innerText = "";
}
successIcon.classList.remove("hidden");
field.classList.remove("input-error");
}
if (status === "error") {
if (successIcon) {
successIcon.classList.add("hidden");
}
field.parentElement.querySelector(".error-message").innerText = message;
errorIcon.classList.remove("hidden");
}
}
}
const form = document.querySelector(".form");
const fields = ["email", "password"];
const validator = new FormValidator(form, fields);
validator.initialize();
I'm trying to make a basic login/signup system with firebase. So far I've been able to fix all the other bugs. The program first creates a user with Firebase Authentication then puts the user data in the Firebase Database. I've managed to get the Authentication working but the database part just makes firebase spit out, "firebase is not defined".
Here's the code:
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.13.0/firebase-app.js";
import { getAuth, createUserWithEmailAndPassword } from "https://www.gstatic.com/firebasejs/9.13.0/firebase-auth.js";
import { getDatabase } from "https://www.gstatic.com/firebasejs/9.13.0/firebase-database.js";
const firebaseConfig = {
apiKey: "AIzaSyCQjuF9A4Km_M7Eo5gnd1B6nmDRRYSle2c",
authDomain: "badge-world.firebaseapp.com",
projectId: "badge-world",
storageBucket: "badge-world.appspot.com",
messagingSenderId: "186421361260",
appId: "1:186421361260:web:852bcaa237f86a76b1f649"
};
const app = initializeApp(firebaseConfig);
const auth = getAuth(app);
const database = getDatabase(app);
document.getElementById ("signup-button").addEventListener("click", register);
document.getElementById ("login-button").addEventListener("click", login);
function register() {
let email = document.getElementById('email').value
let password = document.getElementById('password').value
let username = document.getElementById('username').value
if (validate_email(email) == false || validate_password(password) == false) {
alert("Incorrect Fields. Remember password has to have more than 6 characters and there must be a valid email.")
}
if(validate_field(username) == false) {
alert("Username missing")
}
createUserWithEmailAndPassword(auth, email, password)
.then(function (){
var user = auth.currentUser
var rootRef = firebase.database().ref();
var user_data = {
email : email,
password : password,
username: username,
last_login : Date.now
}
rootRef.child('users/' + user.uid).set(user_data)
alert("User Created!")
})
.catch(function(error) {
var error_code = error.code
var error_message = error.message
alert(error_message)
})
}
function login() {
}
// Validate Functions
function validate_email(email) {
let expression = /^[^#]+#\w+(\.\w+)+\w$/
if (expression.test(email) == true) {
// Email is good
return true
} else {
// Email is not good
return false
}
}
function validate_password(password) {
// Firebase only accepts lengths greater than 6
if (password < 6) {
return false
} else {
return true
}
}
function validate_field(field) {
if (field == null) {
return false
}
if (field.length <= 0) {
return false
} else {
return true
}
}
and here's the database part that seems to be causing the issue:
.then(function (){
var user = auth.currentUser
var rootRef = firebase.database().ref();
var user_data = {
email : email,
password : password,
username: username,
last_login : Date.now
}
rootRef.child('users/' + user.uid).set(user_data)
alert("User Created!")
})
.catch(function(error) {
var error_code = error.code
var error_message = error.message
alert(error_message)
})
Any help is appreciated!
You are using Firebase Modular SDK that uses a functional syntax and not the firebase. namespaced one. The problem is this line:
var rootRef = firebase.database().ref();
There is a top level function ref() to get a DatabaseReference now. Try refactoring the code as shown below:
import { getDatabase, ref, set } from "https://www.gstatic.com/firebasejs/9.13.0/firebase-database.js";
// declared while initializing
const database = getDatabase(app)
set(ref(database, 'users/' + user.uid), user_data)
.then(() => {
console.log("data added")
})
.catch((e) => console.log(e))
The documentation has examples of both the syntaxes so make sure you are referring to modular tab.
Well, I am creating a news feed website. Each user will be able to upload its own events. I am trying to create a section in my firebase database of the users, but I am not able of send variables to the arguments.
firebase.auth().createUserWithEmailAndPassword(email, password).then(function(){
var user = firebase.auth().currentUser;
console.log(user);
if (user) {
// User is signed in.
user.updateProfile({displayName: document.getElementById("name").value});
var user_id = user.id;
var user_email = user.email;
var user_display_name = user.displayName;
//Saving info in the data base.
var database = firebase.database();
database.ref('users/' + user_id).set({
displayName: user_display_name,
id: user_id,
email: user_email
});
window.location = "index.html"
} else {
alert("Something went wrong.");
}
UPDATED VERSION:
window.onload = function(){
var createButton = document.getElementById("createButton");
var signin_button = document.getElementById("signin_button");
createButton.onclick = function(){
var email = document.getElementById("email").value;
var password = document.getElementById("password").value;
firebase.auth().createUserWithEmailAndPassword(email, password).then(function(result){
console.log('result', result);
if (result) {
// User is signed in.
result.updateProfile({displayName: document.getElementById("name").value});
var user_info = {id: result.uid, email: result.email, display_name: result.displayName};
console.log('user_info', user_info);
// Storing user info into database.
var database = firebase.database();
console.log('user id', user_info.id);
database.ref().child('usersss/' + user_info.id).push({
displayName: user_info.display_name,
id: user_info.id,
email: user_info.email
});
window.location = "index.html"
} else {
alert("Something went wrong.");
}
})
.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 if (errorCode == 'auth/email-already-in-use') {
alert('The email is already in use.');
} else if (errorCode == 'auth/invalid-email') {
alert('The email is not valid.');
}else if (errorCode == 'auth/operation-not-allowed') {
alert('This operation is not allowed.');
}else{
alert(errorMessage);
}
console.log(error);
})
}
signin_button.onclick = function(){
window.location = "login.html";
}
}
If nothing exists at 'users/' + user_id you need to use 'push' instead of 'set'. For example:
database.ref().child('/users/' + user_id).push({
//your code
try that.
Here's an action generator I use to log a user into firebase:
export var startLoginWithEmailAndPassword = (email, password) => {
firebase.auth().signInWithEmailAndPassword(email, password).then((result) => {
//handle success
console.log('worked', result);
}).catch((error) => {
//handle error
console.log('error', error);
});
}
In the above case, the 'result' object will have the user details.
To access the content of my app (under ionic), my users have to log in first. Sometimes, the app crashes and it "logs the user out" (well in fact it loses the session but firebase has the user still logged in).
I would like to use the local storage method but I am having a hard time understanding how to put the code together.
I found this tutorial here : Use local storage to login user
And here is my controller :
console.log(window.localStorage.getItem("username"));
console.log(window.localStorage.getItem("password"));
console.log(window.localStorage.getItem("uid"));
// Perform the login action when the user submits the login form
$scope.doLogin = function(userLogin) {
if($document[0].getElementById("user_name").value != "" && $document[0].getElementById("user_pass").value != ""){
// Setup the loader
window.localStorage.setItem("username", $document[0].getElementById("user_name").value);
window.localStorage.setItem("password", $document[0].getElementById("user_pass").value);
$ionicLoading.show({
content: 'Loading',
animation: 'fade-in',
showBackdrop: true,
maxWidth: 200,
showDelay: 0
});
firebase.auth().signInWithEmailAndPassword(userLogin.username, userLogin.password).then(function() {
window.localStorage.setItem("uid", firebase.auth().currentUser.uid);
var userId = window.localStorage.getItem("uid");
firebase.database().ref('accounts/' + userId + '/currentBusiness/').update({
name: "No current business arround",
description: "Seems there's nothing arround...",
})
$state.go("tab.account");
}, function(error) {
// An error happened.
var errorCode = error.code;
var errorMessage = error.message;
if (errorCode === 'auth/invalid-email') {
alert('Enter a valid email.');
$timeout(function () {
$ionicLoading.hide();
}, 1000);
return false;
}else if (errorCode === 'auth/wrong-password') {
alert('Incorrect password.');
$timeout(function () {
$ionicLoading.hide();
}, 1000);
return false;
}else if (errorCode === 'auth/argument-error') {
alert('Password must be string.');
$timeout(function () {
$ionicLoading.hide();
}, 1000);
return false;
}else if (errorCode === 'auth/user-not-found') {
alert('No such user found.');
$timeout(function () {
$ionicLoading.hide();
}, 1000);
return false;
}else if (errorCode === 'auth/too-many-requests') {
alert('Too many failed login attempts, please try after sometime.');
$timeout(function () {
$ionicLoading.hide();
}, 1000);
return false;
}else if (errorCode === 'auth/network-request-failed') {
alert('Request timed out, please try again.');
$timeout(function () {
$ionicLoading.hide();
}, 1000);
return false;
}else {
alert(errorMessage);
$timeout(function () {
$ionicLoading.hide();
}, 1000);
return false;
}
});
}else{
alert('Please enter email and password');
return false;
}//end check client username password
};// end $scope.doLogin()
// Create a callback which logs the current auth state
if (window.localStorage.getItem("username") !== null && window.localStorage.getItem("password") !== null) {
$state.go("tab.account");
} else {
console.log("wooooooo");
}
Any help to integrate both ?
I'm having quite a hard time understanding how to chain promises. I'm writing login function for my app, leverating Loopback's Angular SDK. The objective, upon validating a user's credentials, is to confirm that the user's account is active, then fetch some additional properties including the user's role and set a flag to true if the user has admin privileges.
Here's my code...
$scope.login = function (user) {
User.login(user).$promise.then(
function (data) {
$rootScope.activeUser = data;
$rootScope.user_id = $rootScope.activeUser.user.username;
console.log('Active User: ', $rootScope.activeUser.user.email);
console.log('Status: ', $rootScope.activeUser.user.status);
if ($rootScope.activeUser.user.status === 'Y') {
$scope.loginError = false;
function checkAdmin(eid) {
Se_user.findById({
id: eid
}).$promise.then(
function (data1) {
var user_properties = data1;
if (user_properties.role === 'Admin') {
$rootScope.isAdmin = true;
console.log('isAdminInside: ', $rootScope.isAdmin);
return true;
} else {
//$rootScope.isAdmin = false;
return false;
}
});
};
var isAdmin = checkAdmin($rootScope.user_id);
console.log('isAdminOutside: ', $rootScope.isAdmin);
$state.go('home');
} else {
$scope.loginError = true;
$scope.loginErrorMessage = "Your account has been disabled. Please contact BMT Support for assistance";
}
},
function (err) {
console.log('Error: ', err)
$scope.loginError = true;
$scope.loginErrorMessage = "You've entered an invalid User ID or Password. Please try again.";
});
};
I've been troubleshooting by writing to the console, here's a sample of the output...
Active User: user#email.com
Status: Y
isAdminOutside: undefined
isAdminInside: true
How should I restructure so that the result of checkAdmin is properly returned after a successful login of an active user?
Try changing this part of code :
function checkAdmin(eid) {
return Se_user.findById({
id: eid
}).$promise.then(
function(data1) {
var user_properties = data1;
if (user_properties.role === 'Admin') {
$rootScope.isAdmin = true;
console.log('isAdminInside: ', $rootScope.isAdmin);
return true;
} else {
//$rootScope.isAdmin = false;
return false;
}
});
};
var isAdmin = checkAdmin($rootScope.user_id)
.then(function(val) {
console.log('isAdminOutside: ', val);
$state.go('home');
});