我正在构建一个我想进行非常简单的身份验证的简单React应用。当您进入主页时,我需要检查您是否已登录,如果不是,则需要将您重定向到登录页面。
您登录(目前唯一的方式是通过google登录),然后再也看不到登录,然后重定向到您,直到注销为止,您再也看不到登录页面。
我从来没有做过这样的事情,我感到有些失落。使用google登录确实会弹出,当我单击它时,它似乎正在经历登录过程。但是我不知道如何重定向,也不知道如何告诉我已登录的应用程序的其余部分。
这是我的Firebase.js代码
firebase.initializeApp(firebaseConfig);
export const createUserProfileDocument = async (userAuth, additionalData) => {
if (!userAuth) return;
const userRef = firestore.doc(`users/${userAuth.uid}`);
const snapShot = await userRef.get();
if (!snapShot.exists) {
const { displayName, email } = userAuth;
const createdAt = new Date();
try {
await userRef.set({
displayName,
email,
createdAt,
...additionalData,
});
} catch (error) {
console.log("Error Creating user", error.message);
}
}
return userRef;
};
export const auth = firebase.auth();
export const firestore = firebase.firestore();
const provider = new firebase.auth.GoogleAuthProvider();
provider.setCustomParameters({ prompt: "select_account" });
export const signInWithGoogle = () => auth.signInWithPopup(provider);
// export const signInWithEmailAndPassword = (event, email, password) => {
// event.preventDefault();
// auth.signInWithEmailAndPassword(email, password).catch((error) => {
// console.log("Error with username and password", error);
// });
// };
export default firebase;
然后这是我的登录页面
class Login extends React.Component {
constructor(props) {
super(props);
this.state = {
email: "",
password: "",
};
}
handleSubmit = async (event) => {
event.preventDefault();
console.log("submit")
const { email, password } = this.state;
try {
await auth.signInWithEmailAndPassword(email, password);
this.setState({ email: "", password: ""});
} catch (error) {
console.log(error);
}
};
handleChange = (event) => {
const { value, name } = event.target;
this.setState({ [name]: value });
console.log(value);
};
render() {
return (
<div className="sign-in">
<span>Sign in with your email and password</span>
<form onSubmit={this.handleSubmit}>
<FormInput
name="email"
type="email"
label="Email"
value={this.state.email}
handleChange={this.handleChange}
required
/>
<FormInput
name="password"
type="password"
label="Password"
value={this.state.password}
handleChange={this.handleChange}
required
/>
<input type="submit" value="Submit" />
<button onClick={signInWithGoogle}>Sign in with Google</button>
</form>
</div>
);
}
}
主App.js
class App extends React.Component {
render(){
return (
<div>
<Redirect to="/login"/>
<Route exact path = "/login" component = {Login}/>
<Route exact path = "/" component = {WebContent}/>
</div>
);
}
};