Hashnode/mern-starter

Passport Facebook Auth

Open

#324 geöffnet am 11. Aug. 2017

Auf GitHub ansehen
 (0 Kommentare) (0 Reaktionen) (0 zugewiesene Personen)JavaScript (1.222 Forks)batch import
help wantedquestion

Repository-Metriken

Stars
 (5.143 Stars)
PR-Merge-Metriken
 (Keine gemergten PRs in 30 T)

Beschreibung

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' }); }

}`

Contributor Guide