【发布时间】:2022-10-25 15:51:41
【问题描述】:
我在我的 React 应用程序中使用了 firebase。 当我的应用程序部署到网络时,我遇到了问题。 (通过 github 页面)。 这里奇怪的部分是它告诉我我没有权限,而我的 firebase 规则设置为允许所有传入请求(见图)。
有谁知道如何解决这个问题/知道为什么会这样?
当我按下“获取令牌”按钮时,我使用以下查询从 usersData 集合请求数据:
const {user, logout, deleteSignedUser} = UserAuth();
async function getDataFromUser() {
// we get the documentId of the user with:
// docId = user.uid; The uid of the user is the same as the uid of the document in the users' collection.
const docRef = doc(firestoreDB, 'usersData', user.uid).withConverter(tokensConverter);
// we get the document
const docSnap = await getDoc(docRef);
// print the document to the console
console.log(docSnap.data());
// we get the data from the document and set it to the states
setTokens(docSnap.data().tokens); // we set the tokens to the state
setUsername(docSnap.data().username); // we set the username to the state
}
const [tokens, setTokens] = useState(undefined);
const [username, setUsername] = useState(undefined);
return(
<>
{tokens && <h4>Tokens available: {tokens}</h4>}
{username && <h4>Username: {username}</h4>}
<Button onClick={getDataFromUser}
variant='primary'
className="col-6">
Get Tokens
</Button>
</>
);
我的 AuthContext:
import { createContext, useContext, useEffect, useState } from 'react';
import {
createUserWithEmailAndPassword,
signInWithEmailAndPassword,
signOut,
onAuthStateChanged,
sendPasswordResetEmail,
reauthenticateWithCredential,
deleteUser,
EmailAuthProvider,
} from 'firebase/auth';
import { auth } from '../services/firebase';
const UserContext = createContext(undefined);
export const AuthContextProvider = ({ children }) => {
const [user, setUser] = useState({});
// sign up a new user with email and password
const createUser = (email, password) => {
return createUserWithEmailAndPassword(auth, email, password);
};
// login an existing with email and password
const signIn = (email, password) => {
return signInWithEmailAndPassword(auth, email, password)
}
// reset password
const resetPassword = (email) => {
return sendPasswordResetEmail(auth, email);
}
// logout the user
const logout = () => {
return signOut(auth)
}
// delete the user
const deleteSignedUser = async (password) => {
const credential = EmailAuthProvider.credential(auth.currentUser.email, password)
const result = await reauthenticateWithCredential(auth.currentUser, credential)
await deleteUser(result.user)
}
useEffect(() => {
const unsubscribe = onAuthStateChanged(auth, (currentUser) => {
console.log(currentUser);
setUser(currentUser);
});
return () => {
unsubscribe();
};
}, []);
return (
<UserContext.Provider value={{ createUser, user, logout, signIn, resetPassword, deleteSignedUser}}>
{children}
</UserContext.Provider>
);
};
export const UserAuth = () => {
return useContext(UserContext);
};
【问题讨论】:
标签: reactjs firebase github-pages