req.session is not storing data - node.js

I'm trying to implement a login system where an user can register to a website, and then sign in with his account. Once the user is logged in, he can edit his personal information.
To check if the user is logged in, I'm trying to set req.session.isLoggedIn to true and then check if that value is true to access some areas of the website. The thing is that just after I signed in, I print the value of req.session and I see my just setted valued, but after that, when I try to check the value of req.session.isLoggedIn in another route, I get no value.
Here's my code:
const express = require('express');
const app = express();
var { Client } = require('pg');
var bcrypt = require('bcrypt');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var cors = require('cors');
var path = require('path');
var session = require('express-session');
var url = require("url");
app.use(cors());
app.use(express.static(path.join(__dirname, 'client/build')));
app.use(cookieParser());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(session({ secret: 'keyboard cat', cookie: { maxAge: 600000000 }}))
const client = new Client({
user: 'xxxxxxxxxxxxx',
host: 'xxxxxxxxxxxxx',
password: 'xxxxxxxxxxxxxxx',
database: 'xxxxxxxxxxxxxx',
port: 5432,
ssl: true
})
client.connect();
/*Rutas*/
/*Seleccionar huellas pertenecientas a una cierta categoria*/
app.get('/api/huellas/:categoria', (req, res) => {
client.query('SELECT * FROM huellas WHERE categoria = $1 AND activo = TRUE', [req.params.categoria], (err, query) => {
if (err) {
console.log(err.stack);
} else {
res.json(query.rows);
}
});
});
/*Listar todas las huellas*/
app.get('/api/mostrarHuellas', function(req, res, next) {
client.query('SELECT * FROM huellas', (err, query) => {
if (err) {
console.log(err.stack);
} else {
res.json(query.rows);
}
});
});
app.get('/api/buscarHuellas/', function(req, res) {
console.log(req);
console.log("nombre: " + req.query.nombre + " categoria: " + req.query.categoria + " estado: " + req.query.estado);
client.query('SELECT * FROM huellas WHERE (nombre = $1 AND categoria = $2 AND estado = $3) AND activo = TRUE', [req.query.nombre, req.query.categoria, req.query.estado], (err, query) => {
if (err) {
console.log(err.stack);
} else {
res.json(query.rows);
}
});
});
app.post("/api/registro", function(req, res) {
var email = req.body.email;
var password = bcrypt.hashSync(req.body.password, 10);
client.query('INSERT INTO usuarios(email, password, huella) VALUES ($1, $2, $3)', [email, password, req.body.huella], function(err, result) {
if(err) {
//console.log(err.stack);
res.json(err);
}
else {
console.log('row inserted');
res.json("ok");
}
});
});
app.post("/api/login", function(req, res) {
client.query('SELECT * FROM usuarios WHERE email = $1', [req.body.email], (err, query) => {
if (err) {
console.log(err.stack);
} else {
if(bcrypt.compareSync(req.body.password, query.rows[0].password)){
req.session.isLoggedIn = true;
console.log(req.session);
res.json("ok");
}
else{
res.json("clave invalida");
}
res.end();
}
});
});
app.get("/api/logout", function(req, res) {
req.session.destroy();
});
app.get("/api/sessions", function(req, res){
console.log(req.session);
if(req.session.isLoggedIn) {
console.log("logged in!");
}
});
const port = process.env.PORT || 5000;
app.listen(port);
When I access /api/login/ I receive this output in the terminal, I can see isLoggedIn:
Session {
cookie:
{ path: '/',
_expires: 2017-09-05T00:29:19.786Z,
originalMaxAge: 600000000,
httpOnly: true },
isLoggedIn: true }
But after that, when I access /api/sessions/ I receive this output:
Session {
cookie:
{ path: '/',
_expires: 2017-09-05T00:29:21.451Z,
originalMaxAge: 599999999,
httpOnly: true } }
I'm using Nodejs and Expressjs. Also, I'm serving some static file stored in /client/build, and they are working fine.
Thanks in advance!
EDIT:
Here's what my handle login method looks like, I'm using react and react-router 4:
handleSubmit(event){
event.preventDefault();
fetch('/api/login', {
method: 'post',
headers: {'Content-Type':'application/json'},
body: JSON.stringify({
"email": document.getElementById("email").value,
"password": document.getElementById("pwd").value
})
})
.then(response => response.json())
.then(res => {
switch (res) {
case "clave invalida":
alert("clave invalida");
break;
case "ok":
alert("sesion iniciada");
this.props.history.push("/");
break;
default:
alert("Error. Contacte a un administrador");
break;
}
})
.catch(err => console.log(err));
};

Well, I just found a solution for my problem. I used the solution posted by #ytibrewala here and the comment made by #nlawson here. This is what I did:
Apparently, by default, fetch method doesn't send cookies, so you need to set the credentials parameter inside the AJAX call, I did it this way:
AJAX call
handleSubmit(event){
event.preventDefault();
fetch('http://localhost:5000/api/login', {
method: 'post',
credentials: 'include',
headers: {'Content-Type':'application/json'},
body: JSON.stringify({
"email": document.getElementById("email").value,
"password": document.getElementById("pwd").value
})
})
.then(response => response.json())
.then(res => {
console.log(res);
if(res.isLoggedIn){
alert("Signed in");
this.props.history.push("/hueprint");
}
else{
alert("Invalid user or password");
}
})
.catch(err => console.log(err));
};
I used include because I'm not working with the same origin. More information about the values that the credentials parameter accepts can be found here
Then, I was facing a CORS issue in my browser, so I changed this on my index.js file on my back end:
index.js
app.use(cors({credentials: true, origin: true}));
Now, everytime I use my handleSubmit method in my website, and I checked the test route that prints req.session I see my isLoggedIn parameter properly setted.
I leave my route, for those who want to see it:
app.post("/api/login", function(req, res) {
client.query('SELECT * FROM usuarios WHERE email = $1', [req.body.email], (err, query) => {
if (err) {
console.log(err.stack);
}
else {
if(bcrypt.compareSync(req.body.password, query.rows[0].password)){
console.log("password matches");
req.session.isLoggedIn = true;
req.session.save();
res.send(req.session);
}
else{
console.log("password doesn't match");
req.session.isLoggedIn = false;
req.session.save();
res.send(req.session);
}
}
});
});

You need to send the cookies with the res object whenever you want to save them. Here is my code and it works. Check it out.
app.use(session({
secret: 'keyboard cat',
resave: true,
saveUninitialized: true,
}))
app.get("/", function(req, res){
if(req.session.views){
req.session.views++;
}else{
req.session.views = 1;
}
res.status(200).send(req.session);
})
app.get("/checkerPage", function(req, res){
console.log(req.session); //it logs the correct data.
res.send("whatever");
})
//post req
app.post("/post", function(req, res){
req.session.user = "myname";
res.send(req.session);
console.log(req.session);
});
my index html
<form action="/post" method="post">
<input type="text" name="myName" value="">
<input type="submit" name="" value="submit">
</form>

Related

req.session keeps returning undefined

I am new to cookies and session in express and I have a problem I don't understand how to solve. I make a simple user login system which communicate with DB. My login call works fine, but when I try to recuperate the value in req.session.user, it always return undefined when I call it in /getevents or /addevent.
const express = require("express");
const mysql = require("mysql");
const cors = require("cors");
const cookieParser = require("cookie-parser");
const session = require("express-session");
const bcrypt = require("bcrypt");
const saltRounds = 10;
const app = express();
app.use(express.json());
app.use(
cors({
origin: ["http://localhost:3000"],
methods: ["GET", "POST"],
credentials: true,
})
);
app.use(cookieParser());
app.use(
session({
key:"userId",
secret: "123123123",
resave: true,
saveUninitialized: true
}));
const db = mysql.createConnection({
database: 'defaultdb',
host: "dbhost.com",
port: 12345,
user: "db_user",
password: "password"
});
app.post("/login", (req, res) => {
const username = req.body.username;
const password = req.body.password;
db.query(
"SELECT * FROM user WHERE username = ?;",
[username],
(err, result) => {
if (err) {
res.send({ err: err });
}
if (result.length > 0) {
bcrypt.compare(password, result[0].password, (error, response) => {
if (response) {
req.session.userId = result[0].id;
res.send(result);
} else {
res.send({ message: "Invalid username / password !" });
}
});
} else {
res.send({ message: "Username does not exist !" });
}
}
);
});
app.get("/getevents", (req, res) => {
db.query(
"SELECT title, date FROM events WHERE user_id =?;",
req.session.userId,
(err, result) => {
if (err) {
console.log(err);
}
else {
res.send(result);
}
}
);
});
app.post("/addevent", (req, res) => {
db.query(
"INSERT INTO event (title,date,user_id) VALUES (" + req.body.title + ", " + req.body.date + ", " + parseInt(req.session.userId) + ")",
(err, result) => {
if (err) {
console.log(err);
}
else {
res.send(result);
}
}
);
})
After trying to resolve for a few hours I'm kind of out of ideas...

Nuxt JS with passport local

I'm starting with Nuxt JS trying to migrate an old site with passport local and express-session, I get to make the authentication based on this repository but the main problem comes when I reload the page the users logout, its appears that Nuxt JS it's not saving my user session on the browser. I mostly sure there is something that im forgetting to implement or im not understanding. How could I save my res session token on my user browser?. Btw I have my API running on a separate port, so im not sure if there is any problem on saving session from other port. Here is my code:
Login.vue
<script>
import axios from 'axios';
export default {
data() {
return {
error : false,
form : {
username: '',
password: ''
}
}
},
created() {
if(this.$store.state.user) {
return this.$router.push('/');
}
},
methods: {
async login () {
await this.$store.dispatch('login', {
username : this.form.username,
password: this.form.password
});
this.form.password = '';
this.form.username = '';
}
},
}
</script>
Store/Index.js:
import axios from "axios";
export const state = () => ({
user: null,
});
export const mutations = {
SET_USER(state, user) {
state.user = user;
},
};
export const actions = {
nuxtServerInit({ commit }, { req }) {
if (req) {
if (
typeof req.session !== "undefined" &&
typeof req.user !== "undefined"
) {
commit("SET_USER", req.user);
}
}
},
login({ commit }, { username, password }) {
return axios({
method: "post",
url: this.$axios.defaults.baseURL + "/auth/login",
credentials: "same-origin",
data: {
username,
password
}
})
.then(res => {
if (res.data.meta.error === true) {
throw res.data;
}
return res.data.user;
})
.then(authUser => {
commit("SET_USER", authUser);
});
},
};
API Index.js
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
const helmet = require('helmet');
const cors = require('cors') // Srsly. Fuck Cors
const morgan = require('morgan');
const session = require('express-session');
const MySQLStore = require('express-mysql-session')(session);
const passport = require('passport');
const { database } = require('./config/keys');
const config = require('./config/config.json');
require('./lib/bAuth');
app.disable('view cache');
app.disable('x-powered-by');
app.set('port', process.env.PORT || config.port);
app.use(helmet());
app.use(cors());
app.use(morgan('dev'));
app.use(express.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
app.use(cookieParser());
app.use(session({
name: '_hsid',
key: 'sessionKey',
secret: config.session_secret,
resave: false,
saveUninitialized: false,
store: new MySQLStore(database),
cookie : {
maxAge: 1000 * 60 * 60 *24 * 365,
},
})
);
app.use(passport.initialize());
app.use(passport.session());
app.listen(app.get('port'), () => console.log(`[✔] Website connected and running at port: ${app.get('port')}`))
Login Route:
app.post('/login', async (req,res,next) => {
req.query = req.body;
auth.authenticate('user-login', (err,user,info) => {
if(user){
req.logIn(user,(err)=>{
if(err){
return res.json({
meta: {
error: true,
msg: err
}
});
}else{
if(req.isAuthenticated()){
if(!req.user.authenticated){
return res.json({
meta: {
error: true,
msg: "Bad credentials"
}
});
}else{
return res.json({
meta: {
error: false
},
user: bAccess.cleanUser(Object.assign({}, user))
});
};
}
}
});
}else{
return res.json({
meta: {
error: true,
msg: "Bad credentials"
}
});
}
})(req,res,next);
});
Passport Config:
auth.use('user-login', new Strategy({
usernameField: 'username',
passwordField: 'password',
passReqToCallback: true
}, async (req, username, password, done) => {
const _user = await _context.query('select username,password from users where username = ?', username);
if (!_user[0]) return done(null,false);
if (!_user[0].password || !await bAccess.verifyPassword(password, _user[0].password)) {
return done(null, false);
}
done(null, _user[0], {scope : '*'});
}, ));
auth.serializeUser(function (user, done) {
done(null, user);
});
auth.deserializeUser(async (user, done) => {
done(null, user);
});

Can't get jwt token after login

Background
I am tryng to do an simple authtentication system using jwt and mysql+sequelize here
What I had being able to do so far
I am being able to login and generate a token after that.
Problem
After being logged in, when I try to check the jwt token with a middleware on a particular route, it simply says that the token was not found.
What I tried to do
Since the token should be found at the req.headers['x-access-control'] or ['authorization'] I tried to console.log(req.headers) when I call the middleware but there is nothing about these two headers... Then I think that the problem might be there, but I have no idea on how to solving this :(
Pieces of code
This is the middleware (userController.js) which I use to login (signIn) and to verify the token (verifyToken)
var bcrypt = require("bcryptjs");
var jwt = require("jsonwebtoken");
const config = require("../config/config");
const User = require("../models").User;
module.exports = {
signIn(req, res) {
console.log("Sign-In");
User.findOne({
where: {
email: req.body.email
}
})
.then(user => {
if (!user) {
return res.status(404).send("User not found");
}
var passwordIsValid = bcrypt.compareSync(
req.body.password,
user.password
);
if (!passwordIsValid) {
return res
.status(401)
.send({
auth: false,
accessToken: null,
reason: "Invalid Password"
});
}
var token = jwt.sign({ id: user.id }, config.secret, {
expiresIn: 86400 // expires in 24 hours
});
res.status(200).send({ auth: true, accessToken: token });
})
.catch(err => {
res.status(500).send("Error =>" + err);
});
},
verifyToken(req, res) {
console.log(req.headers);
let token =
req.body.token ||
req.query.token ||
req.headers["x-access-token"] ||
req.headers["authorization"];
if (!token) {
return res.status(403).send({
auth: false,
message: "No token provided"
});
}
jwt.verify(token, config.secret, (err, decoded) => {
if (err) {
return res.status(500).send({
auth: false,
message: "Fail to Authentication. Error -> " + err
});
}
req.userId = decoded.id;
next();
});
}
};
and here is the app.js file with the Routes
const express = require("express");
const app = express();
const port = 3000;
const Sequelize = require("sequelize");
const sequelize = new Sequelize("mydb", "root", "Metin.234", {
host: "localhost",
dialect: "mysql"
});
sequelize
.authenticate()
.then(() => {
console.log("Connection with sequelize has been established successfully");
})
.catch(err => {
console.error("Unable to connect", err);
});
const userController = require("./controllers").user;
var bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.set("view engine", "ejs");
app.use(express.static(__dirname + "/public"));
app.get("/", (req, res) => {
res.render("home");
});
app.get("/register", (req, res) => {
res.render("register");
});
app.get("/login", (req, res) => {
res.render("login");
});
app.post("/login", userController.signIn);
app.get("/showAll", userController.verifyToken);
app.listen(port, () => {
console.log("server started!");
});
Thanks in advance, any help is appreciated! =D
EDIT
I saved the token on a variable called globalToken, so then it could be used on the verify token function (EDIT 2 and it works fine for what I want), however I am wondering on how can I get the value of accesstoken that is inside the response object that I am sending after the login proccess.

Passport req.login doesn't create req.user

i am trying to develop a login system with React,Node,Mysql,Express and Passport but i have encountered this problem. After calling req.login and passing it the userID, when i go to the route where i check for the req.user it says undefined. Here is my code for the server side.
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const app = express();
const session = require("express-session");
const { PORT = 8000 } = process.env;
const bcrypt = require("bcrypt");
const saltRounds = 10;
const cookieParser = require("cookie-parser");
const passport = require("passport");
var LocalStrategy = require('passport-local').Strategy;
const mysql = require("mysql");
/app.options("*", cors());
app.use(cors());
app.use(express.json()) // for parsing application/json
app.use(express.urlencoded({ extended: true })) // for parsing application/x-www-form-urlencoded
// app.use(cookieParser());
app.use(
session({
secret: "keyboard cat",
resave: false,
saveUninitialized: false
// cookie: { secure: false }
})
);
app.use(passport.initialize());
app.use(passport.session());
const connection = mysql.createConnection({
host: "localhost",
user: "root",
password: "qwertyhnjkl",
database: "login"
});
connection.connect(err => {
if (err) {
console.error("Error connection to database");
}
else console.log("Database connected");
});
app.get('/',function (req,res){
console.log(req.user);
console.log(req.isAuthenticated())
res.send('hello world')
});
app.post("/register", (req, res) => {
const { name, username, email, password } = req.body;
console.log(req.body);
bcrypt.hash(password, saltRounds, function(err, hash) {
connection.query(
`insert into users(Name,Username,Email,Password) values('${name}','${username}','${email}','${hash}')`,
function(error) {
if (error) console.error(error);
}
);
connection.query("SELECT LAST_INSERT_ID() as userID", (error,results,fields) =>
{
if (error) throw error;
console.log(results)
const userID = results[0].userID;
console.log("userid in query: " + userID);
req.login(userID, function(err) {
if(err) res.send(err);
else{
console.log("req.user in req.login: " + req.user)
console.log("isAuthenticated: "+ req.isAuthenticated())
console.log(req.session )
console.log('Logged in succesfully')
res.send("Logged in succesfully");
}
});
});
});
});
And this is how i handle the form in react:
submitRegister(event) {
event.preventDefault();
const data = this.state.data
axios.post("http://localhost:8000/register", {
name: data.name,
username: data.username,
email: data.email,
password: data.password
})
.then(response => {
console.log(response);
if(response.data){
console.log('Succesful signup');
this.setState({ //redirect to login page
redirectTo: '/'
})
}
}).catch(error => {
console.log("Sign up to server failed");
console.log(error)
});
}
After i request the '/' of the server and check for the session in Application->Cookies->localhost there is no session.
The insertion is well done. I get the username email hashed password in my database. i get the right userID i even get the console.log in serialize function with the right userID(the last one introduced)
req.user in req.login: 47
isAuthenticated: true
Session {
cookie:
{ path: '/',
_expires: null,
originalMaxAge: null,
httpOnly: true },
passport: { user: 47 } }
Logged in succesfully
serialize 47
This is what i get in the console when requesting the route /register from the server. Now when i go for localhost:8000 it says req.user is undefined and isAuthenticated false.
Looks like cors() was the issue here. After removing it and using proxy in package.json solved the issue.

Passport + Sequelize not saving req.user

I'm having an issue with saving the session. It appears that logging in and logging out works fine. However, if making code changes or if the nodemon server refreshes, it renders null on the current_user route.
And then this error when making post requests.
Cannot read property 'id' of undefined
router.get("/current_user", (req, res) => {
if(req.user){
res.status(200).send({ user: req.user});
} else {
res.json({ user:null})
}
});
routes
const jwt = require('jsonwebtoken');
const passport = require('passport');
router.post('/loginUser', passport.authenticate('login', {session: true}), (req, res, next) => {
passport.authenticate('login', (err, user, info) => {
if (err) {
console.log(err);
}
if (info != undefined) {
console.log(info.message);
res.status(401).send(info.message);
} else {
req.logIn(user, err => {
models.User.findOne({
where: {
username: req.body.username,
},
}).then(user => {
const token = jwt.sign({ id: 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({
auth: true,
token: token,
message: 'user found & logged in',
});
// console.log(req.user)
});
});
}
})(req, res, next);
});
passport.js
const bcrypt = require('bcrypt'),
BCRYPT_SALT_ROUNDS = 12,
JWTstrategy = require('passport-jwt').Strategy,
ExtractJWT = require('passport-jwt').ExtractJwt,
Sequelize = require('sequelize'),
Op = Sequelize.Op,
models = require( '../models/'),
localStrategy = require('passport-local').Strategy;
// passport = require("passport");
// serialize session, only store user id in the session information
module.exports = async (passport) => {
passport.use(
'register',
new localStrategy(
{
usernameField: 'username',
passwordField: 'password',
passReqToCallback: true,
session: false,
},
(req, username, password, done) => {
try {
models.User.findOne({
where: {
[Op.or]: [
{
username: username,
},
{ email: req.body.email },
],
},
}).then(user => {
if (user != null) {
console.log('username or email already taken');
return done(null, false, {
message: 'username or email already taken',
});
} else {
bcrypt.hash(password, BCRYPT_SALT_ROUNDS).then(hashedPassword => {
models.User.create({
username: req.body.username,
password: hashedPassword,
email: req.body.email
}).then(user => {
console.log('user created');
return done(null, user);
});
});
}
});
} catch (err) {
done(err);
}
},
),
);
passport.use(
'login',
new localStrategy(
{
usernameField: 'username',
passwordField: 'password',
session: false,
},
(username, password, done, req) => {
try {
models.User.findOne({
where: {
[Op.or]: [
{
username: username,
}
],
},
}).then(user => {
if (user === null) {
return done(null, false, { message: 'Username doesn\'t exist' });
} else {
bcrypt.compare(password, user.password).then(response => {
if (response !== true) {
console.log('passwords do not match');
return done(null, false, { message: 'passwords do not match' });
}
console.log('user found & authenticated');
// note the return needed with passport local - remove this return for passport JWT
return done(null, user);
});
}
});
} catch (err) {
done(err);
}
},
),
);
const opts = {
jwtFromRequest: ExtractJWT.fromAuthHeaderWithScheme('JWT'),
secretOrKey: process.env.JWT_SECRET,
};
passport.use(
'jwt',
new JWTstrategy(opts, (jwt_payload, done) => {
try {
models.User.findOne({
where: {
username: jwt_payload._id,
},
}).then(user => {
if (user) {
console.log('user found in db in passport');
// note the return removed with passport JWT - add this return for passport local
done(null, user);
// console.log(user);
} else {
console.log('user not found in db');
done(null, false);
}
});
} catch (err) {
done(err);
}
}),
);
passport.serializeUser(function(user, done) {
done(null, user.id);
console.log(user.id); // gets user id
});
// from the user id, figure out who the user is...
passport.deserializeUser(function(id, done){
models.User.findOne({
where: {
id,
},
}).then(user => done(null, user))
.catch(done);
});
}
app.js
var express = require('express');
var app = express();
var userRoute = require('./routes/users');
var postRoute = require('./routes/posts');
var bodyParser = require('body-parser');
var logger = require('morgan');
var session = require('express-session');
var cookieParser = require('cookie-parser') ;
var dotenv = require('dotenv');
var env = dotenv.config();
var cors = require('cors');
var models = require('./models/');
const host = '0.0.0.0';
const PORT = process.env.PORT || 8000;
const passport = require('passport');
const path = require('path');
// const allowOrigin = process.env.ALLOW_ORIGIN || '*'
// CORS Middleware
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());
app.use(session({
secret : process.env.JWT_SECRET,
}));
require('./config/passport.js')(passport); // PASSPORT Init
app.use(passport.initialize());
app.use(passport.session());
app.use(bodyParser.urlencoded({ extended:false}));
app.use(bodyParser.json());
// this code may be useless or useful, still trying to understand cors.
app.use(function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Credentials', true);
res.header("preflightContinue", false)
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
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'));
})
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();
});
models.sequelize.sync().then(function() {
app.listen(PORT, host, () => {
console.log('[api][listen] http://localhost:' + PORT)
})
})
The question is not so much about saving the req.user, this is an issue with not having a store set in place.
app.use(session({
store: '', // enter a store
secret : process.env.JWT_SECRET,
}));
You're using Sequelize, so i would recommend you to look into this
https://github.com/mweibel/connect-session-sequelize
If all runs well, you will not have to worry about req.id becoming undefined everytime you make a code change. Hope this helps.
You can do something like
const SequelizeStore = require('connect-session-sequelize')(session.Store);
const 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,
})
app.use(session({
store: myStore,
secret : process.env.JWT_SECRET,
}));

Resources