How do I access the user UID in my firebase database - javascript

I am working on a fantasy soccer web app based on a local league. So far, when a user is created using firebase auth, there is a respective node created in my firebase using the user uid as follows:
$scope.signUp = function (){
var username = $scope.user.email;
var password = $scope.user.password;
var teamname = $scope.user.teamname;
var fullname = $scope.user.fullname;
var ref = firebase.database().ref().child('users');
if(username && password){
var auth = $firebaseAuth();
auth.$createUserWithEmailAndPassword(username,
password).then(function(user){
console.log("User Successfully Created");
let usersRef = firebase.database().ref("users");
//child is created under users node with a user's user id as
child name
usersRef.child(user.uid).set({
email: user.email,
userName: username,
teamname: teamname,
fullname: fullname,
total: 0,
week:0
});
$location.path('/home');
}).catch(function(error){
$scope.errMsg = true;
$scope.errorMessage = error.message;
});
}
};
That part works fine. In the database, the JSON tree looks something like this:
users:{
user UID: {
email:
teamname:
fullname:
week:
}
}
I have a service I use for all my views :
.service('CommonProp',['$location','$firebaseAuth', function($location,$firebaseAuth){
var user = "";
var auth = $firebaseAuth();
return {
getUser:function(){
if(user == ""){
user = localStorage.getItem("userEmail");
}
return user;
},
setUser: function(value){
localStorage.setItem("userEmail", value);
user = value;
},
logoutUser: function(){
auth.$signOut();
console.log("Logged Out Successfully");
user = "";
localStorage.removeItem("userEmail");
$location.path('/home');
}
};
}]);
PROBLEM
My problem is that when I go to my 'select player' view, I do not know how to access the user UID so that I can set each user's selection for each week.This is what I tried to do :`
$scope.saveTeam = function(user){
$scope.history = [];
var uid = user.uid;
var ref2 = firebase.database().ref("users/" + auth.uid + "/week");
ref2.set($scope.history);
};
Is there a way that I can access each user's respective "week" child node under their respective user uid?

Related

how can I redirect to another html file after being able to store data in firestore?

I've first made my web store data on firebase real time database and
now I changed it to firestore but now I'm not quite sure how can I
redirect after data has been posted to firestore I tried adding location.href =
"https://dr-elvic-tengco-web.firebaseapp.com/ThankYou.html"; under
console.log("Document successfully written!");
yes it redirects and stores the data
and what I noticed it does work when I wait for 2 seconds before I
click the OK button on the window.alert("Appointment Request Sent!
Please wait for a confirmation on your Email or We'll txt you back!") but noone would wait for 2 seconds before you click "okay" button ,
right?
//I had this code first on firebase realtime database-this worked and redirected
var data = {
FirstName: firstName,
LastName: lastName,
Contact: cPhone,
Gender: inputGender,
Birthdate: Bday,
Address: inputAddress,
City: inputCity,
Province: inputState,
Zip: inputZip,
Email: exampleInputEmail1,
Message: inputMessage,
Clinic: inputClinic
};
var firebaseRef = firebase.database().ref();
firebaseRef.push(data, (error) => {
if (error) {
console.log('error');
} else {
location.href = "https://dr-elvic-tengco-web.firebaseapp.com/ThankYou.html";
}
})
//and now this is the firestore
<script>
//FOR REALTIME DABASE
function getInfo() {
var firstName = document.getElementById("firstName").value;
var lastName = document.getElementById("lastName").value;
var cPhone = document.getElementById("cPhone").value;
var exampleInputEmail1 = document.getElementById("exampleInputEmail1").value;
var Bday = document.getElementById("Bday").value;
var inputGender = document.getElementById("inputGender").value;
var inputAddress = document.getElementById("inputAddress").value;
var inputCity = document.getElementById("inputCity").value;
var inputState = document.getElementById("inputState").value;
var inputZip = document.getElementById("inputZip").value;
var inputMessage = document.getElementById("inputMessage").value;
var inputClinic = document.getElementById("inputClinic").value;
if (!firstName || !lastName || !cPhone || !exampleInputEmail1 || !Bday || !inputGender || !inputAddress || !inputCity || !inputState || !inputZip || !inputMessage || !inputClinic) {
window.alert("Please Complete the Form! The Page will Reload For Security Purpose")
document.getElementById("gbutton").disabled = true;
document.location.reload()
} else {
window.alert("Appointment Request Sent! Please wait for a confirmation on your Email or We'll txt you back!")
var db = firebase.firestore();
db.collection("Requests").doc().set({
FirstName: firstName,
LastName: lastName,
Contact: cPhone,
Gender: inputGender,
Birthdate: Bday,
Address: inputAddress,
City: inputCity,
Province: inputState,
Zip: inputZip,
Email: exampleInputEmail1,
Message: inputMessage,
Clinic: inputClinic
})
.then(function() {
console.log("Document successfully written!");
location.href = "https://dr-elvic-tengco-web.firebaseapp.com/ThankYou.html";
})
.catch(function(error) {
console.error("Error writing document: ", error);
});
}
}
I have found an alternative by using setTimeout
.then(function() {
console.log("Document successfully written!");
setTimeout(function() {
location.href = "https://dr-elvic-tengco-web.firebaseapp.com/ThankYou.html";
}, 2000);
})
.catch(function(error) {
console.error("Error writing document: ", error);
});

ReactNative and firebase, Real time database when signUp

I build a react native signUp form with this fields (email, password, name, and phone) and I need to add it to the firebase database when user create his account.
I create the signUp function like this:
onSignUpPress() {
const navigation = this.props.navigation;
this.setState({ error: '', loading: true });
const { email, password } = this.state;
firebase.auth().createUserWithEmailAndPassword(email, password)
.then(() => {
this.setState({ error: '', loading: false });
navigation.navigate("Profile");
})
.catch(() => {
this.setState({ error: 'Authentication failed.', loading: false });
console.log("Error creating user:");
});
}
and it's work
I need to know how can I add the field to a database
I try this :
writeUserData(uid, name, email, phone) {
let userId = firebaseApp.auth().currentUser.uid;
var newUser = {
name: name,
email: email,
phone: phone
}
var newUserKey = firebase.database().ref().child('users').push().key;
var updates = {};
updates['/users/' + newUserKey] = newUser;
updates['/user-users/' + uid + '/' + newPostKey] = postData;
return firebase.database().ref().update(updates);
}
onSignUpPress() {
....
....
firebase.auth().createUserWithEmailAndPassword(email, password)
.then(() => {
....
this.writeUserData(uid, name, email, phone);
navigation.navigate("Profile");
})
....
.....
}
but it's not working correctly any help, please?
Firebase has many functionalities. Out of them two are authentication and real time database.
When you call createUserWithEmailPassword successfully, it automatically creates a UID of the user and stores the meta in Firebase Authentication.
You can now at point of time get this UID of this user when he is authenticated using firebase.auth(). currentUser.uid and then create a firebase reference where you want to save data database.ref().child(path)
Use the .set(object) or .push(object) to save data.
Tip : Create your database architecture properly (see documentation) to be able to fetch the saved data properly.
try this,
writeUserData(uid, name, email, phone) {
const userId = firebase.auth().currentUser.uid;
//You don't have to create key because userId is uniq value.
return firebase.database().ref(`users/${userId}`).update({name, email, phone});
}
onSignUpPress() {
....
....
// createUserWithEmailAndPassword promise resolve return userData!
firebase.auth().createUserWithEmailAndPassword(email, password)
.then(userData => {
....
this.writeUserData(userData.uid, name, email, phone);
navigation.navigate("Profile");
})
....
.....
}
and I don't get it why you try to update,
updates['/user-users/' + uid + '/' + newPostKey] = postData;
even if you don't have postData at this moment!
You just set when user create post data like this
writePostData(uid, postData) {
const postRef = firebase.database().ref(`user-users/${uid}`);
//this way is useful when key handling before push
var push = postRef.push();
var key = push.key;
return postRef.child(key).set(postData);
//or just push
return postRef.push(postData);
}

Firebase reading a particular key values

Basically I have my username as a key for user data. Now I am trying to match the username with my current username stored in session storage and read the userdata for that username.
Here is my .js code
var database = firebase.database();
var currentusername = sessionStorage.getItem("username");
var userref = database.ref("users");
userref.orderByChild("username").equalTo(currentusername).once("value").then(function(snapshot) {
console.log(snapshot.val());
});
Firebase Data Structure
Appname
Users
username: "a1"
email: " ",
firstname: "abc",
lastname: "xyz"
When I try to run the above code I am getting snapshot.val() as null although there exists a record with a matching username key.
var userref = database.ref("users/"+currentusername);
userref.once("value").then(function(snapshot)
This worked!!!
This should work
var currentusername;
try {
currentusername = sessionStorage.getItem("username");
}
catch(error) {
console.log("shucks " + error);
}
if(currentusername){
firebase.database().ref("users").child(currentusername).once('value').then(function(snap) {
if(snap.val()){
console.log(snap.val().firstname);
}
}, function(error) {
// The Promise was rejected.
console.log('Error: ',error);
});
}

How to check if there's no errors in authentication process in Firebase Web?

I'm new to Web Development, especially to Firebase.
I'm trying to check if there are no errors while creating a user in Firebase Authentication system, so I can put this user into Database.
Here's my code:
function register() {
var firebaseRef = firebase.database().ref();
var shaObj = new jsSHA("SHA-256", "TEXT")
shaObj.update(passwordField.value)
//console.log(hash)
var email = emailField.value
var password = shaObj.getHash("HEX")
if (isBarber != null) {
if (email != "" && password != "") {
firebase.auth().createUserWithEmailAndPassword(email, password).catch(function(error) {
$('#errorMsg').show();
$('#errorMsg').text(error.message);
if (error === null) {
var user = firebase.auth().currentUser;
var userID = user.uid;
firebase.database().ref('users/' + userID).set({
userEmail: email,
userPassword: password,
userIsBarber: isBarber
})
}
});
} else {
alert('Email or password fields are empty')
}
} else {
alert('Select your role')
}
}
createUserWithEmailAndPassword works properly and creates a user, but I don't know how to check if there are no errors so I could add this user to database.
Thanks a lot
You can use then() to action on a successful registration as follows:
firebase.auth().createUserWithEmailAndPassword(email, password).then(function(user) {
//Registration is successful
var user = firebase.auth().currentUser;
var userID = user.uid;
firebase.database().ref('users/' + userID).set({
userEmail: email,
userPassword: password,
userIsBarber: isBarber
})
}).catch(error) {
//Registration unsuccessful
$('#errorMsg').show();
$('#errorMsg').text(error.message);
});

Alloy MVC Framework Titanium Network (Model)

I'm trying to authenticate using the Model in Alloy. I have been trying to figure this problem out since yesterday. If anybody could help me, I'd really appreciate it.
So, I have a view login.xml, then a controller login.js. The login.js contains the following function:
var user = Alloy.Models.user; //my user.js model
function login(e) {
if($.username.value !== '' && $.password.value !== ''){
if(user.login($.username.value, $.password.value)){
Alloy.createController('home').getView().open();
$.login.close();
}
}else{
alert('Username and/or Password required!');
}
}
Then in my user.js model, it's like this:
extendModel : function(Model) {
_.extend(Model.prototype, {
login: function(username, password) {
var first_name, last_name, email;
var _this = this;
var url = 'http://myurl.com/test.php';
var auth = Ti.Network.createHTTPClient({
onerror: function(e){
alert(e.error);
},
onload: function(){
var json = this.responseText;
var response = JSON.parse(json);
if(response.logged == true){
first_name = response.f_name;
last_name = response.l_name;
email = response.email;
_this.set({
loggedIn: 1,
username: email,
realname: first_name + ' ' + last_name,
email: email,
});
_this.save();
}else{
alert(response.message);
}
},
});
auth.open('POST', url);
var params = {
usernames: username,
passwords: password,
};
auth.send(params);
alert(_this.get('email')); //alert email
},
});
When I click on login in login.xml it calls the function login in index.js. So, now my problem is that, when I click the button for the first time, I get an empty alert from alert(_this.get('email')), but then when I click the button the second time, everything works fine, it alerts the email. I have no idea what's going on. Thank you for the help.
I think I figured it out, for people that might stumble upon the same problem. I used callback function to do it.
Refer to this Titanium HTTP Request
Now my user.js looks like this:
extendModel : function(Model) {
_.extend(Model.prototype, {
login: function(username, password, callback) {
var first_name, last_name, email;
var _this = this;
var url = 'http://myurl.com/test.php';
var auth = Ti.Network.createHTTPClient({
onerror: function(e){
alert(e.error);
},
onload: function(){
var json = this.responseText;
var response = JSON.parse(json);
if(response.logged == true){
first_name = response.f_name;
last_name = response.l_name;
email = response.email;
_this.set({
loggedIn: 1,
username: email,
realname: first_name + ' ' + last_name,
email: email,
});
_this.save();
callback(foo); //whatever you want to send
}else{
alert(response.message);
}
},
});
auth.open('POST', url);
var params = {
usernames: username,
passwords: password,
};
auth.send(params);
},
});
And my login.js looks like this:
var user = Alloy.Models.user; //my user.js model
function login(e) {
if($.username.value !== '' && $.password.value !== ''){
var logged_in = user.login($.username.value, $.password.value, function(foo){
if(foo == bar)
call_another_function();
});
}else{
alert('Username and/or Password required!');
}
}
Thanks. I hope this helps.

Categories

Resources