ExpressJS set/get/use cookies - javascript

Cannot get setted cookies within requests.
I set my cookie with
response.cookie('name', 'My name');
I would like to get my cookie this way, and it worked before, but I changed express configuration, and I don't know what seems to be the problem now.
request.cookies is and empty Object
My express configuration:
var express = require('express'),
api = require('./routes/api');
var app = express();
app.configure(function () {
app.set('port', process.env.PORT || 3000);
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
//app.use(express.bodyParser());
app.use(express.compress()); // New call to compress content
app.use(express.cookieParser());
app.use(express.session({secret: 'secret'}));
app.use(app.router);
app.use(express.methodOverride());
//app.use(express.static(__dirname + '/public'));
});
app.all('*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header("Access-Control-Allow-Headers", "X-Requested-With, Content-Type");
next();
});
app.configure('development', function () {
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
app.configure('production', function () {
app.use(express.errorHandler());
});
Setting Cookie:
exports.singIn = function (req, res) {
var mail = req.query.mail,
password = req.query.password;
return user.find({
mail: mail
}).then(function (d) {
var user = usersData(u);
res.cookie('mail', user.mail, { maxAge: 900000});
res.cookie('password', crypted, { maxAge: 900000});
res.json({ user: user });
return { user: user }
}).catch(function () {
res.json(400, {"error-tag": "error-sing-in"});
return {"error-tag": "error-sing-in"};
});
};
Getting Cookie:
exports.account = function (req, res) {
var mail = req.cookies.mail,
password = req.cookies.password;
//here req.cookies is an empty object. I don't know why?
};

An answer for 2017 ..
const cookieParser = require('cookie-parser');
const express = require('express');
const app = express();
app.use(cookieParser());
to get a cookie from an incoming request ..
let cookie = req.cookies['cookiename'];
to set a response cookie (this cookie will be sent on all future incoming requests until deletion or expiration) ..
res.cookie('cookiename', 'cookievalue', {
maxAge: 86400 * 1000, // 24 hours
httpOnly: true, // http only, prevents JavaScript cookie access
secure: true // cookie must be sent over https / ssl
});
to delete a response cookie ..
res.cookie('cookiename', 'cookievalue', {
maxAge: 0
});

It's kind of exaggerated to use an extra package ("cookie-parser"), when this is the middleware function you need:
function cookieParser(req, res, next) {
var cookies = req.headers.cookie;
if (cookies) {
req.cookies = cookies.split(";").reduce((obj, c) => {
var n = c.split("=");
obj[n[0].trim()] = n[1].trim();
return obj
}, {})
}
next();
}
app.use(cookieParser);
I couldn't use "cookie-parser" in my graphQL server because it was messing things up.

Related

The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is include

I have been trying to make a MERN stack project,and I was learning about sockets,but I am encountering this error when I try to use sockets:
Access to XMLHttpRequest at 'http://localhost:5000/socket.io/?EIO=3&transport=polling&t=O6F3vrY' from origin 'http://localhost:8000' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
I have read many stackoverflow answers and tried to use their code,but the error is not getting fixed anyhow.
I am pasting my files here, please help me out!
index.js file
const cors = require("cors");
const express = require('express');
const cookieParser = require('cookie-parser');
const app = express();
const port = 8000;
const expressLayouts = require('express-ejs-layouts');
const db = require('./config/mongoose');
// used for session cookie
const session = require('express-session');
const passport = require('passport');
const passportLocal = require('./config/passport-local-strategy');
const passportJWT = require('./config/passport-jwt-strategy');
const passportGoogle = require('./config/passport-google-oauth2-strategy');
const MongoStore = require('connect-mongo')(session);
const sassMiddleware = require('node-sass-middleware');
const flash = require('connect-flash');
const customMware = require('./config/middleware');
app.use(cors({ credentials: true, origin: 'http://localhost:8000' }));
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", req.header('Origin'));
res.header("Access-Control-Allow-Credentials", true);
res.header(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept"
);
res.header("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT, DELETE");
next();
});
// setup the chat server to be used with socket.io
const chatServer = require('http').Server(app);
const chatSockets = require('./config/chat_sockets').chatSockets(chatServer);
chatServer.listen(5000);
console.log('chat server is listening on port 5000');
app.use(sassMiddleware({
src: './assets/scss',
dest: './assets/css',
debug: true,
outputStyle: 'extended',
prefix: '/css'
}));
app.use(express.urlencoded());
app.use(cookieParser());
app.use(express.static('./assets'));
// make the uploads path available to the browser
app.use('/uploads', express.static(__dirname + '/uploads'));
app.use(expressLayouts);
// extract style and scripts from sub pages into the layout
app.set('layout extractStyles', true);
app.set('layout extractScripts', true);
// set up the view engine
app.set('view engine', 'ejs');
app.set('views', './views');
// mongo store is used to store the session cookie in the db
app.use(session({
name: 'codeial',
// TODO change the secret before deployment in production mode
secret: 'blahsomething',
saveUninitialized: false,
resave: false,
cookie: {
maxAge: (1000 * 60 * 100)
},
store: new MongoStore(
{
mongooseConnection: db,
autoRemove: 'disabled'
},
function (err) {
console.log(err || 'connect-mongodb setup ok');
}
)
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(passport.setAuthenticatedUser);
app.use(flash());
app.use(customMware.setFlash);
// use express router
app.use('/', require('./routes'));
app.listen(port, function (err) {
if (err) {
console.log(`Error in running the server: ${err}`);
}
console.log(`Server is running on port: ${port}`);
});
chat-sockets.js in config folder
module.exports.chatSockets = function (socketServer) {
let io = require('socket.io')(socketServer,{
cors:{
origin:"http://localhost:8000"
}
});
io.sockets.on('connection', function (socket) {
console.log('new connection received', socket.id);
socket.on('disconnect', function () {
console.log('socket disconnected!');
});
});
}
chat-engine.js in assets/js
class ChatEngine {
constructor(chatBoxId, userEmail) {
this.chatBox = $(`#${chatBoxId}`);
this.userEmail = userEmail;
this.socket = io.connect('http://localhost:5000');
if (this.userEmail) {
this.connectionHandler();
}
}
connectionHandler() {
this.socket.on('connect', function () {
console.log('connection established using sockets...!');
});
}
}
Any help is sincerely appreciated.

Express JS session value undefined?

let createError = require("http-errors");
let express = require("express");
let path = require("path");
let cookieParser = require("cookie-parser");
let logger = require("morgan");
const session = require("express-session");
let fileStore = require("session-file-store")(session);
const oneDay = 1000 * 60 * 60 * 24;
// Routers
let indexRouter = require("./routes/index");
let usersRouter = require("./routes/users");
let loginPage = require("./routes/login");
let app = express();
// System settings
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "ejs");
app.set("trust proxy", 1);
app.use(logger("dev"));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, "public")));
app.use(
session({
secret: "SECRET_KEY_FOR_SESSION",
saveUninitialized: true,
resave: false,
cookie: { maxAge: oneDay, secure: !true },
store: new fileStore(),
})
);
app.use("/", indexRouter);
app.use("/login", loginPage);
app.use("/users", usersRouter);
app.get("/createSession", (req, res, next) => {
res.send("This is sessionCreate file");
let mysession = req.session.save;
mysession.data = "LOGIN";
res.end;
});
app.get("/getSession", (req, res, next) => {
let getsession = req.session;
res.send(`${getsession.data}`);
res.end;
});
// catch 404 and forward to error handler
app.use(function (req, res, next) {
next(createError(404));
});
// error handler
app.use(function (err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get("env") === "development" ? err : {};
// render the error page
res.status(err.status || 500);
res.render("error");
});
module.exports = app;
getsession.data === undefined?
I uploaded a variable to the session but it was not detected?
All system settings are set correctly but what is the error? Session => The session is being saved to a storage folder but cannot be read.
session_saved_folder
Specifies the boolean value for the Secure Set-Cookie attribute. When truthy, the Secure attribute is set, otherwise it is not. By default, the Secure attribute is not set.
Note be careful when setting this to true, as compliant clients will not send the cookie back to the server in the future if the browser does not have an HTTPS connection.
Please note that secure: true is a recommended option. However, it requires an https-enabled website, i.e., HTTPS is necessary for secure cookies. If secure is set, and you access your site over HTTP, the cookie will not be set. If you have your node.js behind a proxy and are using secure: true, you need to set "trust proxy" in express:

GET,HEAD response when making a passport Oauth github request

I keep getting
GET, HEAD
response, when authenticating github user. This application is using express, and react.
I tried many solutions when it comes to blocked by cors, and although some solutions that may work for some developers. None has work for me
for example a solution from another post, does not work.
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
next();
});
Api call
router.get('/auth/github', passport.authenticate('github', { session: true, scope: ['profile'] }) );
router.get('/auth/github/callback',
passport.authenticate('github', { failureRedirect: '/' }),
function(req, res) {
// Successful authentication, redirect home.
var token = jwt.sign({ id: req.user.id}, 'nodeauthsecret');
res.cookie("jwt", token, { expires: new Date(Date.now() + 10*1000*60*60*24)});
res.redirect('http://127.0.0.1:8001/dashboard');
console.log(token)
console.log('this works');
});
app.js (express setup)
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 models = require('./models');
var User = require('./models/user');
var session = require('express-session');
var cookieParser = require('cookie-parser') ;
var cookieSession = require('cookie-session');
var dotenv = require('dotenv');
var env = dotenv.config();
var cors = require('cors');
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()
}
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(cookieParser());
app.use(bodyParser());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(session({
secret : 'nodeauthsecret',
resave: false,
saveUninitialized: true,
}));
// var corsOptions = {
// origin: 'http://example.com',
// optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
// }
app.use(passport.initialize());
app.use(passport.session());
require('./config/passport')(passport);
require('./config/passport-github')(passport);
app.use(function(req, res, next) {
res.locals.user = req.user; // This is the important line
console.log(res.locals.user);
next();
});
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
next();
});
app.use('/api/users', userRoute)
app.use('/api/posts', postRoute )
app.listen(port, () => {
console.log('[api][listen] http://localhost:' + port)
})
Redux action
export const signWithGithub = () => {
return (dispatch) => {
Axios.get('localhost:8000/auth/github', {
headers: {
'content-type': 'application/x-www-form-urlencoded',
'Access-Control-Allow-Credentials': true
},
crossdomain: true
}).then( (res) => {
console.log(res);
dispatch({type: SIGN_GITHUB});
});
}
}
Home.js
signGithub = () => {
this.props.signWithGithub();
};
...
<a onClick={this.signGithub}>
<Chip
label="Sign In with Github"
clickable
avatar={< Avatar alt = "Natacha" src = "https://avatars0.githubusercontent.com/u/9919?s=280&v=4" />}
component="a"
className={classes.chip}/>
</a>

nodejs expressjs ERR_TOO_MANY_REDIRECTS

I have error with "ERR_TOO_MANY_REDIRECTS" in browser.
On linux server it looks like:
Error: Can't set headers after they are sent.
This is my app.js:
const express = require('express');
const bodyParser = require('body-parser');
const mysql = require('mysql');
const path = require('path');
const app = express();
const session = require('express-session');
const {getHomePage} = require('./routes/index');
const {getmain, addUserPage, addUser, deleteUser, editUser, editUserPage, addTemplates, getHistory} = require('./routes/user');
const port = 5000;
var auth = function(req, res, next) {
if (req.session && req.session.user === "amy" && req.session.admin)
return next();
else
return res.sendStatus(401);
};
// create connection to database
// the mysql.createConnection function takes in a configuration object which contains host, user, password and the database name.
const db = mysql.createConnection ({
host: 'localhost',
user: '*****',
password: '*****',
database: '*****',
charset : 'utf8mb4'
});
// connect to database
db.connect((err) => {
if (err) {
throw err;
}
console.log('Connected to database');
});
global.db = db;
// configure middleware
app.set('port', process.env.port || port); // set express to use this port
app.set('views', __dirname + '/views'); // set express to look in this folder to render our view
app.set('view engine', 'ejs'); // configure template engine
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json()); // parse form data client
app.use(express.static(path.join(__dirname, 'public'))); // configure express to use public folder
app.locals.moment = require('moment');
app.use(session({
secret: '2C44-4D44-WppQ38S',
resave: true,
saveUninitialized: true,
cookie: { maxAge: 1800000}
}));
// routes for the app
app.get('/', getHomePage);
app.get('/main', auth, getmain);
app.get('/add', auth, addUserPage);
app.get('/edit/:id', auth, editUserPage);
app.get('/delete/:id', auth, deleteUser);
app.get('/addtemp/:login', auth, addTemplates);
app.get('/history', auth, getHistory)
app.post('/add', auth, addUser);
app.post('/edit/:id', auth, editUser);
app.post('/addtemp/:login', auth, addTemplates);
// Login endpoint
app.get('/login', function (req, res) {
if (!req.query.username || !req.query.password) {
res.send('login failed');
} else if(req.query.username === "amy" || req.query.password === "amy") {
req.session.user = "amy";
req.session.admin = true;
res.redirect('/main');
}
});
// Logout endpoint
app.get('/logout', function (req, res) {
req.session.destroy();
res.redirect("/");
});
// set the app to listen on the port
app.listen(port, () => {
console.log(`Server running on port: ${port}`);
});
I know I have some problems in
app.get('login...
Theres everything ok with success login using correct username and password but when I use incorrect nothing happend.
This is my module getmain (after correct login):
getmain: (req, res) => {
let query = "SELECT * FROM `users` ORDER BY id ASC";
// execute query
db.query(query, (err, result) => {
if (err) {
res.redirect('/main');
}
res.render('main.ejs', {
title: "blablabla"
,users: result
});
});
},
And this is index.js:
module.exports = {
getHomePage: (req, res) => {
let query = "SELECT * FROM `users` ORDER BY id ASC";
// execute query
db.query(query, (err, result) => {
if (err) {
res.redirect('/');
}
res.render('index.ejs', {
title: "blablabla"
,users: result
});
});
},
};
I read that's all because by looping but I can not figure it out.
I will be grateful for directing me to the source of the problem.

Passport Local Strategy not saving user in cookie or session

I'm attempting to use passport with express 4 and authenticate with a local strategy. I'm trying to get a simple setup working but I'm have issues.
I'm try to authenticate with an authorization middleware function... deserializeUser is never called, req.user is undefined and the user data is missing from both the sessions and cookies.
My server.js file:
var express = require('express');
var app = express();
var path = require('path')
var port = process.env.PORT || 3000;
var argv = require('minimist')(process.argv.slice(2));
var dust = require('express-dustjs')
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var methodOverride = require('method-override');
var authService = require('./app/services/auth.js')
var dbConfig = require('./app/config.js')['documentDB'];
var authService = require('./app/services/auth.js');
/*
* DUST JS
*/
// Dustjs settings
dust._.optimizers.format = function (ctx, node) {
return node
}
// Define custom Dustjs helper
dust._.helpers.demo = function (chk, ctx, bodies, params) {
return chk.w('demo')
}
// Use Dustjs as Express view engine
app.engine('dust', dust.engine({
// Use dustjs-helpers
useHelpers: true
}))
/*
* STATIC ASSETS
*/
app.use('/', express.static(__dirname + '/public'));
app.set('view engine', 'dust')
app.set('views', path.resolve(__dirname, './app/views'))
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser('X+a1+TKXwd26mkiUUwqzqQ=='));
app.use(session({
secret: 'X+a1+TKXwd26mkiUUwqzqQ==',
resave: true,
saveUninitialized: true,
cookie : { secure : true, maxAge : (4 * 60 * 60 * 1000) }
}));
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "http://localhost:8080");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, X-AUTHENTICATION, X-IP, Content-Type, Accept");
res.header("Access-Control-Allow-Credentials", true);
res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
next();
});
// Configure Passport authenticated session persistence.
//
// In order to restore authentication state across HTTP requests, Passport needs
// to serialize users into and deserialize users out of the session. The
// typical implementation of this is as simple as supplying the user ID when
// serializing, and querying the user record by ID from the database when
// deserializing.
passport.serializeUser(function(user, cb) {
console.log('serializeUser : ', user);
cb(null, user.id);
});
passport.deserializeUser(function(id, cb) {
console.log('-------------------------------');
console.log('-------------------------------');
console.log('deserializeUser : ', id);
console.log('-------------------------------');
console.log('-------------------------------');
authService.getAccountByID(id, function (err, user) {
if (err) { return cb(err); }
cb(null, user);
});
});
passport.use('local', new LocalStrategy({
usernameField: 'email',
passwordField: 'password'
}, function(username, password, callback) {
authService.authenticate(username, password, function(err, user) {
if (err) {
console.log("ERR >> ", err);
return callback(err, false, err);
}
return callback(err, user);
});
})
);
app.use(passport.initialize());
app.use(passport.session());
app.use(methodOverride());
/*
* ROUTES
*/
app.use('/', require('./app/routes/index.js')(passport));
app.use('/prototypes/', require('./app/routes/prototypes.js'));
app.use('/auth', require('./app/routes/auth')(passport));
/*
* APP START
*/
app.listen(port, function () {
var msg = 'Express started > ';
console.log('Express started >> ');
console.log(' env: ', process.env.NODE_ENV);
}).on('error', function(err){
console.log('ON ERROR >> ');
console.log(err);
});
process.on('uncaughtException', function(err) {
console.log('ON UNCAUGHT EXCEPTION >>');
console.log(err);
});
The middleware function and route.
var express = require('express');
var router = express.Router();
var controller = require('../controllers/index.js');
module.exports = function(passport) {
router.get('/', controller.index);
router.get('/test', verifyAuth, function(req, res) {
return res.status(200)
.json({"req.isAuth" : req.isAuth});
});
return router;
};
function verifyAuth(req,res,next) {
console.log('req.cookies : ', req.cookies);
console.log('req.login', req.login);
console.log('req.isAuthenticated : ', req.isAuthenticated);
console.log('req.session', req.session);
console.log('req.user : ', req.user);
if ( !req.isAuthenticated() ) {
res.status( 400 ); // constant defined elsewhere, accessible here
return res.end('Please Login'); // or a redirect in a traditional web app,
} // as opposed to an SPA
next();
}
Here is the login route:
router.post('/login', function(req, res, next) {
passport.authenticate('local', function(err, user, info) {
if (err || !user) {
return res.send(500, info);
}
req.login(user, function(err) {
if (err) {
return next(err);
console.log('ERROR > ', error);
}
return res.json(200, user);
});
})(req, res, next);
});
I believe you need to put the passport logic in app.post(); not only in app.use():
app.post('/login',
passport.authenticate('local', { failureRedirect: '/login' }),
function(req, res) {
res.redirect('/');
});
Check out this example server.js form the passport team on github:
Passport Example

Categories