Hi, i created a very basic auth example, just for learning. I'm curious your opinion about the way. Is good start or i missunderstud something.
I created a git repo: https://github.com/devmetal/mern-auth-example
Currently there is no site or describtion. Im working on it. The main points here:
//routes.js
import { Route, IndexRoute } from 'react-router';
import React from 'react';
import App from './container/App';
import PostContainer from './container/PostContainer/PostContainer';
import PostDetailView from './container/PostDetailView/PostDetailView';
import LoginContainer from './container/Login/LoginContainer';
import * as Actions from './redux/actions/auth-actions';
export default (store, req) => {
let token = null;
if (req && req.session.token) {
token = req.session.token;
}
const requireLogin = (nextState, replace, cb) => {
function checkAuth() {
const { auth: { isAuthenticated }} = store.getState();
if (!isAuthenticated) {
replace('/login');
}
cb();
}
const { auth: { loaded }} = store.getState();
if (!loaded) {
store.dispatch(Actions.checkToken(token)).then(checkAuth);
} else {
checkAuth();
}
};
return (
<Route path="/" component={App} >
<IndexRoute component={PostContainer} />
<Route path="/post/:slug" component={PostDetailView} onEnter={requireLogin} />
<Route path="/login" component={LoginContainer} />
</Route>
)
};
//auth-actions checkToken
export function checkToken(sToken) {
return (dispatch) => {
const token = typeof window === 'undefined' ? sToken : localStorage.getItem('token');
if (!token) {
return Promise.resolve(dispatch(tokenInvalid()));
}
dispatch(requestCheckToken());
return fetch(`${baseURL}/auth/me`, {
method: 'GET',
credentials: 'same-origin',
headers: new Headers({
'Authorization': `JWT ${token}`
})
})
.then((response) => {
if (response.status === 401) {
dispatch(tokenInvalid());
return Promise.reject();
}
return response.json()
})
.then((response) => {
const { user } = response;
if (!user.ok) {
dispatch(tokenInvalid());
return Promise.reject();
}
dispatch(tokenValid());
})
.catch((err) => {
console.log(err);
})
}
}
I tought the main problem is the storage. On server i dont have a localStorage. The project currently is not consistent because if you login, and reload, the @@Init state sill falsy about authentication. But i think it can be solved by the index.js on server side just like fetchComponentData method.
What dou you think? This is a good way? Or is missed something.
And im really happy with MERN stack :) Thank you for authors!!!