Firebase tips(Storage rule)

9909 단어 Firebase

FIREBASE TIPS


1. Allow user to be able to upload profile.png in own directory.


storage.rule
service firebase.storage {
  match /b/{bucket}/o {
    match /{allPaths=**} {
      allow read: if request.auth != null;
    }

    match /images/{userId}/profile.png {
      allow read;
      allow write: if request.auth.uid == userId;
    }
  }
}
  • TEST1: UID of [email protected] is eFcFmn2lbqTzXf83vtHPdSCID9W2
  • test1
    <script>
        firebase.initializeApp(config);
        firebase.auth().signInWithEmailAndPassword('[email protected]', 'xxxxx').catch((error) => {
            console.log('code:' + error.code + 'message' + error.message);
        });
    
        firebase.auth().onAuthStateChanged(function (user) {
            if (user) {
                let uid = user.uid;
                console.log('login success');
            } else { }
        });
    
        var storage = firebase.storage();
        function upload() {
            var file = document.getElementById('loadFile').files[0];
            var storageRef = storage.ref('/images/eFcFmn2lbqTzXf83vtHPdSCID9W2/profile.png');
            storageRef.put(file).then(function (snapshot) {
                console.log('Uploaded a blob or file!');
            });
        }
    </script>
    
    result result
  • TEST2: UID of [email protected] is not eFcFmn2lbqTzXf83vtHPdSCID9W2
  • test2
    <script>
        firebase.initializeApp(config);
        firebase.auth().signInWithEmailAndPassword('[email protected]', 'xxxxx').catch((error) => {
            console.log('code:' + error.code + 'message' + error.message);
        });
    
        firebase.auth().onAuthStateChanged(function (user) {
            if (user) {
                let uid = user.uid;
                console.log('login success');
            } else { }
        });
    
        var storage = firebase.storage();
        function upload() {
            var file = document.getElementById('loadFile').files[0];
            var storageRef = storage.ref('/images/eFcFmn2lbqTzXf83vtHPdSCID9W2/profile.png');
            storageRef.put(file).then(function (snapshot) {
                console.log('Uploaded a blob or file!');
            });
        }
    </script>
    
    result

    좋은 웹페이지 즐겨찾기