Hello I am trying to make a certain path "/main" only accessible to logged in users. I have a loginUser action that sends the login request then redirects to "/main". However if you just type in "/main" after localhost:3000 without loggin in you can still get to "/main". Any help appreciated.
Here is my action:
export function loginUser(username1, password1) {
const mainPage = (response, dispatch) => {
if(true) {
history.push('/main');
}
dispatch({
type: POST_DATA_SUCCESS,
response,
});
};
const promise = fetch('http://localhost:8080/users/login', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': 'Basic ' + btoa(username1 + ":" + password1),
},
body: JSON.stringify({
username: username1,
password: password1,
})
});
return {
onRequest: POST_DATA_TRIGGERED,
onSuccess: mainPage,
onFailure: POST_DATA_FAILURE,
promise,
};
}
Here is my app.js:
import React from 'react';
import {Router, Route, Link} from 'react-router-dom';
import history from '../history'
import Journal from './journal';
import AddForm from './add-form';
import GetSearch from './old-search';
import SignUp from './signup';
import Front from './front';
import { loginUser } from '../actions';
export default function App(props) {
return(
<Router history={history}>
<div>
<h3><Link className="title-journey" to="/">A Journey of Life</Link>
</h3>
<main>
<Route exact path="/" component={Journal} />
<Route path="/sign-up" component={SignUp} />
<Route path="/add" component={AddForm} />
<Route path="/get" component={GetSearch} />
<Route path="/main" component={Front} />
</main>
</div>
</Router>
);
}
And here is my login.js component:
import React from 'react';
import {BrowserRouter as Router, Route, Link} from 'react-router-dom';
import { loginUser } from '../actions';
import { connect } from 'react-redux';
export class Login extends React.Component {
constructor(props) {
super(props);
this.state = {
//username: '',
//password: '',
}
}
login(e) {
e.preventDefault();
const userName = this.username.value;
const passWord = this.password.value;
console.log(userName);
console.log(passWord);
this.props.loginUser(userName, passWord);
}
render() {
return(
<form>
<h3>Login to start your Journey</h3>
<input placeholder="username" ref={input => {this.username = input}}>
</input>
<input placeholder="password" type="password"ref={input =>
{this.password = input}}></input>
<button onClick={this.login.bind(this)}>Login</button>
</form>
)
}
}
export default connect(null, { loginUser })(Login);
via JontheNerd
No comments:
Post a Comment