User auth in ionic + firebase

My goal in my side project is to set up an authentication system where users are able to log in with firebase, and also set up permissions so that they are able to edit their own wallets, but only view other peoples wallets. In order to set this up, I tapped into firebase’s authentication methods.

Useful firebase functions:

createUser()  -> creates a user based on email and password.
authWithPassword() -> logs a user in with email,password.
getAuth() -> shows the currently logged in user.
unAuth() -> logs out current logged in user.

First of all, inject :

$firebaseArray,$firebaseObject

Into your login controller. For user creation, you need to create a firebase ref, than createUser function to create a user, than wait for success or failure.

var ref = new Firebase(“https://my-firebase.com");
ref.createUser({
email : email,
password : password
},

In terms of logging in an existing user, you can use a built in function: authWithPassword:

ref.authWithPassword({
email : email,
password : password

In order to show which user is currently logged in you can getAuth():

ref.getAuth();

Which returns an object showing information on the currently authenticated user.

For logging out you can use the unAuth() function:

ref.unauth();

In terms of setting up user permissions, the current strategy that I’ve decided on has been to add a UID field to each item that a user creates, as a result of this action, if a user wants to edit an item, the controller will first check to see if the current logged in user’s id is equal to the item’s id.

 $scope.wallet = $firebaseObject(galRef);
 $scope.wallet.$loaded().then(function() {
$scope.oid = $scope.wallet.uid;
if($scope.oid === $scope.uid) {
$state.go(‘edit’, { “id”: $scope.id});
}
else {
console.log(‘incorrect user’);
}});

In firebase, one tricky thing is that I have to use: $loaded() on my ref if I want to get back data about a specific field, otherwise it doesn’t return the fetched data.