Check whether user is anonymous in AngularFire - angularjs

I have read the document in AngularFire 1 about Authentication. However, I cannot find out how to check whether the current user is anonymous.
Here is what I tried
.controller('IndexCtrl',['$scope','$route','Auth', function($scope,$route,Auth){
//Check whether user is existent
$scope.isExistent = function(){
var isIt = true;
if(firebaseUser.isAnonymous()){
isIt = false;
console.log("is anonyous");
}
return isIt;
};
}]);
Any help would be appreciated.

I know this is very late but the firebase user object has the property isAnonymous within it. Thus calling it as a property instead of a function should do the trick
$scope.isExistent = function(){
var isIt = true;
if(firebaseUser.isAnonymous){
isIt = false;
console.log("is anonyous");
}
return isIt;
};

Related

How can I monitor the value of some scope variables for changes?

I have this code in my appController. The code sets the value of $scope.cursorWait to true when there's an HTTP in progress:
$scope.$on('cfpLoadingBar:started', function (event, data) {
$scope.cursorWait = true;
});
$scope.$on('cfpLoadingBar:completed', function (event, data) {
$scope.cursorWait = false;
});
I also have this in my connect service. The functions get called when the internet is disconnected:
isConnectedHandler = (): void => {
var self = this;
self.$rootScope.connected = true;
self.$rootScope.disconnected = false;
self.connectMessage = null;
self.minutes = 0;
}
isNotConnectedHandler = (): void => {
var retry = 0;
var self = this;
self.$rootScope.connected = false;
self.$rootScope.disconnected = true;
How could I monitor the value of $rootScope.disconnected and cursorWait to then set the value of a rootScope variable waiting to true if either $rootScope.disconnected or cursorWait were true?
Assuming your controller has several ViewModels it would like to monitor, let's say cursorWait and connected for example. In this case, Angular provide you with the watchGroup ability. This way you can monitor several variables and in the case one of them change, you may react accordingaly.
Sample Code (Using Typescript for demonstration)
$scope.$watchGroup([()=> { return this.cursorWait }, ()=> { return this.connected}],
(oldValues, newValues)=> {
/* The callback gets an array of `oldValues` and an array of `newValues`,
the index according to the variables you were watching */
});
For more information, refer to Angular documentation.

Check if a value is present in scope

I have a scope called $scope.activities. Inside that scope are multiple objects. Each object has a string called viewed with the value of check or uncheck. I would like to check if the value uncheck is present in the scope.
I've created this, but it doesn't seem to work.
if (activities.indexOf("uncheck") == -1) {
console.log ('uncheck found')
$scope.newActivities = 'newActivities';
} else {
console.log ('no uncheck found')
}
Because in activities I have two objects, one with the uncheck value, and a object without it.
[{"id":2,", "viewed":"check"}, {"id":3,", "viewed":"uncheck"}]
You've got to loop each object and check the property - you can use Array.some
var hasValue = activities.some(function(obj) { return obj.viewed == "unchecked" });
You have to loop over each object in the array and test if the property "viewed" equal to "unchek"
var activities = [{"id":2, "viewed":"check"}, {"id":3, "viewed":"uncheck"}];
var activities2 = [{"id":2, "viewed":"check"}, {"id":3, "viewed":"check"}];
var check = function(data){
var checked = false;
for(var i in data){
if(data[i].hasOwnProperty("viewed") && (data[i]["viewed"]=="uncheck") ){
checked = true ;
}
}
return checked;
} ;
console.log(check(activities));
console.log(check(activities2));

Getting object or array value for Auth on Firebase

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!

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.

AngularJS: Assign variables to $scope after AJAX call

I am sooo close I can smell the finish line --
When my app starts, I harvest the login information from the user (it's an AngularJS SPA so I can get it easy from spInfoContext) and I check to see if the user is a returning user by searching a list called itiUsers for the userId. If no records are found, I immediately create a new record in itiUsers and then present a form for the new user to enter the information that I can't grab from SharePoint. The record is created properly. When the promise returns, I am trying to populate the $scope.current_user object so that it would be the same as if this were a returning user -- that's so I only have to have one My Preferences form.
However when I log out $scope after the record is created, current_user is empty.
Here's my Controller function (i reduced values for brevity and I tried to bold the problem line):
$.when(SharePointJSOMService.getCurrentUser())
.done(function(jsonObject){
if(jsonObject.d.results.length < 1 || jsonObject.d.results.newUser ){
// new user
$.when(SharePointJSOMService.getLoggedInUser())
.done(function(jsonObject){
$scope.loggedInUser = jsonObject.d;
$scope.isNewUser = true;
$.when(SharePointJSOMService.createNewUser($scope))
.done(function(jsonObject){
**$scope.current_user.DisplayName = $scope.loggedInUser.Title;
console.log($scope);**
})
.fail(function(err){
$scope.prefPane = true;
console.info(JSON.stringify(err));
});
})
.fail(function(err){
$scope.prefPane = true;
console.info(JSON.stringify(err));
});
$scope.prefPane = true; // force preference pane
$scope.taskClose = true;
$scope.$apply();
} else {
// existing user
$scope.isNewUser = false;
$scope.prefPane = false; // hide preference pane
$scope.current_user = jsonObject.d.results[0];
switch($scope.current_user.Role){
case 'USR':
$scope.projectClose = 'true';
break;
case 'PMG':
$scope.projectClose = 'false';
break;
default:
$scope.projectClose = 'true';
break;
} // end switch
$scope.$apply();
} // end if
})
.fail(function(err){
$scope.prefPane = true;
console.info(JSON.stringify(err));
});
It crashes because you are trying to set $scope.current_user.DisplayName after creating a new user but $scope.current_user object is undefined. Try instead:
$scope.current_user = {
DisplayName: $scope.loggedInUser.Title
}

Resources