Improve the login function

If a token is in the localStorage of the browser we now assume that the
user is already logged in. If that's no the case, he will be redirected
to the login page.
This commit is contained in:
Grégoire Delattre 2017-05-20 00:33:44 +02:00
parent 614d1ab11e
commit 76b2859d88
3 changed files with 26 additions and 28 deletions

View File

@ -38,12 +38,6 @@ export function userLogout() {
}
}
export function isUserLoggedIn() {
return {
type: 'IS_USER_LOGGED_IN',
}
}
export function loginUser(username, password) {
return request(
'USER_LOGIN',

View File

@ -44,21 +44,16 @@ import UserLoginForm from './components/users/login'
import UserEdit from './components/users/edit'
import UserSignUp from './components/users/signup'
class Main extends React.Component {
componentWillMount() {
this.props.isUserLoggedIn();
}
render() {
function Main(props) {
return (
<div>
<NavBar {...this.props}/>
<Alert {...this.props}/>
<NavBar {...props}/>
<Alert {...props}/>
<div className="container-fluid">
{React.cloneElement(this.props.children, this.props)}
{React.cloneElement(props.children, props)}
</div>
</div>
);
}
}
function mapStateToProps(state) {
@ -79,7 +74,20 @@ const App = connect(mapStateToProps, mapDispatchToProps)(Main);
const loginCheck = function(nextState, replace, next, f) {
const state = store.getState();
const isLogged = state.userStore.isLogged;
if (!isLogged) {
let token = localStorage.getItem('token');
// Let's check if the user has a token, if he does let's assume he's logged
// in. If that's not the case he will be logged out on the fisrt query
if (token !== "") {
store.dispatch({
type: 'USER_SET_TOKEN',
payload: {
token: token,
},
});
}
if (!isLogged && token === "") {
replace('/users/login');
} else {
f();

View File

@ -20,12 +20,8 @@ export default function userStore(state = defaultState, action) {
return logoutUser(state)
}
return updateFromToken(state, action.payload.data.token)
case 'IS_USER_LOGGED_IN':
let localToken = localStorage.getItem('token');
if (!localToken || localToken === "") {
return state;
}
return updateFromToken(state, localToken)
case 'USER_SET_TOKEN':
return updateFromToken(state, action.payload.token)
case 'USER_LOGOUT':
return logoutUser(state)
case 'GET_USER_FULFILLED':