You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React-Redux版LinkedIn克隆应用Firebase Storage上传权限问题求助

问题

使用React-Redux构建LinkedIn克隆应用,已实现用户发布图文功能,Firebase连接正常、登录功能可用,但发布图片时无法上传至Firebase Storage,控制台报错storage/unauthorized或storage/unknown,对应src/actions/index.js第64行。已正确安装并导入Firebase相关组件(auth、storage、provider等),仅图片上传功能失效。


相关代码

src/actions/index.js

import { auth, provider, storage } from "../firebase";
import db from "../firebase";
import { SET_USER } from "./actionType";
import "firebase/compat/auth";
import "firebase/compat/firestore";
import "firebase/compat/storage";

export const setUser = (payload) => ({
  type: SET_USER,
  user: payload,
});

//Code for Sign-In, User Authentication and Sign-Out functionality

export function postArticleAPI(payload) {
  return (dispatch) => {
    if (payload.image != "") {
      const upload = storage
        .ref(`image/${payload.image.name}`)
        .put(payload.image);
      upload.on(
        "state_changed",
        (snapshot) => {
          const progress =
            (snapshot.bytesTransferred / snapshot.totalBytes) * 100;

          console.log(`Progess: ${progress}%`);
          if (snapshot === `RUNNING`) {
            console.log(`Progress: ${progress}%`);
          }
        },
        (error) => console.log(error.code),                                 //line 64, refer 1st para
        async () => {
          const downloadURL = await upload.snapshot.ref.getDownloadURL();
          db.collection("articles").add({
            actor: {
              description: payload.user.email,
              title: payload.user.displayName,
              date: payload.timestamp,
              image: payload.user.photoURL,
            },
            video: payload.video,
            sharedImg: downloadURL,
            comments: 0,
            description: payload.description,
          });
        }
      );
    }
  };
}

src/components/PostModal.js

import { useState } from "react";
import styled from "styled-components";
import ReactPlayer from "react-player";
import { connect } from "react-redux";
import firebase from "firebase/compat/app";
import "firebase/compat/auth";
import "firebase/compat/firestore";
import "firebase/compat/storage";
import { postArticleAPI } from "../actions";

const PostModal = (props) => {
  const [editorText, setEditorText] = useState("");
  const [shareImage, setShareImage] = useState("");
  const [videoLink, setVideoLink] = useState("");
  const [assetArea, setAssetArea] = useState("");

  const postArticle = (e) => {
    console.log("start");                        //debugging, this message logs in console
    e.preventDefault();
    if (e.target !== e.currentTarget) {
      console.log("insideif");                   //debugging, this message doesn't logs in console
      return;
    }

    const payload = {
      image: shareImage,
      video: videoLink,
      user: props.user,
      description: editorText,
      timestamp: firebase.firestore.Timestamp.now(),
    };

    props.postArticle(payload);
    reset(e);
  };

  return (
    <>
      {props.showModal === "open" && (
        <Container>
          <Content>

            //Fronted for Post Functionality

            <ShareCreation>

            //Fronted for Post Functionality

              <PostButton
                disabled={!editorText ? true : false}
                onClick={(event) => postArticle(event)}
              >
                Post
              </PostButton>
            </ShareCreation>
          </Content>
        </Container>
      )}
    </>
  );
};

//css: styled.divs, styled.buttons, etc.

const mapStateToProps = (state) => {
  return {
    user: state.userState.user,
  };
};

const mapDispatchToProps = (dispatch) => ({
  postArticle: (payload) => dispatch(postArticleAPI(payload)),
});

export default connect(mapStateToProps, mapDispatchToProps)(PostModal);

控制台输出

start                      PostModal.js:34
Progess: 0%                index.js:59
storage/unauthorized       index.js:64

解决方法

1. 修复Firebase Storage权限规则

storage/unauthorized是核心问题,默认规则可能未正确授权认证用户写入:

  • 登录Firebase控制台,进入Storage > 规则页面
  • 测试阶段可临时设置宽松规则(生产环境需严格限制):
rules_version = '2';
service firebase.storage {
  match /b/{bucket}/o {
    match /{allPaths=**} {
      allow read, write: if request.auth != null;
    }
  }
}
  • 生产环境建议添加更严格的权限控制,比如仅允许上传者访问自己的文件:
rules_version = '2';
service firebase.storage {
  match /b/{bucket}/o {
    match /image/{fileName} {
      allow write: if request.auth != null && request.auth.token.email == request.resource.metadata.email;
      allow read: if request.auth != null;
    }
  }
}

同时在上传代码中携带用户邮箱元数据:

const upload = storage
  .ref(`image/${payload.image.name}`)
  .put(payload.image, { metadata: { email: payload.user.email } });

2. 修正上传状态判断逻辑

当前代码中snapshot === 'RUNNING'的判断错误,snapshot是对象,需判断其state属性:

if (snapshot.state === 'running') {
  console.log(`Progress: ${progress}%`);
}

3. 优化空图片边界判断

当前判断payload.image != ""不严谨,用户取消选择图片时shareImage可能为null,修改为:

if (payload.image && payload.image.name) {
  // 执行上传逻辑
}

4. 确认用户认证状态有效性

虽然登录功能正常,但需确保上传时props.user包含有效认证信息,可在postArticle方法中添加日志校验:

console.log("当前认证用户:", props.user);

若用户信息为空,需检查Redux的用户状态同步逻辑是否正常。


内容的提问来源于stack exchange,提问作者him.himanshu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 13:05:26