I have a problem managing the authentication in my app, it's actually working but the problem is that when I refresh the page I am redirected to the Login page even if I am not signed out ! Here is the code of the routes page :
export const fakeAuth = {
isAuthenticated: false,
authenticate(cb) {
this.isAuthenticated = true
setTimeout(cb, 1000)
},
signout(cb) {
this.isAuthenticated = false
setTimeout(cb, 1000)
}
}
const PrivateRoute = ({ component: Component, ...rest }) => (
<Route {...rest} render={(props) => (
fakeAuth.isAuthenticated === true
? <Component {...props} />
: <Redirect to={{
pathname: '/login',
state: { from: props.location }
}} />
)} />
)
ReactDOM.render(
<Router history={hist}>
<Switch>
<Route path="/login" component={Login} />
<PrivateRoute path="/admin" component={AdminLayout} />
<Redirect to="/admin/dashboard" />
</Switch>
</Router>,
document.getElementById("root")
);
And here is the code of the Login component :
export class Login extends Component {
state = {
email: '',
password: '',
redirectToReferrer: false,
}
async login() {
const email = this.state.email
const password = this.state.password
await fakeAuth.authenticate(() => {
this.setState({
redirectToReferrer: true
})
})
/*axios.post(`${API_URL}login`, { email, password })
.then(async (response) => {
this.setState({
redirectToReferrer: true
})
//alert(response.data.admin.email + " est connecté !")
})*/
}
render() {
const { from } = this.props.location.state || { from: { pathname: '/admin' } }
console.log(from)
if (this.state.redirectToReferrer === true) {
return <Redirect to={from} />
}
return (
<>
<PanelHeader size="sm" />
<div className="content">
<Row>
<Col md="3"></Col>
<Col md="6">
<Card>
<CardHeader>
<h1 className="title"
style={{ textAlign: "center" }}
>Login</h1>
</CardHeader>
<CardBody>
<Form>
<Row>
<Col md="12">
<FormGroup>
<h6>Email</h6>
<Input
placeholder="Email"
type="email"
required
onChange={(e) => {
var email = e.target.value
this.setState({ email: email })
}}
/>
</FormGroup>
</Col>
</Row>
<Row>
<Col md="12">
<FormGroup>
<h6>Mot de passe</h6>
<Input
placeholder="Mot de passe"
type="password"
onChange={(e) => {
var password = e.target.value
this.setState({ password: password })
}}
/>
</FormGroup>
</Col>
</Row>
<Row>
<Col md="12">
<FormGroup style={{ left: "40%" }}>
<Button outline color="info" size="lg"
onClick={this.login.bind(this)} className="btn-round">Login</Button>
</FormGroup>
</Col>
</Row>
</Form>
</CardBody>
</Card>
</Col>
<Col md="3"></Col>
</Row>
</div>
</>
)
}
}
Any ideas, what should I do ?