Hashnode/mern-starter

Passport Facebook Auth

Open

#324 创建于 2017年8月11日

在 GitHub 查看
 (0 评论) (0 反应) (0 负责人)JavaScript (1,222 fork)batch import
help wantedquestion

仓库指标

Star
 (5,143 star)
PR 合并指标
 (30 天内没有已合并 PR)

描述

I created a login system for the site with Facebook via Passport. I keep the token on req.user and transfer it to the store through redux, and I keep it in local storage.

I'm stuck in the testing phase whether or not the user is logged in while loading the app for the first time. If it comes from the server, the local storage. is not defined.

Another option is to save the token in req.user or req.session, but I can not do dispatch to action what routes.js file.

routes.js:

`/* eslint-disable global-require */
import React from 'react';
import { Route, IndexRoute } from 'react-router';
import App from './modules/App/App';
import * as Actions from './modules/Auth/AuthActions';
import store, {dispatch} from './store.js';

  const requireLoggedIn = (nextState, replace, cb) => {
    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();
        }
    };
  };

export default (
  <Route path="/" component={App}>
    <IndexRoute
      getComponent={(nextState, cb) => {
        require.ensure([], require => {
          cb(null, require('./modules/Post/pages/PostListPage/PostListPage').default);
        });
      }}
    />
    <Route
      path="/login"
      getComponent={(nextState, cb) => {
        require.ensure([], require => {
          cb(null, require('./modules/Auth/components/LoginForm').default);
        });
      }}
    />
    <Route
      path="/test"
      getComponent={(nextState, cb) => {
        require.ensure([], require => {
          cb(null, require('./modules/Auth/components/LoginForm').default);
        });
      }}
    />
    <Route
      path="/posts/:slug-:cuid"
      onEnter={requireLoggedIn}
      getComponent={(nextState, cb) => {
        require.ensure([], require => {
          cb(null, require('./modules/Post/pages/PostDetailPage/PostDetailPage').default);
        });
      }}
    />
  </Route>
);
`

Actions.js:

`export function checkAuth () {
  return (dispatch) => {
    dispatch(requestCheckAuth());
    return fetch(`${baseURL}/auth/checkAuth`, {
      method: 'GET',
      credentials: 'same-origin',
      headers: new Headers({
        'Content-Type': 'application/json',
      }),
    })
    .then((response) => response.json())
    .then((response) => {
      console.log(response)
      const { user, message } = response;
      if (!user.ok) {
        dispatch(loginFailure(message));
        return Promise.reject(message);
      }

      localStorage.setItem('token', user.token);
      dispatch(loginSuccess(user));
    })
    .catch((err) => {
      console.log(err);
    });
  };
}`

server, checkAuth:

`export function checkAuth (req, res, next) { if (req.user) { return res.json({ message: '', user: { ok: true, token: generateToken(req.user), user: req.user} }); } else { return res.status(400).send({ msg: 'not authorization' }); }

}`

贡献者指南