login with mails added to checklist -javascript - javascript

Have a realtime db login auth rules.
When I enter the mails manually, the mails I authorize gain access, there is no problem. Here is code:
{
"rules": {
".read": "
auth.token.email == \"xx#qq.co\"
|| auth.token.email == \"yy.yy#yy.co\"
|| auth.token.email == \"ss#ss.com\"
",
".write": true
}
}
But my idea:
{"emails":{"xx#hotmail.com", "qq#gmail.com"},
{
"rules": {
".read": "auth.token.email == emails",
".write": true
}
and realtime db code screenshot:
any idea this issue?

That second snippet looks like invalid syntax for Firebase security rules, and thus won't work (it actually shouldn't even save when you enter that in the Firebase console).
If you want a dynamic list of user to gain access, the idiomatic way is to store their UIDs in the database and then check against that in your security rules.
So for example, you could have this in the database:
"uidsThatAreAllowedToRead": {
"uid1": true,
"uid2": true,
"uid3": true
}
And then in your read rule check against that with:
".read": "root.child('uidsThatAreAllowedToRead').child(auth.uid).exists()"
You could do the same with email addresses, but you'd have to encode them as keys cannot contain . characters which are required in an email address. The common encoding method is to replace each . with a ,, which conveniently is allowed in the database keys but not in email addresses.

Related

How do I create a record in firebase with a specific users credential?

I have a requirement of an app that has a contact form. I need to add records securely with the realtime database rules set to the uid of a specific user say my creds to prevent someone from adding records to the dB from anywhere but my form.
All the articles I looked talked about firebase in test mode with the rules set as read and write to true but doing so someone can have access to my dB and populate records from anywhere.
Have a look at the Firebase documentation on implementing content-owner only access, which contains these rules for the Realtime Database:
{
"rules": {
"some_path": {
"$uid": {
// Allow only authenticated content owners access to their data
".read": "auth != null && auth.uid == $uid"
".write": "auth != null && auth.uid == $uid"
}
}
}
}
To write to this database, the user would need to be signed in, and then:
firebase.database().ref('some_path').child(firebase.auth().currentUser.uid).set("hello world");

Firebase basic rules issues

I have a firebase realtime database that stores users information. I am creating a dashboard where I can track all of this , but I am having trouble with creating secure rules. I want to be able to read and write on this dashboard but users cannot read the database. I will be the only person on the dashboard since its local. I was thinking of like checking for an api key that I can have in the dashboard but I cannot find any information online. If you have any suggestions please let me know. These are my current rules below. I have it to where nobody can read the database but they can write to it. I want to be able to read the database from the dashboard.
{
"rules": {
".read": "false",
".write": true,
"posts": {
"$uid": {
".write": "!data.exists()"
}
}
}
}
The security rules will depend on what exactly it is that the users can read/write but if you wanted to be the only person who can do either you could set the security rules to something like,
{
"rules": {
"users": {
"$node_with_data": {
".write": "auth.uid === 'enter_your_uid_here_123' ",
".read": "auth.uid === 'enter_your_uid_here_123' "
}
}
}
}
This means that the only person who can read/write to the node specified is the the user with the uid that matches the one you enter. Obviously this would mean the users couldn't write to this node so you'll need to think about what types of users you have and what they're allowed to access.
Here's a useful link Firebase Security Rules
What I did is use firebase Authentication and what I can do is allow only authenticated users through since I don't authenticate anyone or I can only let my Gmail through which works great! Mine looks like this
{
"rules": {
".read": "auth.token.email_verified == true && auth.token.email.matches(/YOUROWNEMAIL/)",
".write": true,
"posts": {
"$uid": {
".write": "!data.exists()" // This makes it so nobody can delete anything
}
}
}
}

Firebase Database to be only accessed by specific domain [duplicate]

I have a small, personal Firebase webapp that uses Firebase Database. I want to secure (lock down) this app to any user from a single, specific domain. I want to authenticate with Google. I'm not clear how to configure the rules to say "only users from a single, specific domain (say #foobar.com) can read and write to this database".
(Part of the issue that I see: it's hard to bootstrap a Database with enough info to make this use case work. I need to know the user's email at the time of authentication, but auth object doesn't contain email. It seems to be a chicken-egg problem, because I need to write Firebase rules that refer to data in the Database, but that data doesn't exist yet because my user can't write to the database.)
If auth had email, then I could write the rules easily.
Thanks in advance!
If you're using the new Firebase this is now possible, since the email is available in the security rules.
In the security rules you can access both the email address and whether it is verified, which makes some great use-cases possible. With these rules for example only an authenticated, verified gmail user can write their profile:
{
"rules": {
".read": "auth != null",
"gmailUsers": {
"$uid": {
".write": "auth.token.email_verified == true &&
auth.token.email.matches(/.*#gmail.com$/)"
}
}
}
}
You can enter these rules in the Firebase Database console of your project.
Here is code working fine with my database , I have set rule that only my company emails can read and write data of my firebase database .
{
"rules": {
".read": "auth.token.email.matches(/.*#yourcompany.com$/)",
".write": "auth.token.email.matches(/.*#yourcompany.com$/)"
}
}
Code which is working for me.
export class AuthenticationService {
user: Observable<firebase.User>;
constructor(public afAuth: AngularFireAuth) {
this.user = afAuth.authState;
}
login(){
var provider = new firebase.auth.GoogleAuthProvider();
provider.setCustomParameters({'hd': '<your domain>'});
this.afAuth.auth.signInWithPopup(provider)
.then(response => {
let token = response.credential.accessToken;
//Your code. Token is now available.
})
}
}
WARNING: do not trust this answer. Just here for discussion.
tldr: I don't think it's possible, without running your own server.
Here's my attempt thus far:
{
"rules": {
".read": "auth.provider === 'google' && root.child('users').child(auth.uid).child('email').val().endsWith('#foobar.com')",
".write": "auth.provider === 'google' && root.child('users').child(auth.uid).child('email').val().endsWith('#foobar.com')",
"users": {
"$user_id": {
".write": "auth.provider === 'google' && $user_id === auth.uid && newData.child('email').val().endsWith('#foobar.com')"
}
}
}
}
I believe the above says "only allow people to create a new user if they are authenticated by Google, are trying to write into the database node for themselve ($user_id === auth.uid) and their email ends in foobar.com".
However, a problem was pointed out: any web client can easily change their email (using the dev console) before the message is sent to Firebase. So we can't trust the user entry's data when stored into Firebase.
I think the only thing we can actually trust is the auth object in the rules. That auth object is populated by Firebase's backend. And, unfortunately, the auth object does not include the email address.
For the record, I am inserting my user this way:
function authDataCallback(authData) {
if (authData) {
console.log("User " + authData.uid + " is logged in with " + authData.provider + " and has displayName " + authData.google.displayName);
// save the user's profile into the database so we can list users,
// use them in Security and Firebase Rules, and show profiles
ref.child("users").child(authData.uid).set({
provider: authData.provider,
name: getName(authData),
email: authData.google.email
});
As you might be able to imagine, a determined user could overwrite the value of email here (by using the DevTools, for examples).
This should work for anyone looking for a Cloud Firestore option, inspired by Frank van Puffelen's answer.
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
// Allows all users to access data if they're signed into the app with an email of the domain "company.com"
allow read, write: if request.auth.uid != null && request.auth.token.email.matches(".*#company.com$");
}
}
}
For anyone really not wanting to have unverified accounts logging in. Maybe dirty, but very effective.
This is my workaround (Angular app):
this.userService.login(this.email.value, this.password.value).then(data => {
if (data.user.emailVerified === true) {
//user is allowed
} else {
//user not allowed, log them out immediatly
this.userService.logout();
}
}).catch(error => console.log(error));

Firebase Database Rules for multi-update transactions

I’m trying to create security rules for the “Save data as transactions” blogging app example from the Firebase guide.
The user can increase or decrease the star count for a post, having his own UID being included or removed from the node at the same time.
I’ve written the following rules:
(I removed the rules for the counter increase/decrease since they are out of the scope of the question)
“stars”: {
".read": true,
"$postId”: {
".write": "auth != null && (newData.child('users').child(auth.uid).exists() || data.child('users').child(auth.uid).exists())",
"users": {
"$userId": {
".validate": "$userId === auth.uid"
}
}
}
}
And an exemple of a stars node:
“stars”: {
“postId1”: {
starCount: 2,
"users": {
“userId1”: true,
“userId2”: true
}
}
}
The rules work fine for adding an user to the “users” node, but a problem arises when removing.
It’s possible for a mean-spirited user to remove any other user from the “users” node, just update it with a empty node. Or a node with all the users from before, minus one he chose to remove.
The “.validate” rule ("$userId === auth.uid") does not work for a empty node being submited and I can't write a rule that checks if all the users that were in the database before the update are still there after.
The way I’d solve the problem if I wasn’t using transactions was to to move the “.write” rule to under “$userId”, limiting the uptate for only one user at a time and only with the same UID as the logged user.
Something like:
“stars”: {
".read": true,
"$postId”: {
"users": {
"$userId": {
".write": "auth != null && $userId === auth.uid"
}
}
}
"starCount": {
".write": true
}
But since I’m doing the database update using transactions I need the “.write” rule under the "$postId”, permitting the update of the “users” node and the “starCount” node at the same time. Something that would not be possible in my last exemple (no “.write” rule under "$postId”).
So it seem like a Catch-22. Or I use transactions but I’m not able to secure the starCount with rules, or I do it as a normal multi-update but loose the concurrency benefits for increasing the counter.
How can I correctly secure the “Save data as transactions” blogging app exemple?

Unique IP write permissions Firebase collection

Let's say I have a collection of articles:
https://example.firebaseio.com/articles/$key
And I want to add a viewCounter and currentUsersCounter children to articles.
https://example.firebaseio.com/articles/$key/viewCounter
https://example.firebaseio.com/articles/$key/currentUsersCounter
I execute a function anytime a user has scrolled into the next article:
var currentArticle = function(key){
//key == index of the article
//This is where I want to increment the `viewCounter` and `currentUsersCounter`
}
Obviously I don't want anyone writing to anything more then those two children.
How do I expand on my security rules which currently (black-lists all writes) to white-listing writes only for these specific collections?
How would I limit writes to unique IP addresses in my security rules for these white-listed collections? (if possible)
Currently black-listing all writes:
{
"rules": {
".read": true,
".write": "auth.email == 'example#gmail.com'"
}
}
You can't do this in a way that will protect the integrity of the data (i.e. ensuring that the counts are actually accurate), since if you grant write access to those fields a client can write whatever value it wants to it.
You can, however, provide granular read/write access for only those specific children by using variables in your security rules:
{
"articles": {
"$key": {
"viewCounter": {
".write": true,
".validate": "newData.isNumber() && newData.val() == data.val() + 1"
},
"$other": {
".write": "auth.email == 'example#gmail.com'"
}
}
}
}
It is not possible to do any filtering based on IP addresses. You'll want to use a secret from trusted server code to do that as suggested in the comment.

Categories