I'm trying to use express-session in nodejs express but I can't set or get sessions. I get "Property 'session' does not exist on type 'Request'" when I'm trying to build.
I tried to change the order of the codes but nothing works
node version : v10.15.3
visual studio : 2017
my dependencies
"dependencies": {
"axios": "^0.19.0",
"body-parser": "^1.19.0",
"cookie-parser": "^1.4.4",
"debug": "^2.2.0",
"express": "^4.14.0",
"express-session": "^1.16.2",
"pug": "^2.0.0-rc.3",
"session-file-store": "^1.3.0"
},
"devDependencies": {
"#types/debug": "0.0.30",
"#types/express": "^4.0.37",
"#types/express-serve-static-core": "^4.0.50",
"#types/mime": "^1.3.1",
"#types/serve-static": "^1.7.32",
"#types/node": "^6.0.87"
}
app.ts
var app = express();
var bodyParser = require('body-parser');
var session = require('express-session');
var FileStore = require('session-file-store')(session);
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json()); // to support JSON-encoded bodies
app.use(express.json()); // to support JSON-encoded bodies
app.use(express.urlencoded({ extended: true })); // to support URL-encoded bodies
app.use(session({
name: 'test-session-cookie-id',
secret: 'test',
resave: true,
store: new FileStore(),
saveUninitialized: true,
cookie: { secure: true }
}));
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
app.use('/signup', signup);
app.use('/verify', verify);
app.use(function printSession(req, res, next) {
console.log('req.session', req.session); //error
return next();
});
update :
module seems to be working fine itself . it created a session folder with 500+ files which is odd
update2 :
the express session is working fine but the error is bugging me. I uninstalled vs2017 and installed vs2019 and updated the typescript but the problem is still there
there was no #types/express-session in my dependencies/devDependencies . npm install --save #types/express-session did the job . there is no error now
Related
Setup:
I am trying to get the demo code for keycloak-connect library to run, but failing.
Here's what I did:
Download and start keycloak 4.7 standalone, set admin user and pw
Create a basic public client
Create a user
Create a basic express app in webstorm
Relevant files:
index.js
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var session = require('express-session');
var Keycloak = require('keycloak-connect');
var memoryStore = new session.MemoryStore();
let keycloak = new Keycloak({ store: memoryStore });
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var app = express();
app.set('trust proxy', 1); // trust first proxy
app.use(session({
secret: 'keyboard cat',
resave: false,
saveUninitialized: true,
cookie: { secure: true },
store: memoryStore
}));
app.use( keycloak.middleware() );
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.get('/$', function(req, res) {
res.write('Secure');
res.end();
});
app.get( '/secure', keycloak.protect('realm:master'), function(req, res){
//Edit: keycloak.protect() gives the same result
res.write("Yo!");
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;
keycloak.json (copy/paste)
{
"realm": "master",
"auth-server-url": "http://localhost:8080/auth",
"ssl-required": "external",
"resource": "test",
"public-client": true,
"confidential-port": 0
}
package.json
{
"name": "keycloak-test",
"version": "0.0.0",
"private": true,
"scripts": {
"start": "node ./bin/www"
},
"dependencies": {
"cookie-parser": "~1.4.3",
"debug": "~2.6.9",
"express": "~4.16.0",
"express-session": "^1.15.6",
"http-errors": "~1.6.2",
"keycloak-connect": "^4.7.0",
"morgan": "~1.9.0",
"pug": "2.0.0-beta11"
}
}
Problem:
On accessing http://localhost:3000/secure, I am redirected to the keycloak login form, an can log in with the user credentials for the demo user.
I am then redirected back to /secure, and the website says Access denied with 403 forbidden response code.
The keycloak console says
16:44:56,691 WARN [org.keycloak.events] (default task-8)
type=CODE_TO_TOKEN_ERROR,
realmId=master,
clientId=test,
userId=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx,
ipAddress=127.0.0.1,
error=invalid_code,
grant_type=authorization_code,
code_id=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx,
client_auth_method=client-secret
The node.js console says Could not obtain grant code: 400:Bad Request.
What am I doing wrong?
you are securing your resource /secure with a realm role called master
app.get( '/secure', keycloak.protect('realm:master')
you need to create master role and assign to demouser as shown below
The problem with this is a problem with the npm keycloak-connect package, when you install using npm install must be getting a warning which says, run npm audit.
Run npm audit --force abd rerun the app it will work. I was stuck in the same problem for a day and this thing came as a life saver for me.
run npm audit --force after an npm install.
npm install
npm audit --force
First of all sorry my bad English. I'm studying and I'm doing an academic project and came across a problem. I can not recall a session variable.
package.json
"dependencies": {
"body-parser": "^1.7.0",
"ejs": "~1.0.0",
"express": "^4.8.7",
"express-session": "^1.11.3",
"ini": "^1.3.4",
"mysql": "^2.8.0",
"winston": "^1.0.1"
}
server.js
var express = require('express');
var session = require('express-session');
var app = express();
...
require('./router/main')(app, language, connection, logger);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.engine('html', require('ejs').renderFile);
app.use(express.static(__dirname + '/public'));
app.use(session({
secret: 'pecuniamsekretsession',
resave: false,
saveUninitialized: true,
cookie: { secure: true }
}));
main.js
module.exports = function(app, languageItems, connection, logger) {
app.post('/', require('../router/login.js')(languageItems, connection, logger));
app.get('/', require('../router/login.js')(languageItems, connection, logger));
}
login.js
module.exports = function (language, connection, logger) {
var routerTemplateLogin = function (req, res) {
var utils = require('../utils/utils');
var util = new utils.Util;
// It does not work :-(
logger.debug(req.session);
req.on('data', function(data) {
var arrayPost = util.postDataToArray(data);
});
res.render('pages/login.ejs', {
lang: language
});
}
return routerTemplateLogin;
}
In login.js see // It does not work :-(. Full project in https://github.com/braulioti/pecuniam
Thanks
The problem is that the routes are set up before any other middleware. Move this line:
require('./router/main')(app, language, connection, logger);
after this:
app.use(session({
secret: 'pecuniamsekretsession',
resave: false,
saveUninitialized: true,
cookie: { secure: true }
}));
in your server.js.
I am using dustjs as the templating engine in an express app, and was wondering if anyone has successfully used the contextDump helper in a server side template in express? I followed the consolidate example for integrating dust with express, and it is working well. The helpers are there, as I'm able to do a simple test with the eq helper and it works. but when trying to dump the context I'm not seeing it anywhere. here is a sample template:
{>layout/}
{<content}
<ul>
{#users}
<li>{username} - Create New Task
<ul>
{#user.tasks}
<li>{title} - Delete Task |
Update Task</li>
{/user.tasks}
</ul>
</li>
{/users}
</ul>
{/content}
{#contextDump to="console"/}
Here's my app.js:
var express = require('express');
var app = express();
var http = require('http');
var path = require('path');
var db = require ('./models');
var dust = require('dustjs-linkedin');
var cons = require('consolidate');
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('models', db);
//configure dust
app.set('view engine', 'dust');
app.set('template_engine', 'dust');
app.engine('dust', cons.dust);
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(express.cookieParser('your secret here'));
app.use(express.session());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
//require routes
require('./routes')(app);
require('./routes/user')(app);
require('./routes/task')(app);
db
.sequelize
.sync({ force: true })
.complete(function (err) {
if (err) {
throw err;
} else {
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
}
});
and here's package.json:
{
"name": "application-name",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "node app.js"
},
"dependencies": {
"express": "3.4.6",
"sequelize": "~2.0.0-beta.5",
"mysql": "~2.0.0-rc2",
"lodash": "~2.4.1",
"async": "~0.2.9",
"dustjs-linkedin": "~2.2.2",
"dustjs-helpers": "~1.1.1",
"consolidate": "~0.10.0"
}
}
Thanks!
Modules:
"express": "~3.0.0",
"jade": ">= 0.0.1",
"mongoose": ">= 3.6.2",
"connect-mongo": "0.3.2",
"nodemailer": ">= 0.3.20",
"socket.io": "0.9",
"cookie": "0.0.5",
"passport": "0.2.3",
"passport-facebook": "*",
"underscore": "*"
-- BACKEND --
Expressjs Configuration:
app.configure(function(){
app.set('port', process.env.PORT || 3000);
app.set('views', config.root + '/app/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.limit('1mb'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser(''));
app.use(express.session());
app.use(express.static(path.join(config.root, 'public')));
// express/mongo session storage
app.use(express.session({
secret: '',
store: new mongoStore({
url: config.db,
collection : 'sessions'
})
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(app.router);
});
In routers:
app.get('/login/facebook', passport.authenticate('facebook', { display: 'popup', scope: [ 'email', 'user_about_me'], failureRedirect: '/' }));
app.get('/login/facebook/callback', passport.authenticate('facebook', { failureRedirect: '/' }), user.callbackLogin);
In user.callbackLogin :
exports.callbackLogin = function(req, res){
res.render('callback_login');
};
callback_login view has a js script to close the window login popup.
-- FRONTEND --
Utils.popupCenter = function(url, width, height, name) {
var left = (screen.width/2)-(width/2);
var top = (screen.height/2)-(height/2);
return window.open(url, name, "menubar=no,toolbar=no,status=no,width="+width+",height="+height+",toolbar=no,left="+left+",top="+top);
};
Utils.popupCenter('login/facebook', 600, 400, 'Facebook Login');
I'm having troubles with passportjs integration. The popup works, the facebook login is called, and when I click in 'Ok' the facebook returns the data and passport saves in mongodb. But, after this point, nothings works. Expressjs blocking the requests. When I try access another url nodejs stay busy. After spends some time I'm receiving the message "No data received".
I know it's quite late for an answer, but try this project that I put up together:
https://github.com/rafaelfaria/PassportJS-Facebook-Client-Auth
I hope that's what you are looking for.
There is very strange behavior in Express, can't figure out, mind cracking problem.
So suppose in req.user I have user id and here is my middleware code.
app.use(function(req, res, next){
var User = mongoose.model('User');
User.findById(req.user, function(err, user){
if(err) return next(err);
res.locals.user = user;
console.log(user);
next();
});
}
So it is working just fine when request type is GET, but if request is POST it just get to infinite waiting, until I receive No data received.
There is no issues with database nor with session: console.log(user) always works.
This is very very strange... I even tried to use another async function and it didn't work again for POST only requests.
fs.stat(__dirname + '/schemas/user.js', function(err, stat){
next();
})
My conclusion is that if next() is being called from callback during POST request it just hangs, but who can explain me WHY???
The original issue that brings me here was when I was trying to use passport.js deserializer which reads user from mongodb for every request, so that fails too for POST only requests.
configurations
{
"name": "myApp",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "./node_modules/.bin/nodemon app.js"
},
"dependencies": {
"express": "3.0.0rc5", //did also tried with rc4
"ejs": ">= 0.8.3",
"express-partials": "latest",
"mongodb": ">= 1.1.7",
"mongoose": "*",
"node-uuid": "*",
"passport": "*",
"passport-local": "*",
"flashify": "*",
"nodemon": "latest"
}
}
express configuration
var app = express();
app.configure(function(){
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(express.logger('dev'));
app.use(partials());
app.use(express.cookieParser('Secret secret'));
app.use(express.session());
app.use(passport.initialize());
app.use(passport.session());
app.use(MY_MIDDLEWARE_HERE);
app.use(express.favicon());
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(flashify);
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
});
app.configure('development', function(){
app.use(express.errorHandler());
});
I'm not sure this will have an effect, but its recommended to use bodyParser middleware earlier in the middleware stack. I would put it below cookieParser and above passport middleware, since many authentication mechanisms need to find parameters in the body.