Skip to content

Instantly share code, notes, and snippets.

@iamtylerd
Last active August 4, 2016 16:42
Show Gist options
  • Save iamtylerd/44b48aab29304eff34c6e2027e8e6d83 to your computer and use it in GitHub Desktop.
Save iamtylerd/44b48aab29304eff34c6e2027e8e6d83 to your computer and use it in GitHub Desktop.
Firebase Auth Rules

Rules

This is not a full proof way to validate but it will ensure that only a specific UID can. Make sure that you install via Bower angular-local-storage

  1. Link it in the HTML
  2. Add 'LocalStorageModule' to your App (dependency)
  3. Pass 'localStorageService' to any controllers that need to get the user
  4. set let currentUser = localStorageService.get("currentUser"); in the controller.
  • Local Storage is used to cache the user locally since Firebase does not keep them logged in on a refresh

My rules copied from Firebase.

{
    "rules": {
        ".read": true,
        "post": {
          ".indexOn": "date", 
          	"$post": {
              ".write": "auth.uid !== null && newData.child('uid').val() == 'SUPER_SECRET_KEY'  || data.child('uid').val() == 'SUPER_SECRET_KEY'"
            }
        },
        "users": {
          ".indexOn": "uid", 
          		"$uid": {
         		}
        }
    }
}

The first issue we will tackle is "auth.uid !== null" This is very simple form of auth, but it will ensure a user is logged in.

  1. In the factory that you are making a post/put add the following.
  2. 'localStorageService' as an argument to the factory
  3. let currentUser = localStorageService.get("currentUser") in the factory
  4. In the post function let accessToken = currentUser.stsTokenManager.accessToken (This needs to be in each post as the access token has a timer / changes)
  5. In the http request you will need to add ?auth=${accessToken}. Here is what my string looks like relative to my data $http.post(`${FirebaseURL}post.json?auth=${accessToken}` * I am using $http.post as my intial (newData) post to Firebase.

The UID check is relatively simple. You can set your uid to the object by referrencing the currentUser we defined earlier.

  1. In the data you are posting to firebase be sure to include uid: currentUser.uid
  2. In the data you are "putting" also make sure it includes a uid: currentUser.uid
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment