Hashnode / Hashnode/mern-starter

Passport Facebook Auth

Open
#324 0 comments 0 reactions 0 assignees View on GitHub
help wanted question
Dominant language
JavaScript
Stars
5.1k
Forks
1.2k
PR merge metrics
No merged PRs in 30d

Description

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 (

{
require.ensure([], require => {
cb(null, require('./modules/Post/pages/PostListPage/PostListPage').default);
});
}}
/>
{
require.ensure([], require => {
cb(null, require('./modules/Auth/components/LoginForm').default);
});
}}
/>
{
require.ensure([], require => {
cb(null, require('./modules/Auth/components/LoginForm').default);
});
}}
/>
{
require.ensure([], require => {
cb(null, require('./modules/Post/pages/PostDetailPage/PostDetailPage').default);
});
}}
/>

);
`
```
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

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.