dstepan dstepan -4 years ago 146
Swift Question

Pattern for Using an Access Code with Firebase

I'm currently using Firebase for my app, and I'd like to make parts of my application to not only require user authorization but to also be private and require a user to input an access code to gain entry.

I've already got the authorization piece working with a few different providers and anonymous authentication. My question is, is there a proper pattern already existing for above functionality? Or do I need to write a separate web service to handle this requirement?

Answer Source

If you want to add security to your database you better check this out the Firebase documentation about security rules

In the database console under the Rules you will find the section to add security to your database. Basically it's a JSON object like this:

{
  "rules": {
    ".read": "auth != null",
    ".write": "auth != null"
  }
}

In the example above I just declare that for the complete database to read and write there should be a logged in user.

In the same way I recommend you to read the auth section of the documentation and how to implement it here.

EDITED

Because the example above wasn't clear enough I made another one in my Firebase database. In this example I have a path https://*****.firebaseio.com/users. In the example below you can see that I assigned true to the .read property and auth != null to the .write property, it means that everyone can read this path but only authenticated users can write in this path.

{
  "rules": {
      "users":{
        ".read": "true",
        ".write": "auth != null"
      }
  }
}

Using the Firebase simulator you can see that read is enable when you are not authenticated. enter image description here

But if I want to write without authenticate myself I got an error. enter image description here

Now if I use authentication in the simulator I can perform a write operation. enter image description here

EDITED VERSION 2 "ACCESS TOKEN"

Ok I see what you mean. I assume you are going to store this "access code" somewhere in your Firebase database. If you want to validate data within the database to allow read or write you can do it as the documentat says here.

{
  "rules": {
    "users": {
      ".read": "root.child('access_token').child(auth.uid).exists()"
    }
  }
}

In the example above I have a path in the database called access_token, in this path I stored a key pair user_uid-accessToken and then using the root property make a query to validate if you have a value for the authenticated user in this path. I'm using the exists() but there are many others methods you can use to make this validation. For example if the access code is hardcoded then you can use the val() method to compare for an exact value.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download