How can i restrict access to my firebase so that only I - the owner can access it - firebase

I find my self very confused.
My task is very simple, i want to use Firebase with node.js so that only i will be able to access the base.
Usually services gives a sort of a key so that only the owner can login to the base.
Why isn't this possible? I don't need any authentication for users in my case, so i find the documentation very confusing since i don't need any authentication except for not allowing anyone else than me to access the base.
This is not supposed to be done via a 3rd party provider, this should be allowed directly from your service.
Please help.

Ok. so i managed to find the solution.
In you account you have the tab security rules which you should change to:
{
"rules": {
".read": false,
".write": false
}
}
Now go to the tab Secrets and you will find your auth key.
Now in the node.js code do:
var dataRef = new Firebase("https://<YOUR-FIREBASE>.firebaseio.com/");
// Log me in.
dataRef.auth(AUTH_TOKEN, function(error) {
if(error) {
console.log("Login Failed!", error);
} else {
console.log("Login Succeeded!");
}
});
This is confused me a little since they are talking about users, but i didn't think of my self (owner) as a user accessing the base.

Related

Authorize access to write and delete only if the user knows the node - Rules Firebase

I face an issue : I want the user of my web program to write and delete data in firebase only if he knows where it is and I don't understand what rules have to apply to that.
For instance, my user has an id which is '785475' and I want to only give him access to '/data/785475'. How do I do that please?
Do I have to use authentification?
Thanks in advance and please have a nice day!
In Firebase security rules permission cascades. So in your model and requirement, it is important that the user doesn't have read access to /data, as that means they could read /data and all nodes under it.
To the trick is to only grant them access to the individual child nodes of /data:
{
"rules": {
"data": {
"$any": {
".write": true
}
}
}
}
With the above nodes, a user can delete any existing node that the know the key of, but they can't read (or query) the entire /data node to determine those keys.
To only allow them to overwrite existing data, and not create any new nodes, you can do:
{
"rules": {
"data": {
"$any": {
".write": "data.exists()"
}
}
}
}
For more on this, and other examples, check out the Firebase documentation on new vs existing data.

How to check Item exists in Firebase Database? - react-native-firebase

Currently, I am using https://github.com/invertase/react-native-firebase for my project. I have a custom database for users and I want to check if the user exists or not by email.
Here is a screenshot of the database:
Here's a generic firebase method but you may need to reconfigure the method to suit your data structure. Please refer to the official docs if you wish to know more.
firebase.database()
.ref(`/users`)
.orderByChild("email")
.equalTo(email)
.once("value")
.then(snapshot => {
if (snapshot.val()) {
// data exist, do something else
}
})
You can also query the registration status with hasChild method. Refer to your root path and query with .once and check the result returned.
export function checkUserExist(email) {
return(dispatch) => {
firebase.database().ref(`/ExistingUser/`)
.once('value', snapshot => {
if(snapshot.hasChild(email)) {
dispatch({
type: FIREBASE_USER_EXISTED
});
} else {
dispatch({
type: FIREBASE_USER_NOT_EXISTED,
});
}
});
}
}
Another preferred method would be using the fetchProvidersForEmail method provided by Firebase. It takes an email and returns a promise that resolves with the list of providers linked to that email if it is already registered, refer here.
Is there a good reason to store users credential in your database? In my daily practice, I would use the createUserWithEmailAndPassword provided by Firebase for security purposes, refer here. Just make sure rules are defined properly to prevent unauthorized access.

Restrict Firebase users by email

I have a client that would like to be able to make a list of restricted emails that can access the data. So anyone else coming to the app can't read/write any data at all ( ideally can't even log in but I don't think that's possible with Firebase? ). Any ideas on how to go about this? I had thought of having an array of accepted emails and checking whether their email existed in the security rules but that didn't seem to work. I had the following in the database:
"validEmails": ["test#test.com"]
and then in the security rules:
".read": "root.child('validEmails').val().indexOf(auth.token.email) > -1"
But it looks like you can't use indexOf in those security rules.
Maybe I need to have a list of acceptable emails, and then when a user signs up it checks whether they're in that list and adds their UID to an accepted list? I guess I could do this through a cloud function or something?
Any help would be much appreciated.
Cheers
Have the list of allowed user's emails in the database:
"whitelist": {
"fred#gmail%2Ecom": true,
"barney#aol%2Ecom": true
}
Since periods are not allowed in keys, you need to escape strings with periods before storing them.
Then in the database rules:
{
"rules": {
"whitelist": {
".read": false,
".write": false
},
".read": "root.child('whitelist').child(auth.token.email.replace('.', '%2E')).exists()",
".write": "root.child('whitelist').child(auth.token.email.replace('.', '%2E')).exists()"
}
}
User's email is accessible via auth.token.email. You need to escape the dots (. -> %2E) and check if the key exists on the whitelist.
These rules don't allow anyone read or write access to the /whitelist section of the database. Modification is only possible via firebase console.
Thanks guys, what I ended up doing was having a list of acceptable emails:
{
"validEmails": ["test#test.com"],
"validUsers": {}
}
and then have a cloud function run to check when a user signed up if their email was in the valid email list. If it was then it added them to the valid users list and if not it deleted the newly created user. I also set up data rules so that only users within validUsers could access the data.
The front-end then handled the redirection etc for invalid users.
Once you enable the authentication module of Firebase I believe you can't restrict it to email addresses or domains. However you could secure your database another way. If your users are already registered and you know their uid, then you can restrict read and write access based on these.
Lets pretend you have an acl object in the database, you can list the users and their uid with their read/write permissions.
These rules will check each request and only allow authorised users to access the data.
{
"acl": {
[
{
"uid: "abc123"
"canRead": true,
"canWrite": true
},
{
"uid": "def456",
"canRead": true,
"canWrite": false
}
},
"secure": {
".read": { root.child('acl').child(auth.uid).child('canRead').val() == true }
".write": { root.child('acl').child(auth.uid).child('canWrite').val() == true }
}
}

Publishing different data for different users

I'm trying to publish all users to admins only but ommitting certain data (In this case an API key which is supposed to be "private" to each user, I realize that the admin can most likely check the database but let's ignore the security implications for now).
So the basic idea is that a user can see his own profile completely and no one else. An admin can see his own complete profile and a censored version of all other user's profiles. For this I have the following publish code:
Meteor.publish('currentUser', function() {
return Meteor.users.find({_id: this.userId}, {fields: {'profile.apiKey': true}});
});
Meteor.publish('allUsers', function() {
var currentUser = Meteor.users.findOne(this.userId);
return currentUser && currentUser.profile.admin ?
Meteor.users.find({}, {sort: ['username', 'asc'], fields: {'profile.apiKey': false}}) : null;
});
The problem is that the apiKey field doesn't get published after logging in. Ie. if I simply login as an admin the admin's apiKey won't be available until the page is reloaded. Removing the restriction from the 'allUsers' publish function solves the issue so it must have something to do with this. Is there any way to force Meteor to reload the subscriptions after a login?

Basic user authentication with records in AngularFire

Having spent literally days trying the different, various recommended ways to do this, I've landed on what I think is the most simple and promising. Also thanks to the kind gents from this SO question: Get the index ID of an item in Firebase AngularFire
Curent setup
Users can log in with email and social networks, so when they create a record, it saves the userId as a sort of foreign key.
Good so far. But I want to create a rule so twitter2934392 cannot read facebook63203497's records.
Off to the security panel
Match the IDs on the backend
Unfortunately, the docs are inconsistent with the method from is firebase user id unique per provider (facebook, twitter, password) which suggest appending the social network to the ID. The docs expect you to create a different rule for each of the login method's ids. Why anyone using >1 login method would want to do that is beyond me.
(From: https://www.firebase.com/docs/security/rule-expressions/auth.html)
So I'll try to match the concatenated auth.provider with auth.id to the record in userId for the respective registry item.
According to the API, this should be as easy as
In my case using $registry instead of $user of course.
{
"rules": {
".read": true,
".write": true,
"registry": {
"$registry": {
".read": "$registry == auth.id"
}
}
}
}
But that won't work, because (see the first image above), AngularFire sets each record under an index value. In the image above, it's 0. Here's where things get complicated.
Also, I can't test anything in the simulator, as I cannot edit {some: 'json'} To even authenticate. The input box rejects any input.
My best guess is the following.
{
"rules": {
".write": true,
"registry": {
"$registry": {
".read": "data.child('userId').val() == (auth.provider + auth.id)"
}
}
}
}
Which both throws authentication errors and simultaneously grants full read access to all users. I'm losing my mind. What am I supposed to do here?
I don't think you want to store user-specific data under a non-user-specific index. Instead of push()ing to your firebase reference, store the user data behind a meaningful key.
e.g.
auth.createUser(email, password, function(error, user) {
if (!error) {
usersRef.child(user.id).set(stuff);
}
});
Now you can actually fetch user data based on who is authenticated.
The custom Auth in the forge's simulator isn't the greatest but if you hit the tab key after selecting the input, it lets you paste or edit the field. At which point you can add {"provider":"facebook","id":"63203497"} or {"provider":"twitter","id":"2934392"} and hopefully get some useful debug out of it.
Assuming your firebase is something like:
{"registry":{
"0":{
"id":"abbacadaba123",
"index":"0",
"name":"New Device",
"userId":"facebook63203497"},
"1":{
"id":"adaba123",
"index":"1",
"name":"Other Device",
"userId":"twitter2934392"}
}
}
This may work for security rules:
{
"rules": {
"registry":{
"$registryId":{
".read":"data.child('userId').val() === (auth.provider + auth.id)",
".write":"(data.child('userId').val() === (auth.provider + auth.id))||(auth != null && !data.exists())",
".validate": "newData.hasChildren(['id', 'index', 'name', 'userId'])",
"id": {
".validate":"newData.isString()"
},
"index": {
".validate":"newData.isNumber()"
},
"name": {
".validate":"newData.isString() && newData.val().length >= 1"
},
"userId": {
".validate":"newData.val() === (auth.provider + auth.id)"
}
}
}
}
}
Your read rule tested as expected. The facebook user read-tests true on registry 0 and false on 1. The twitter user is false on 0 and true on 1.
I did a couple quick tests on the .write and .validate rules and they seem to work.
Hope this helps at least rule out the firebase security rules portion of things, so you can focus on the AngularFire binding part.

Resources