Prevent duplicate users with Firebase Database, Swift 3 - ios

I try to prevent the creation of already existing usernames.
This is my code where I upload usernames to the database:
ref?.child("users").child(FIRAuth.auth()!.currentUser!.uid).child("username").setValue(self.createUserName.text)
And this is the code where I try to get if the username already exists or not
ref?.child("users")
.queryOrdered(byChild: "username")
.queryEqual(toValue: self.createUserName.text?.uppercased())
.observeSingleEvent(of: .value, with: { (snapshot) in
if !snapshot.exists() {
print("😍")
}
}) { error in
print("👾")
}
The database looks like this
Database_App {
users {
-3bSRmS4PHXUwsr7XbMBwgPozNfK2 {
username: "sebas.varela"
}
}
}
And appear this line in the console:
Consider adding ".indexOn": "username" at /users to your security rules for better performance
The problem is that I always get 😍. What is the problem with this?

You can only query for values that are at a directly under the reference you query at. For your case that would be with a data model like:
Database_App {
users {
-3bSRmS4PHXUwsr7XbMBwgPozNfK2: "sebas.varela"
}
}
This will work in your code, but is hard to get secure and performant. The more common approach is to work with a extra node where you map user names to uids:
Database_App {
userNames {
"sebas,varela": "-3bSRmS4PHXUwsr7XbMBwgPozNfK2"
}
}
In this case the node essentially allows a user to claim their name. The advantage of this system is that the keys are automatically guaranteed to be unique on the server, no client-side code needed for that part.
You will want to:
add security rules that ensure a user can only claim a username that hasn't been claimed yet
also in these security rules allow a user to release their claim on a username
add client-side code to handle conflicts in a nicer way than the default "permission denied" error you'll get from the server

Related

Firebase realtime database - Wildcard rules

I'm a bit confused about firebase rules. This is my realtime database. Each node inside "1" is created using the firebase unique id of the user. And in the user's node there is a list of objects.
The objective is for the user to be able to create this node if it doesn't exist, and allow the user to read/write only inside this node.
I tried this but it doesn't work. I get permission error.
{
"rules": {
"1": {
"$key": {
".read": "auth != null && auth.uid == $key",
".write": "auth != null && auth.uid == $key"
}
}
}
}
Note: In the future there will be other parent nodes ("2","3" etc) So it is important to keep the "1". Also in case it matters I am using firebase anonymous sign in.
I appreciate the help.
UPDATE:
I retrieve the installationId like this:
Task<String> getIdTask = FirebaseInstallations.getInstance().getId()
and access the database like this:
FirebaseDatabase.getInstance()
.getReference()
.child("1")
.child(installationId)
Trying to access the database using above code gives this:
Listen at /1/cKYZwWrlRmSof79rtfuX82 failed: DatabaseError: Permission denied
SOLUTION:
I just realized the magnitude of my mistake. To retrieve the userId I was using
FirebaseInstallations.getInstance().getId()
instead of this which is what firebase sees as userId:
FirebaseAuth.getInstance().getCurrentUser().getUid();
Using the later one solved the issue.
Unless you'd add another node, that actually links the UID with your user ID, how shall it know about it? I'd suggest to reconsider the structure and get rid of that superfluous node altogether; just use the UID. It's not that it wouldn't be possible, to lookup values by UID ... but it might be an unfortunate database design, which ignores the given environment.

Firebase Auth Database permissions by 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));

How to write a security rule to allow read without using auth variable

I am trying to write Security rules, but I am bit confused on writing it. For my case I am not authenticating the users using Firebase, but I have node in database which has child named by usernames. I am trying to achieve logic like this: for any child of this node if value is true then he can move on further or else not. Here is my sample node
"Customers":{
"John":"true",
"Jack":"false"
}
"Messages":{
"Message1":{
....
},
},
And here is my rules node where I am confused.I have tried using "$" wild card variable but getting error that variable is unknown.
"rules":{
"Messages":{
".read":"root.child('Customers').child($name).val()===true",
".write":"root.child('Customers').child($name).val()===true"
}
}
I think the "$" variable can't be used this way. So how should I do this?
How do you decide which user to check for value? You must have a value for comparison. If you want a logic like users can see their own messages, you should add an Username field under messages node. Like;
"Messages":{
"Message1":{
"John": {
},
....
},
}
And with this field you can do this;
"rules":{
"Messages":{
"$userId" : {
".read":"root.child('Customers').child($userId).val()===true",
".write":"root.child('Customers').child($userId).val()===true"
}
}
}

When to use uid and when to use $id in angularfire

$id The key where this record is stored. The same as obj.$ref().key
To get the id of an item in a $firebaseArray within ng-repeat, call $id on that item.
These two are from the angular fire reference:
https://github.com/firebase/angularfire/blob/master/docs/reference.md
What I understand is if there is firebase object created with :
var object = $firebaseObject(objectRef);
then I can use uid always.
uid : object.uid
But I saw examples where the firebase auth user is used with $id.
return Auth.$requireSignIn().then(function (firebaseUser) {
return Users.getProfile(firebaseUser.uid).$loaded().then(function (profile) {
**profile.uid or profile.$id here**
Also is it possible the object to have uid but not to have $id (obj.$ref().key). Aren't they the same thing? Does the object have to be loaded first with $loaded() to use $id or uid?
Regards
You seem to be confusing two concepts:
the object.$id of an AngularFire object contains the key of that object in the Firebase Database.
a firebaseUser.uid in Firebase terms is the identification of a Firebase Authentication user.
It is common to store your Firebase Authentication users in the database under their uid, in which case user.$id would be their uid. But they are still inherently different things.
Users
uid1
displayName: "makkasi"
uid2
displayName: "Frank van Puffelen"
So if you we look at the code snippet you shared:
return Auth.$requireSignIn().then(function (firebaseUser) {
return Users.getProfile(firebaseUser.uid).$loaded().then(function (profile) {
The first line requires that the user is signed-in; only then will it execute the next line with the firebaseUser that was signed in. This is a regular JavaScript object (firebase.User), not an AngularFire $firebaseObject.
The second line then uses the firebaseUser.uid property (the identification of that user) to load the user's profile from the database into an AngularFire $firebaseObject. Once that profile is loaded, it executes the third line.
If the users are stored in the database under their uid, at this stage profile.$id and firebaseUser.uid will be the same value.

Using a JSON user object for Authentication in AngularJS

So I've got an question about authentication and have been wondering how other people might handle this situation. I'm currently running an Angular app that is built on a Rails API.
So far for authentication I have a form that does a post to the Rails side which logs the user in and then sends them back to the Angular app on success. Once the cookie is set and the user is logged in, I'm able to access a user.json file which contains all the User information one might expect (Id, username, roles, rights, etc). Since verification all happens on Rails, if the user logs out then this information is removed. So the two states look like so...
Logged in
{
id: 99384,
name: "Username",
url: "//www.test.com/profiles/Username",
timezone: null,
rights: [ ],
roles: [
"admin"
],
}
Logged out
{
error: "You need to login or join before continuing."
}
So far I've seen all these millions of different ways to do auth for Angular, but it seems like nothing fits this type of method. So my question is, since the server is handling all of the verification, is there a way to just check if they user.json file is empty (displaying the error message) and if it is send the Angular app to the Rails login page? Is there really any point messing with Cookies, Tokens, etc when I can base it all on the JSON file?
You are already using cookies - the server is setting them. What you have done is a fairly standard way of doing things.
To check the json file, you can do something like this stub shows in your controller:
app.controller('AppControl', function($scope, $http, $location){
// Get the JSON file.
$http.get('/path/to/json/file')
.then(response){
if(response.data.error){
// redirect to login
$location.path('login');
}
else{
$scope.user = response.data;
// your app code here.
}
})
.catch(function (error){
// unable to reach the json file - handle this.
});
});
Of course, you should really move this out into a service so you can re-use it, and also cache the data, rather than getting the user every time you change route/page, but this gives you a vague idea.
EDIT Example factory:
.factory('User', function( $http ){
// Create a user object - this is ultimately what the factory will return.
// it's a singleton, so there will only ever by one instance of it.
var user = {};
// NOTE: I am assigning the "then" function of the login promise to
// "whenLoggedIn" - your controller code is then very easy to read.
user.whenLoggedIn = $http.get('user.json')
.then(function(response){
// Check to see if there is an error.
if (response.data.error !== undefined) {
// You could be more thorough with this check to determine the
// correct action (examine the error)
user.loggedIn = false;
}
else {
// the user is logged in
user.loggedIn = true;
user.details = response.data;
return user;
}
}).then; // <-- make sure you understand why that .then is there.
return user;
})
Usage in the controller
.controller('ExampleController', function($scope, User){
// It's handy to have the user on the scope - you can use it in your markup
// like I have with ng-show on index.html.
$scope.User = User;
// Do stuff only if the user is loggedin.
// See how neat this is because of the use of the .then function
User.whenLoggedIn( function (user){
console.log(user.details.name + " is logged in");
});
});
Because it's on the scope, we can do this in the html:
<body ng-controller="ExampleController">
<h1 ng-show="User.loggedIn == null">Logging in..</h1>
<h1 ng-show="User.loggedIn == true">Logged in as {{ User.details.name }}</h1>
<h1 ng-show="User.loggedIn == false">Not logged in</h1>
</body>
Here is an example on plunker where this is working.
Note the following:
If the user is/was already logged in, when you inject the service in the future, it won't check the file again. You could create other methods on the service that would re-check the file, and also log the user out, back in, etc. I will leave that up to you.
There are other ways to do this - this is just one possible option!
This might be obvious, but it's always worth saying. You need to primarily handle authentication and security on the server side. The client side is just user experience, and makes sure the user doesn't see confusing or conflicting screens.

Resources