Skip to content

Firestore – Auth

Version 2 – Từ 2019

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {

Khai báo

service cloud.firestore {
  match /databases/{database}/documents {
    // ...
  }
}

service cloud.firestore là để tránh conflict của firestore & cloud storage

match /databases/{database}/documents là match any database in project

5 loại Rules

  • Read :
    • Get : lấy cụ thể /users/1
    • List : query find : /user?name=__
  • Write :
    • Create
    • Update
    • Delete
allow get: if <condition>;
allow list: if <condition>;
allow create: if <condition>;
allow update: if <condition>;
allow delete: if <condition>;

Cấu trúc phân cấp (Nested Level)

Full Path

match /databases/{database}/documents {
    match /cities/{city}/landmarks/{landmark} {
      allow read, write: if <condition>;
    }
}

Nested Path

match /databases/{database}/documents {
    match /cities/{city} {
      match /landmarks/{landmark} {
        allow read, write: if <condition>;
      }
    }
}

– Thừa hưởng parent

Khác với Real-time DB, Auth của Firestore không cascade

Nghĩa là rule apply cho /restaurant sẽ không apply cho /restaurant/review

Wildcard (version 2)

Đỉnh cao

match /{everythingInMyDatabase=**}{
  allow read, write: if request.auth.token.super_admin == true;
}

All Doc

Match any doc from Collection -> Sub-Collection {document=**}

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /cities/{city}/{document=**} {
      allow read, write: if <condition>;
    }
  }
}

Collection Group

Match any doc in Collection Group – Songs

{
  author: "some_auth_id",
  authorname: "some_username",
  content: "I just read a great story.",
  published: false
}
function authorOrPublished() {
      return resource.data.published == true || request.auth.uid == resource.data.author;
}

match /{path=**}/posts/{post} {

  allow list: if authorOrPublished();

  allow get: if authorOrPublished();
}

match /forums/{forumid}/posts/{postid} {
  allow write: if request.auth.uid == resource.data.author;
}

Giống như

var user = firebase.auth().currentUser;

db.collectionGroup("posts").where("author", "==", user.uid).get()

Authentication

match /users/{userId} {
      allow read, update, delete: if request.auth != null && request.auth.uid == userId;
      allow create: if request.auth != null;
}

match /cities/{city} {
      allow create: if request.auth != null && exists(/databases/$(database)/documents/users/$(request.auth.uid))


      allow delete: if request.auth != null && get(/databases/$(database)/documents/users/$(request.auth.uid)).data.admin == true
}

match /some_collection/{document} {
     allow read: if request.auth != null && get(/databases/$(database)/documents/users/$(request.auth.uid)).data.role == "Reader"

Data Validation

match /cities/{city} {
  allow read: if resource.data.visibility == 'public';
}

Truy cập ~ doc khác

Sử dụng get() , getAfter() and exists()

match /cities/{city} {
      allow create: if request.auth != null && exists(/databases/$(database)/documents/users/$(request.auth.uid))


      allow delete: if request.auth != null && get(/databases/$(database)/documents/users/$(request.auth.uid)).data.admin == true
}

Refactor – Sử dụng function

function signedInOrPublic() {
  return request.auth.uid != null || resource.data.visibility == 'public';
}

match /cities/{city} {
  allow read, write: if signedInOrPublic();
}

match /users/{user} {
  allow read, write: if signedInOrPublic();
}

Safe Query

{
  title: "A Great Story",
  content: "Once upon a time...",
  author: "some_auth_id",
  published: false
}
match /stories/{storyid} {
      allow read, write: if request.auth != null && request.auth.uid == resource.data.author;
}

Request Object

Auth : chứa thông tin user đã đăng nhập = firebase auth

•	Request.auth != null
•	Request.auth.uid
•	Request.auth.token.email
•	Request.auth.token.email_verified

Resource : chứa content

resource vs request.resource

  • Request.resouce : là khi client gửi data lên
  • resource : là đã có sẵn

Firebase Auth

Sign up

firebase.auth().createUserWithEmailAndPassword(email, password).catch(function(error) {
  // Handle Errors here.
  var errorCode = error.code;
  var errorMessage = error.message;
  // ...
});

Sign in

firebase.auth().signInWithEmailAndPassword(email, password)

State observer & get user data

firebase.auth().onAuthStateChanged(function(user) {
  if (user) {
    // User is signed in.
    var displayName = user.displayName;
    var email = user.email;
    var emailVerified = user.emailVerified;
    var photoURL = user.photoURL;
    var isAnonymous = user.isAnonymous;
    var uid = user.uid;
    var providerData = user.providerData;
    // ...
  } else {
    // User is signed out.
    // ...
  }
});
Published inFirestore

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *