I'm implementing a simple login for my node app with Passport Local, Express, Next.js, and MongoSession store.
Everything works well, except my app runs deserializeUser for every single request. This results in my db being hit 10+ times for any app interaction
Based on this post https://github.com/jaredhanson/passport/issues/14#issuecomment-4863459 I know that my requests for static assets are hitting the middleware stack.
Most of the requests are for the path /_next/static*
I have tried and failed to implement express.static as shown in the above example. Please help me figure out how avoid calling deserializeUser on every request.
Thanks!
Here's my code:
app.js
const app = next({ dev });
const handle = app.getRequestHandler();
app.prepare().then(async () => {
const server = express();
server.use(helmet());
server.use(express.static(path.join(__dirname, '_next', 'static')));
server.use(express.json());
auth({ ROOT_URL, server });
api(server);
routesWithSlug({ server, app });
sitemapAndRobots({ server });
server.get('*', (req, res) => {
const url = URL_MAP[req.path];
if (url) {
app.render(req, res, url);
} else {
handle(req, res);
}
});
server.listen(port, (err) => {
if (err) throw err;
logger.info(`> Ready on ${ROOT_URL}`);
});
});
module.exports = { app };
auth.js
function auth({ ROOT_URL, server }) {
const dev = process.env.NODE_ENV !== 'production';
const MongoStore = mongoSessionStore(session);
const sess = {
name: 'builderbook.sid',
secret: process.env.sessSecret,
store: new MongoStore({
mongooseConnection: mongoose.connection,
ttl: 14 * 24 * 60 * 60, // expires in 14 days
}),
resave: false,
saveUninitialized: false,
cookie: {
httpOnly: true,
maxAge: 14 * 24 * 60 * 60 * 1000, // expires in 14 days
},
};
if (!dev) {
server.set('trust proxy', 1);
sess.cookie.secure = true;
}
server.use(session(sess));
server.use(passport.initialize());
server.use(passport.session());
server.use(bodyParser.urlencoded({ extended: false }));
passport.serializeUser((user, done) => {
console.log('serializeUser');
done(null, user.id);
});
passport.deserializeUser((id, done) => {
console.log(`deserializeUser, id: ${id}`);
User.findById(id, User.publicFields(), (err, user) => {
done(err, user);
});
});
const verifyLocal = async (req, email, password, done) => {
console.log({ email, password, req });
const { firstName, lastName } = req.body;
try {
// signInOrSign up the user to MongoDb
const user = await User.signInOrSignUp({
email,
password,
firstName,
lastName,
});
console.log(user);
if (!user) {
return done(null, false);
}
if (!User.verifyPassword(email, password)) {
return done(null, false);
}
return done(null, user);
} catch (err) {
console.log(err); // eslint-disable-line
return done(err);
}
};
passport.use(
new LocalStrategy(
{
usernameField: 'email',
passReqToCallback: true,
},
verifyLocal,
),
);
}
module.exports = auth;
authroutes.js
router.post('/login', passport.authenticate('local', { failureRedirect: '/fail' }), (req, res) => {
res.redirect('/');
});
router.get('/logout', (req, res) => {
req.logout();
res.redirect('/login');
});
module.exports = router;
This code seemed to solve the problem. Thanks to Tima over at Builderbook!
https://github.com/builderbook/builderbook/issues/229
server.get('/_next*', (req, res) => {
handle(req, res);
});
server.get('/static/*', (req, res) => {
handle(req, res);
});
Related
hello every one i was trying to use connect-flash with passport local but can not seem to find relevant info either on the docs and other sources,if any one can guide me on this and tell me what i went wrong ,thanks.And why does request to login-fail gives this error:-
ERROR is AxiosError: Request failed with status code 404
but when i test the route with rest client on vscode it responses perfectly like seen
here.
also when i check the database right after i click submit on the route
there will be two sessions stored consecutively one having the flash(the first) and the other not like this:-
session:
{"cookie":{"originalMaxAge":259200000,"expires":"2023-01-16T12:30:14.395Z","secure":false,"httpOnly":true,"path":"/"},"flash":{"error":["Incorrect password"]}}
session:
{"cookie":{"originalMaxAge":259200000,"expires":"2023-01-16T12:30:14.453Z","secure":false,"httpOnly":true,"path":"/"}}
why this is happening?
userRoutes.js
const router = require("express").Router();
const passport = require("passport");
const { ObjectID } = require("mongodb");
const LocalStrategy = require("passport-local");
const bcrypt = require("bcrypt");
const flash = require("connect-flash");
const User = require("../models/userModel.js");
router.route("/register").post(
(req, res, next) => {
User.findOne({ fullName: req.body.fullName }, (err, user) => {
if (err) {
next(err);
} else if (user) {
res.redirect("/");
} else {
const {
fullName,
email,
id,
department,
stream,
batch,
sex,
age,
phoneNumber,
password,
} = req.body;
const hash = bcrypt.hashSync(password, 12);
console.log(hash);
const newUser = new User({
fullName,
email,
id,
department,
stream,
batch,
sex,
age,
phoneNumber,
password: hash,
});
newUser.save((err, data) => {
if (err) res.redirect("/");
next(null, data);
});
}
});
},
passport.authenticate("local", { failureRedirect: "/" }),
(req, res, next) => {
res.json({ user: "i am josh" });
}
);
router
.route("/login")
.post(
passport.authenticate("local", {
failureRedirect: "/login-fail",
failureFlash: true,
}),
(req, res) => {
res.json({ user: "i am josh" });
}
);
router.route("/login-fail").get((req, res) => {
// console.log(req.flash('error'));
res.json({ user: "josh" });
});
router.route("/logout").get((req, res) => {
req.logout();
res.redirect("/");
});
passport.serializeUser((user, done) => {
done(null, user._id);
});
passport.deserializeUser((id, done) => {
User.findOne({ _id: new ObjectID(id) }, (err, doc) => {
done(null, doc);
});
});
const customFields = {
usernameField: "email",
};
passport.use(
new LocalStrategy(customFields, (email, password, done) => {
User.findOne({ email }, (err, user) => {
//console.log(`User ${user.username} attempted to log in.`);
if (err) return done(err);
if (!user) return done(null, false, { message: "email does not exist" });
if (!bcrypt.compareSync(password, user.password)) {
return done(null, false, { message: "Incorrect password" });
}
return done(null, user);
});
})
);
function ensureAuthenticated(req, res, next) {
if (req.isAuthenticated()) {
return next();
}
res.json({ msg: "You are not authorized to view this page" });
}
module.exports = router;
server.js
require("dotenv").config();
const express = require("express");
const app = express();
const flash = require("connect-flash");
const session = require("express-session");
const passport = require("passport");
const mongoose = require("mongoose");
const MongoStore = require("connect-mongo");
const cors = require("cors");
app.use(express.json());
// app.use(express.urlencoded({ extended: true }));
app.use(cors());
app.use(flash());
app.use(
session({
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: true,
store: MongoStore.create({
mongoUrl: process.env.DB,
collection: "sessions",
}),
cookie: { secure: false, maxAge: 1000 * 60 * 60 * 24 * 3 },
})
);
app.use(passport.initialize());
app.use(passport.session());
mongoose
.connect(process.env.DB)
.then(() => {
console.log("DB connection successful");
})
.catch((err) => {
console.log(`DB connection Error: ${err}`);
});
const usersRouter = require("./routes/userRoutes");
app.use("/user", usersRouter);
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
console.log(`server is running on port ${PORT}`);
});
module.exports = app;
ya,have seen the same question here on stack over flow but none of the answers work
I am creating a mern stack chat application. I used google authentication using passport js. everything is working fine in the localhost. I can log in and the user get saved in the database but when I upload the frontend to Netlify it does not work. I can login and the user get saved in the Mongodb database but cookies doesn't get saved.
// passport.js middle ware
import * as dotenv from "dotenv";
import passport from "passport";
import { Strategy as GoogleStrategy } from "passport-google-oauth20";
import User from "./models/user.js";
dotenv.config();
passport.serializeUser((user, cb) => {
cb(null, user.id);
});
passport.deserializeUser((id, cb) => {
User.findById(id).then((user) => {
cb(null, user);
});
});
passport.use(
new GoogleStrategy(
{
clientID: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
callbackURL: process.env.GOOGLE_CALLBACK_URL,
},
function (accessToken, refreshToken, profile, cb) {
console.log(" google strategy called");
User.findOne({ googleId: profile.id }).then((currentUser) => {
if (currentUser) {
// already have user
console.log("user find one called");
cb(null, currentUser);
} else {
// if not, create user in our db
new User({
name: profile.displayName,
googleId: profile.id,
email: profile.emails[0].value,
picture: profile.photos[0].value,
membership: "free",
})
.save()
.then((newUser) => {
cb(null, newUser);
});
}
});
}
)
);
// index.js
dotenv.config();
const app = express();
app.use(
cors({
origin: "https://taupe-starburst-7fab32.netlify.app",
methods: "GET,POST,PUT,DELETE",
credentials: true,
})
);
app.use(express.json());
Connection();
app.use(
cookieSession({
name: "session",
keys: [process.env.SESSION_SECRET],
// Cookie Options
domain: "https://taupe-starburst-7fab32.netlify.app",
maxAge: 24 * 60 * 60 * 1000, // 24 hour
secure: true,
httpOnly: true,
sameSite: "none",
})
);
// to solve session.regenarate issue
app.use(function (request, response, next) {
if (request.session && !request.session.regenerate) {
request.session.regenerate = (cb) => {
cb();
};
}
if (request.session && !request.session.save) {
request.session.save = (cb) => {
cb();
};
}
next();
});
app.use(passport.initialize());
app.use(passport.session());
app.use("/auth", router);
const server = app.listen(process.env.PORT || 5000, () =>
console.log("server running")
);
// auth.js
import express from "express";
import passport from "passport";
const router = express.Router();
//sunccess redirect
router.get("/login/success", (req, res) => {
if (req.user) {
res.status(200).json({
success: true,
message: "successfull",
user: req.user,
});
} else {
res.status(401).json({
success: false,
message: "Unauthorized: User is not logged in",
});
}
});
//failure redirect
router.get("/login/failed", (req, res) => {
res.status(401).json({
success: false,
message: "failure",
});
});
// authenticate
router.get(
"/google",
passport.authenticate("google", { scope: ["email", "profile"] })
);
// callback
router.get(
"/google/callback",
passport.authenticate("google", {
successRedirect: process.env.CLIENT_URL,
failureRedirect: "/login/failed",
})
);
//logout
router.get("/logout", (req, res) => {
req.logout(function (err) {
if (err) {
return next(err);
}
res.redirect(`${process.env.CLIENT_URL}/login`);
});
});
export default router;
// React Frontend
function Login() {
const google = () => {
window.open(`${process.env.REACT_APP_API_URL}auth/google`, '_self');
};
return (
<button type="button" onClick={google}>
Login with Google
</button>
);
}
export default Login;
My website keeps logging me out when I try to access other pages when logged in. I am using cookies to store the session but, I guess I did not do it properly cause even after authentication, I am being continuously logged out. It is not letting me use my app.
Here is the link to my web-app: https://upset-gilet-lion.cyclic.app/
Here is my code:
require("dotenv").config();
const express = require("express");
const bodyParser = require("body-parser");
const ejs = require("ejs");
const mongoose = require("mongoose");
const session = require("express-session");
const passport = require("passport");
const passportLocalMongoose = require("passport-local-mongoose");
const GoogleStrategy = require('passport-google-oauth20').Strategy;
const findOrCreate = require("mongoose-findorcreate")
const app = express();
app.use(express.static(__dirname + "/public/"));
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({
extended: true
}));
// Initializing Session
app.use(session({
secret: process.env.SECRET,
resave: false,
saveUninitialized: false
}));
// Initializing Passport
app.use(passport.initialize());
app.use(passport.session());
// Connecting to MongoDB using Mongoose
mongoose.set('strictQuery', true);
const mongodb = "mongodb://127.0.0.1:27017/userDB"
const mongodbNet = "mongodb+srv://admin-bhoami:"+ process.env.PASSWORD +"#secretscluster.uztbzho.mongodb.net/userDB";
mongoose.connect(mongodbNet, function(err){
if (err) {
console.log('Unable to connect to MongoDB');
console.log(err);
} else {
const PORT = process.env.PORT || 3000;
app.listen(PORT, function() {
console.log("Server started on Port ${PORT}");
console.log('Successfully connected to MongoDB');
});
}
});
// Creating a new User Database
const userSchema = new mongoose.Schema ({
email: String,
password: String,
googleId: String,
secret: Array
});
userSchema.plugin(passportLocalMongoose);
userSchema.plugin(findOrCreate);
const User = new mongoose.model("User", userSchema);
// Set Local Login Strategy
passport.use(User.createStrategy());
// Serialize and Deserialize
passport.serializeUser(function(user, done) {
done(null, user._id);
});
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
done(err, user);
});
});
// Google Authentication Strategy that authenticates users using a Google Account and OAuth 2.0 tokens.
passport.use(new GoogleStrategy({
clientID: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
callbackURL: "https://upset-gilet-lion.cyclic.app/auth/google/secrets", //"http://localhost:3000/auth/google/secrets"
},
function(accessToken, refreshToken, profile, cb) {
User.findOrCreate({username: profile.emails[0].value, googleId: profile.id }, function (err, user) {
return cb(err, user);
});
}
));
// Home Page
app.route("/")
.get(function(req, res) {
res.render("home");
});
// Google Authentication Route
app.get('/auth/google',
passport.authenticate('google', { scope: ["openid", "profile", "email"] }));
app.get("/auth/google/secrets",
passport.authenticate("google", { failureRedirect: "/signin" }),
function(req, res) {
// Successful authentication, redirect home.
res.redirect("/secrets");
});
// Sign-Up Page
app.route("/signup")
.get(function(req, res) {
res.render("signup");
})
.post(function(req, res) {
User.register({username: req.body.username}, req.body.password, function(err, user) {
if (err) {
console.log(err);
res.redirect("/signup");
} else {
passport.authenticate("local")(req, res, function() {
res.redirect("/secrets");
});
}
});
});
// Sign-In Page
app.route("/signin")
.get(function(req, res) {
res.render("signin");
})
.post(function(req, res) {
// Check database to see if the username provided exists in it.
User.findOne({username: req.body.username}, function(err, foundUser) {
// If username found, create an object "user" to store username and password which was used for login
if (foundUser) {
const user = new User ({
username: req.body.username,
password: req.body.password
});
// Use the "user" object to compare against username and password stored in Database.
// The code below will either return false is no match was found or it will return the 'found user'.
passport.authenticate("local", function (err, user) {
if (err) {
console.log(err);
} else {
// the 'user' below is the user returned from passport.authenticate callback; it will either be false if no match was found or the user
if (user) {
// If the user is found, then he/she is logged in or they are redirected to sign in page.
req.login(user, function(err) {
res.redirect("/secrets");
})
} else {
res.redirect("/signin");
}
}
}) (req, res);
// If no username is found, redirect to sign in page; i.e. user does not exists
} else {
res.redirect("/signin");
}
});
});
// Secrets Page
app.route("/secrets")
.get(function(req, res) {
if (req.isAuthenticated()) {
User.find({secret: {$ne: null}}, function(err, users) {
if (!err) {
if (users) {
res.render("secrets", {usersWithSecrets: users});
} else {
console.log(err);
}
} else {
console.log(err);
}
});
} else {
res.redirect("/signin");
}
});
// Sign-Out Route
app.route("/signout")
.get(function(req, res) {
req.logout(function(err) {
if (err) {
console.log(err);
} else {
res.redirect("/")
}
});
});
// Submit Route
app.route("/submit")
.get(function(req, res) {
if (req.isAuthenticated()) {
res.render("submit");
} else {
res.redirect("/signin");
}
})
.post(function(req, res) {
const submittedSecret = req.body.secret;
if(req.isAuthenticated()) {
req.user.secret.push(submittedSecret);
req.user.save(function() {
res.redirect("/secrets");
})
} else {
res.redirect("/signin");
}
});
// Delete Route
app.route("/delete")
.get(function(req, res) {
if (req.isAuthenticated()) {
res.render("delete", {secrets: req.user.secret});
} else {
res.redirect("/signin");
}
})
.post(function(req, res) {
if(req.isAuthenticated()){
User.findById(req.user.id, function (err,foundUser){
foundUser.secret.splice(foundUser.secret.indexOf(req.body.secret),1);
foundUser.save(function (err) {
if(!err){
res.redirect("/secrets");
}
});
});
}else {
res.redirect("/signin");
}
});
Turns out it wasn't a problem with my MongoDB connection. It was a problem with session storage. I used the 'connect-mongo' (https://www.npmjs.com/package/connect-mongo) package from npm and the web app started working as expected.
All I had to do:
npm install connect-mongo
const MongoStore = require('connect-mongo');
app.use(session({
store: MongoStore.create({mongoUrl: "mongodb://127.0.0.1:27017/databaseName"})
}));
I am trying to implement simple authentication with Node, Express, Express-Session and Passport.js. As a storage middleware I'm using connect-pg-simple as I am using pg-promise in my project.
I managed to configure passport to work with my routers but for some reason sessions won't be saved to my database. None of the plugins return any errors, everything seems to be running smoothly but my sessions table is empty.
What could I be doing wrong? connect-pg-simple connects to the server, passport.js is holding sessions and express-session assigns configured maxAge to cookies.
server.js
const express = require('express');
const db = require('./database.js');
const cors = require('cors');
const helmet = require('helmet');
const session = require('express-session');
const passport = require('passport');
const port = process.env.PORT || 3000;
const app = express();
const pgSession = require('connect-pg-simple')(session);
const pgStoreConfig = {
pgPromise: db.conn
};
app.set('trust proxy', 1);
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(
session({
secret: REDACTED, // need to change it later to some proper hash
store: new pgSession(pgStoreConfig),
resave: true,
cookie: {
maxAge: 30 * 24 * 60 * 60 * 1000, // 30 days ;)
secure: app.get('env') === 'production'
},
saveUninitialized: false
})
);
app.use(passport.initialize());
app.use(passport.session());
app.use(cors());
app.use(helmet());
app.get('/', (req, res) => {
if (req.session.views) {
req.session.views++;
} else {
req.session.views = 1;
}
//res.send(`Views: ${req.session.views}`);
res.json(req.session);
});
const userRouter = require('./routes/user.js');
app.use(userRouter);
config/passport.js
const passport = require('passport');
const local = require('passport-local');
const db = require('../database.js');
const statements = require('../routes/statements/user.js');
const cryptoUtils = require('../utils/crypto.js');
passport.serializeUser((user, done) => {
done(null, user.id);
});
passport.deserializeUser(async (id, done) => {
try {
let result = await db.conn.one(statements.getUserByIdStatement, [id]);
done(null, result);
} catch (error) {
console.log(`Error while deserializing user: ${error}`);
return done(error);
}
});
passport.use(
new local.Strategy(
{ usernameField: 'email', passwordField: 'password' },
async (username, password, done) => {
try {
let user = await db.conn.one(statements.loginUserStatement, [username]);
if (user == null) {
console.log(`Couldn't find user!`);
return done(null, false);
} else {
let passwordCheck = cryptoUtils.comparePasswords(
password,
user.password,
user.salt
);
if (passwordCheck) {
delete user.password;
delete user.salt;
console.log(`Successfuly logged in!`);
return done(null, user);
} else {
console.log(`Wrong password!`);
return done(null, false);
}
}
} catch (error) {
console.log(`Error during local strategy authentication: ${error}`);
return done(null, false);
}
}
)
);
module.exports = passport;
routes/user.js
router.post('/user/login', (req, res, next) => {
console.log('Authenticating');
passport.authenticate('local', (err, user, info) => {
if (err) {
res.status(500).json({ status: err });
}
if (!user) {
res.status(404).json({ status: 'User not found' });
}
if (user) {
req.logIn(user, function(err) {
if (err) {
res.status(500).json({ status: 'Error while logging in' });
}
res.redirect('/');
});
}
})(req, res, next);
});
router.get('/user/logout', userUtils.loginRequired, (req, res, next) => {
req.logout();
res.status(200).json({ status: 'Logged out' });
});
database.js
const pgp = require('pg-promise')(initOptions);
const conn = pgp(connectionConfig);
module.exports = {
pgp,
conn
};
Any help would be much appreciated.
passport-github is having a hard time knowing the req.user. The following code worked a few minutes ago, now im getting this error
TypeError: Cannot read property 'id' of undefined
shows on this line
var token = jwt.sign({ id: req.user.id}, process.env.JWT_SECRET );
I don't have this issue with passport local strategy, and i do have a store configured. Could it be an issue with the serialization ?
Or maybe because im testing the route path so much that after a while the github api stops working ?
routes/users.js
router.get('/auth/github', passport.authenticate('github', {
session:true,
scope:[ 'id', 'profile']
}));
router.get('/auth/github/callback', (req, res, next) => {
passport.authenticate('github', (user) => {
// Successful authentication, redirect home.
var token = jwt.sign({ id: req.user.id}, process.env.JWT_SECRET );
// res.cookie("jwt", token, { expires: new Date(Date.now() + 10*1000*60*60*24)});
jwt.verify(token, process.env.JWT_SECRET, function(err, data){
console.log(err, data);
})
res.status(200).send({message:"github user signed in", auth: true});
// console.log(`frontid ${req.user.id}`)
// res.redirect('')
console.log('this works', token);
})(req, res, next);
});
passport-github.js
const passport = require("passport");
const GitHubStrategy = require('passport-github2').Strategy;
const Sequelize = require('sequelize');
const Op = Sequelize.Op;
const models = require("../models/");
// passport.serializeUser((user, done) => {
// // push to session
// done(null, user.id);
// console.log(user.id)
// });
// passport.deserializeUser((id, done) => {
// models.User.findOne({
// where: {
// id,
// },
// }).then(user => done(null, user))
// .catch(done);
// });
passport.use(
new GitHubStrategy(
{
clientID: process.env.clientID,
clientSecret: process.env.secret,
callbackURL: 'http://127.0.0.1:8000/api/users/auth/github/callback',
passReqToCallback: true,
profileFields: ['id', 'login']
},
(req, accessToken, refreshToken, profile, done) => {
const { id, login, email} = profile._json;
console.log(`backbro ${id}`);
// console.log(req)
models.User.find({
where:{
id: id
}
}).then( user => {
// if user is found
if(user){
return done(null, user)
}
// else create new user
else{
models.User.create({
id: id,
username:login,
email: email,
createdAt: Date.now()
}).then( user => {
console.log('github user created');
return done(null, user);
})
}
})
}
)
);
passport.serializeUser((user, done) => {
// push to session
done(null, user.id);
});
passport.deserializeUser((userId, done) => {
// console.log('calling deserial' + userId);
// // TODO: findByPk syntax? findById deprecated? Try later after sucessfully record data in DB
models.User
.find({ where: { id: userId } })
.then(function(user){
// console.log(user);
return done(null, userId);
}).catch(function(err){
done(err, null);
});
// return done(null, id);
});
module.exports = passport;
routes/current_user
router.get("/current_user", (req, res) => {
if(req.user){
res.status(200).send({ user: req.user});
} else {
res.json({ user:null})
}
});
app.js
var sequelize = new Sequelize(
process.env.POSTGRES_DB,
process.env.POSTGRES_USER,
process.env.POSTGRES_PASSWORD,{
"dialect": "sqlite",
"storage": "./session.sqlite"
});
myStore = new SequelizeStore({
db:sequelize,
})
if (!process.env.PORT) {
require('dotenv').config()
}
// console.log(process.env.DATABASE_URL);
if (!process.env.PORT) {
console.log('[api][port] 8000 set as default')
console.log('[api][header] Access-Control-Allow-Origin: * set as default')
} else {
console.log('[api][node] Loaded ENV vars from .env file')
console.log(`[api][port] ${process.env.PORT}`)
console.log(`[api][header] Access-Control-Allow-Origin: ${process.env.ALLOW_ORIGIN}`)
}
app.use(logger('dev'));
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'build')));
app.use(cookieParser());
// We need a store in order to save sessions, instead of the sessions clearing out on us :)
app.use(session({
store: myStore,
saveUninitialized: false,
resave:false,
cookie: { maxAge: 30 * 24 * 60 * 60 * 1000 }, // 30 days
secret : process.env.JWT_SECRET,
}));
myStore.sync();
require('./config/passport')(passport); // PASSPORT Init
require('./config/passport-github'); // PASSPORT Init
app.use(passport.initialize());
app.use(passport.session());
app.use(bodyParser.urlencoded({ extended:false}));
app.use(bodyParser.json());
app.use(function(req, res, next) {
res.locals.user = req.user; // This is the important line
// req.session.user = user
console.log(res.locals.user);
next();
});
// this code may be useless or useful, still trying to understand cors.
app.use((req, res, next) => {
const { headers } = req;
res.header('Access-Control-Allow-Origin', headers.origin);
res.header('Access-Control-Allow-Headers', headers);
res.header('Access-Control-Allow-Credentials', true);
next();
});
app.use(cors({
origin: process.env.ALLOW_ORIGIN,
credentials: true,
allowedHeaders: 'X-Requested-With, Content-Type, Authorization',
methods: 'GET, POST, PATCH, PUT, POST, DELETE, OPTIONS'
}))
app.use('/api/users', userRoute );
app.use('/api/posts', postRoute );
// In order to use REACT + EXPRESS we need the following code, alone with a build
// in the client folder we run a npm run build in the client folder then it is referred
// in the following code.
app.use(express.static(path.join(__dirname, 'client/build')));
if(process.env.NODE_ENV === 'production') {
app.use(express.static(path.join(__dirname, 'client/build')));
//
app.get('*', (req, res) => {
res.sendfile(path.join(__dirname = 'client/build/index.html'));
})
}
//build mode
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname+'/client/public/index.html'));
})
models.sequelize.sync().then(function() {
app.listen(PORT, host, () => {
console.log('[api][listen] http://localhost:' + PORT)
})
})