Getting object or array value for Auth on Firebase - angularjs

I'm using angularfire 1.1.1 to store my apps objects and each object creates associated indexes. So when a user is created, that user is added to the 'users' table and then the users index table gets keyed with the UID and points to the actual user's id.
When the main state is called, I run a checkAuth() method to see if a user is signed in. If so, then I want to assign $rootScope.auth = {id:userID, role: role} etc.
The function works great in my login method but i don't know how to grab the value from my checkAuth() method. I've tried $value on both $firebaseObject and $firebaseArray, also tried to call them with [0] since there is only one id value in the table for each user's uid.
The sloppy regex is for changing the semi-colon from SimpleLogin:47 to SimpleLogin-47 for keying to the index.
Here's the code that doesn't work:
function authCheck(){
var getAuth = $firebaseAuth(Data.ref);
console.log('signed in as', getAuth.$getAuth().uid);
var uid = getAuth.$getAuth().uid.toLowerCase().replace(/'+/g, '').replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "-").replace(/^-+|-+$/g, '');
var userIndexRef = Data.ref.child('index/users/uid/'+uid);
var userIndexArray = $firebaseArray(userIndexRef);
var userIndexObject = $firebaseObject(userIndexRef);
console.log(userIndexArray, userIndexObject);
var realId = '';
angular.forEach(userIndexObject, function(key, id){
realId = id;
$rootScope.auth = realId;
return realId;
});
}
Here's the login code that does work:
function login(email, pass) {
ref.authWithPassword({email:email,password:pass}, function(error, authData){
if (error) {
console.log(error);
} else {
console.log('signed in as',authData.uid);
var uid = authData.uid.toLowerCase().replace(/'+/g, '').replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "-").replace(/^-+|-+$/g, '');
angular.forEach(Data.dataObject.index.users.uid[uid],function(id, key){
$rootScope.role = Data.dataObject.users[id].role;
$rootScope.auth = {authData:authData, id:id, role:Data.dataObject.users[id].role};
});
}
});
}
If anyone sees where I've messed up, I'll be happy to know. Here's the repo https://github.com/irthos/medviz if it helps. Thank you very much!

Related

Cant match users in firebase

I can't randomly get user from firebase
I'm doing dating app with react native and firebase.
Users can log in with google and set their accounts, but I can't match users.
I can pick 1 user but cant display user's data.
I tried:
i tried get all users from firebase realtime database
i can pick 1 user and log user's details but cant display in app
And sometimes user.uid returns null even if i logged in.
function getRandomUser() {
const numberOfUsers = 15;
const randomIndex = Math.floor(Math.random() * numberOfUsers);
var ref = firebase.database().ref("/users/");
ref
.limitToFirst(1)
.once("value")
.then((snapshot) => {
var randomUser = snapshot.val();
console.log(randomUser);
console.log(randomUser.bio);//this is not even display in console
});
}
I believe you should change the way you are referencing your database, so it should be var ref = firebase.database().ref("users"); and not var ref = firebase.database().ref("/users/");.
After that, are some changes related to the random number number and to the comparing issues that you need to perform, so values are returned. Please, give it a try using the below code.
var dbUser = firebase.database();
var refUser = dbUser.ref("<collection>");
refUser.orderByChild("online").equalTo(1).on("value", function(Data){
var numberOfUsers = 15;
var randomIndex = Math.random() * numberOfUsers;
var userIndex = parseInt(randomIndex, 10); //parse the random number from double to integer
var currentIndex = 0;
var BreakException = {};
try
{
Data.forEach(function(snap){
if(currentIndex==userIndex){
var randomUser = snap.val();
//Do something with your random user
throw BreakException;
}
currentIndex++;
});
}
catch(e){
if(e!== BreakException) throw e;
}
While this code is untested, it was based in this successful use case here and I believe should help you. Besides that, you can get another way of returning random users, but with indexes now, by checking this similar case here, with a very complete answer from a Product Lead from Firestore.

realtime firebase database get property name and value on child_changed

I am working on real-time fire-base database.
i have a issue in getting value what is changed in fire-base.
i have client social database inside it posts and then kkkm(this is key) and then different properties and values and what i want is to toggle approval and rejected values like that approval:true but what i get is just true/false not the property name.
toggleCheck = (id) => {
var ref = firebase.database().ref('posts/'+id);
ref.off("child_changed");
var approval;
ref.on("child_changed", function (data) {
approval = data.val();
console.log("=============================");
console.log("The updated approval is " + approval);
});
}
toggleClose = (id) => {
var ref = firebase.database().ref('posts/'+id);
ref.off("child_changed");
var rejected;
ref.on("child_changed", function (data) {
rejected = data.val();
console.log(ref.getKey());
console.log(ref.getValue());
console.log("=============================");
console.log("The updated rejected is " + rejected);
});
}
I'm not 100% sure to understand what you want to do ("toggle approval and rejected values"?) but, based on the code in your question, the following is probably what you are looking for:
var ref = firebase.database().ref('posts/' + id);
ref.on('child_changed', function(data) {
console.log(data.key); // <-- Name of the field/node that was modified
console.log(data.val()); // <-- Value of the field/node that was modified
console.log("The updated" + data.key + " is " + data.val());
});
Explanations:
data is a DataSnapshot which has:
A key property, which is "the key (last part of the path) of the location of this DataSnapshot."
A val() method, which "extracts a JavaScript value from a DataSnapshot."
UPDATE FOLLOWING YOUR COMMENTS
I understand that you want to get both the values of the approval and rejected nodes (fields) when something changes in the post.
Therefore you should use the value event type instead of the child_changed one, as follows:
var ref = firebase.database().ref('posts/' + id);
ref.on('value', function(data) {
var approved = data.val().approved;
var rejected = data.val().rejected;
var object = {'approved': approved, 'rejected': rejected};
//Do whatever you want with the object
console.log(object);
});

Extending $firebaseArray with an extended $firebaseObject

Trying to cut down code repetition, I've set up a $firebaseArray extension as follows:
var listUsersFactory = $firebaseArray.$extend({
$$added: function (snap) {
return new Customer(snap);
},
$$updated: function (snap) {
var c = this.$getRecord(snap.key);
var updated = c.updated(snap);
return updated;
},
});
and the Customer code:
function Customer(snap) {
this.$id = snap.key;
this.updated(snap);
}
Customer.prototype = {
updated: function(snap) {
var oldData = angular.extend({}, this.data);
this.data = snap.val();
// checks and such
}
}
This works wonders when loading, showing and saving a list of customers, and I'm satisfied with it.
Now, the problem lies in retrieving a single customer and its detail page, because the Customer object isn't an extension of $fireObject and is therefore lacking a $save method
Single customer loading:
customersRef.once("value", function(snapshot) {
if(snapshot.child(uuid).exists())
{
customersFactory.customerDetails = new Customer(snapshot.child(uuid));
return deferred.resolve();
}
}
but when I call customersFactory.customerDetails.$save() I get an error
How can I extend my class so that it works for both array and single object uses?
I couldn't find a way to do this, so I ended up using the $firebaseArray and getting single records off that to pass as details, in case anyone's wondering

Invalid Parse.com request

I have been using parse for a while now and I am quite confused by the issue I am having.
Here is one function that I call first:
$scope.followUser = function(usernameToFollow)
{
console.log('ready to follow user: ' + usernameToFollow);
var user = Parse.User.current();
if (user)
{
var FollowUser = Parse.Object.extend('User');
var query = new Parse.Query(FollowUser);
query.equalTo('username', usernameToFollow);
query.find({
success: function(results)
{
var relationToUserPosts = user.relation('followUser');
$scope.userToAdd = results[0];//This is the user I want to add relational data to
relationToUserPosts.add(results[0]);
user.save();
},
error: function(error)
{
alert('Error: ' + error.code + '' + error.message);
}
});
}
else
{
console.log('Need to login a user');
// show the signup or login page
}
};
Next after I call that function I call this function:
$scope.addToFollowers = function()
{
var currUser = Parse.User.current();
console.log($scope.userToAdd);
var followerUser = $scope.userToAdd.relation('followers');
followerUser.add(currUser);
$scope.userToAdd.save();
};
I know for sure the $scope.userToAdd is the user I want, I know the relation I pull from the object is valid its when I try to save this object with $scope.userToAdd.save() is when I get the bad request, with no further information as to why its a bad request. Thank you in advance.
UPDATE:
The first method call has no errors and no bad requests.
Error message:
Well turns out you cannot save a user object unless your are logged in as that user time to find another solution thank you for the help eth3lbert.

issue with return value of service in AngularJS

I'm facing issues in returning data from Angular Service. Below is the service code....
app.service('Data',function(){
var accountList = [];
var currentAccount ='Test1'; //Initialization
var bookmarkAccount = function(accountName){
accountList.push(accountName);
}
var setPassingAccount = function(Account){
console.log('in Service : setting current account value to '+Account);
currentAccount = Account;
}
return{
bookmarkAccount: bookmarkAccount,
setPassingAccount: setPassingAccount,
currentAccount: currentAccount,
accountList: accountList
};
});
I'm able to access all methods/variables from 'Data' service except "currentAccount". Getting empty value, while accessing it from controller. Below is the controller code...
app.controller('BookmarkController',function(Data){
this.accountList = [];
this.accountList = Data.accountList;
this.account = Data.currentAccount; //ISSUE
Console.log('Account list object'+accountList);
Console.log('Current account selected :'+this.account);
}
I'm able to get all values in 'accountList', but getting empty 'currentAccount'. Can anyone please help on this.

Resources