Firebase Storage仅允许认证用户读写的规则及JS代码实现
好的,我来帮你搞定这个需求!要实现仅认证用户才能上传和下载Firebase Storage文件,你需要在JavaScript代码中先确保用户完成身份认证,然后在操作存储时结合认证状态做检查,下面是具体步骤和代码示例:
1. 先集成Firebase身份认证
首先得让用户能登录,Firebase提供了多种认证方式(邮箱密码、Google登录等),这里给你两个常用的示例:
邮箱密码登录示例
// 处理用户登录 function handleLogin(email, password) { firebase.auth().signInWithEmailAndPassword(email, password) .then((userCredential) => { // 登录成功,userCredential.user就是当前认证用户 console.log("用户登录成功:", userCredential.user.email); // 这里可以触发上传/下载操作,或者更新UI }) .catch((error) => { console.error("登录失败:", error.message); alert(`登录出错:${error.message}`); }); } // 调用示例:比如从登录表单获取邮箱密码 document.getElementById('login-btn').addEventListener('click', () => { const email = document.getElementById('email-input').value; const password = document.getElementById('password-input').value; handleLogin(email, password); });
Google登录示例
// 初始化Google登录提供者 const googleProvider = new firebase.auth.GoogleAuthProvider(); // 处理Google登录 function handleGoogleLogin() { firebase.auth().signInWithPopup(googleProvider) .then((result) => { console.log("Google登录成功:", result.user.displayName); }) .catch((error) => { console.error("Google登录失败:", error.message); }); } // 绑定到按钮点击事件 document.getElementById('google-login-btn').addEventListener('click', handleGoogleLogin);
2. 带认证检查的上传代码
修改你的上传逻辑,先确认用户已认证再执行上传,避免无效请求:
// 封装上传函数 function uploadToNurseFolder(file) { // 检查当前是否有已认证用户 const currentUser = firebase.auth().currentUser; if (!currentUser) { alert("请先登录后再上传文件!"); console.error("未检测到已登录用户"); return; } // 创建存储引用 const storageRef = firebase.storage().ref(`Nurse/${file.name}`); // 开始上传 const uploadTask = storageRef.put(file); // 监听上传状态(进度、完成、错误) uploadTask.on('state_changed', (snapshot) => { // 实时显示上传进度 const progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100; console.log(`上传进度:${Math.round(progress)}%`); document.getElementById('upload-progress').textContent = `上传中:${Math.round(progress)}%`; }, (error) => { // 上传失败处理 console.error("上传出错:", error); alert(`上传失败:${error.message}`); }, () => { // 上传完成,获取文件下载链接 uploadTask.snapshot.ref.getDownloadURL().then((downloadURL) => { console.log("文件上传完成,下载链接:", downloadURL); alert("文件上传成功!"); // 可以把下载链接保存到Firestore或展示给用户 }); } ); } // 绑定文件选择事件 document.getElementById('file-upload-input').addEventListener('change', (e) => { const selectedFile = e.target.files[0]; if (selectedFile) { uploadToNurseFolder(selectedFile); } });
3. 带认证检查的下载代码
下载前同样要验证用户身份,再执行下载操作:
// 封装下载函数 function downloadFromNurseFolder(fileName) { const currentUser = firebase.auth().currentUser; if (!currentUser) { alert("请先登录后再下载文件!"); console.error("未检测到已登录用户"); return; } const storageRef = firebase.storage().ref(`Nurse/${fileName}`); // 获取文件下载链接 storageRef.getDownloadURL() .then((downloadURL) => { // 创建临时a标签触发下载 const downloadLink = document.createElement('a'); downloadLink.href = downloadURL; downloadLink.download = fileName; document.body.appendChild(downloadLink); downloadLink.click(); document.body.removeChild(downloadLink); console.log("文件开始下载"); }) .catch((error) => { console.error("下载出错:", error); // 根据错误码针对性提示 switch(error.code) { case 'storage/object-not-found': alert("该文件不存在"); break; case 'storage/unauthorized': alert("你没有权限下载此文件"); break; default: alert("下载失败,请稍后重试"); } }); } // 调用示例:点击按钮下载指定文件 document.getElementById('download-btn').addEventListener('click', () => { const targetFileName = "example-report.pdf"; // 替换为实际文件名 downloadFromNurseFolder(targetFileName); });
4. 监听认证状态变化(推荐)
可以实时监听用户登录/登出状态,动态更新UI(比如显示/隐藏上传下载按钮):
firebase.auth().onAuthStateChanged((user) => { const uploadSection = document.getElementById('upload-section'); const downloadSection = document.getElementById('download-section'); const loginSection = document.getElementById('login-section'); if (user) { // 用户已登录,显示操作区域,隐藏登录区域 uploadSection.style.display = 'block'; downloadSection.style.display = 'block'; loginSection.style.display = 'none'; console.log("当前登录用户:", user.email); } else { // 用户未登录,隐藏操作区域,显示登录区域 uploadSection.style.display = 'none'; downloadSection.style.display = 'none'; loginSection.style.display = 'block'; console.log("用户已登出"); } });
内容的提问来源于stack exchange,提问作者Pradeep Chagarlamudi
相关产品推荐
相关产品推荐

