How to use express-session - 10 common examples

To help you get started, we’ve selected a few express-session examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github keycloak / keycloak-nodejs-connect / test / fixtures / node-console / index.js View on Github external
this.build = function (kcConfig, params) {
    app.set('view engine', 'html');
    app.set('views', require('path').join(__dirname, '/views'));
    app.engine('html', hogan);

    // Create a session-store to be used by both the express-session
    // middleware and the keycloak middleware.

    var memoryStore = new session.MemoryStore();

    app.use(session({
      secret: 'mySecret',
      resave: false,
      saveUninitialized: true,
      store: memoryStore
    }));

    // Provide the session store to the Keycloak so that sessions
    // can be invalidated from the Keycloak console callback.
    //
    // Additional configuration is read from keycloak.json file
    // installed from the Keycloak web console.
    params = params || { store: memoryStore };
    var keycloak = new Keycloak(params, kcConfig);
github jdesboeufs / connect-mongo / test / legacy-tests.js View on Github external
const makeCookie = function() {
  const cookie = new expressSession.Cookie()
  cookie.maxAge = 10000 // This sets cookie.expire through a setter
  cookie.secure = true
  cookie.domain = 'cow.com'

  return cookie
}
github litixsoft / baboon / test / session.spec.js View on Github external
sut.getSession(cookie, function (error, session) {

                    var data = {
                        sessionID: 'kuXMThISDw9LA7mkEQ0pnOZt',
                        sessionStore: sessionStore
                    };

                    var sess = new Session(data, session);

                    expect(error).toBeNull();
                    expect(sess.id).toBe('kuXMThISDw9LA7mkEQ0pnOZt');
                    expect(sess.user.name).toBe('guest');

                    sess.user.name = 'test';

                    // set session
                    sut.setSession(sess, function (error, result) {

                        expect(error).toBeNull();
                        expect(result).toBe(true);

                        // get session with new params
                        sut.getSession(cookie, function (error, session) {
                            expect(error).toBeNull();
github linxiaowu66 / weChat-learning / server / server.js View on Github external
// force page reload when html-webpack-plugin template changes
  compiler.plugin('compilation', (compilation) => {
    compilation.plugin('html-webpack-plugin-after-emit', (data, cb) => {
      hotMiddleware.publish({ action: 'reload' })
      cb()
    })
  })
  app.use(hotMiddleware)
}


app.use(logger('dev'))
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false }))
app.use(cookieParser());
app.use(session({
  store: new FileStore(),
  secret: 'express-dwb',
  resave: false,
  saveUninitialized: false,
  cookie: { secure: false }
}))
app.use(express.static('dist'))
app.use('/', routes);


mongoose.connect(config.mongoUrl);

const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', () => {
  app.listen(port, config.host, (err) => {
github paragi / sphp / example.js View on Github external
console.error("example.js requires modules installed. Use:"
    + "\n\n  npm install express express-session ws body-parser"
    + "\n\nError: ",err.message);
});

// Load modules
var express = require('express');
var expressSession = require('express-session');
var bodyParser = require('body-parser');
var _ws = require('ws');
var path = require('path');

process.removeAllListeners('uncaughtException');

// Initialize server
var sessionStore = new expressSession.MemoryStore();
var sphp = require('./sphp.js');
var app = express();
var server = app.listen(8080,'0.0.0.0','',function () {
  console.log('Server listening at://%s:%s'
    ,server.address().address
    ,server.address().port);
});
var ws = new _ws.Server({server: server});

// Set up session. store and name must be set, for sphp to catch it

var docRoot = module.filename.substring(0,module.filename.lastIndexOf(path.sep)) + '/example/';

var sessionOptions={
   store: sessionStore
  ,secret:'yes :c)'
github tencentyun / wafer-node-session / index.js View on Github external
response.json({ type, message });
                response.end();
                return;
            }

            const { sessionKey, openId } = yield login({ appId, appSecret, code });

            const wxBiz = new WXBizDataCrypt(appId, sessionKey);
            const userInfo = wxBiz.decryptData(encryptData, iv);

            const session = request.session = {};
            session.id = request.sessionID = crypto.randomBytes(32).toString('hex');
            session.skey = generateSkey(sessionKey);
            session.sessionKey = sessionKey;
            session.userInfo = userInfo;
            session.cookie = new Cookie({ maxAge }); // fake cookie to support express-session Stores

            // save the session
            store.set(session.id, session, (err) => {
                if (err) {
                    console.error('store.set() error: ', err);
                }
                response.json({
                    [constants.WX_SESSION_MAGIC_ID]: 1,
                    session: {
                        id: session.id,
                        skey: session.skey
                    }
                });
                response.end();
            });
            return;
github SummerTiger / bitmedi / sh_blockchain / server.js View on Github external
function(err,results){
			     if (err!=null) {
				 // alert("Key Error!");
				 console.log(err);
				 console.log(results);
				 res.redirect("/");
			     } else {
				 console.log(results);
				 session = req.session;
				 session.login = true;
				 res.render('blockchain',{cargo:results});
			     }
			 });
	    } else {
github pylonide / pylon / plugins-server / connect.session.file / session-ext.js View on Github external
var expires = (typeof sess.cookie.expires === 'string')
                            ? new Date(sess.cookie.expires)
                            : sess.cookie.expires;
                        if (!expires || new Date < expires) {
                            // session ok
                        } else {
                            self.destroy(file);
                        }
                    });
                });
            });
        }, self.reapInterval);
    }
};

FileStore.prototype.__proto__ = Store.prototype;

FileStore.prototype.get = function(sid, fn){
  var self = this;
  var exists = fs.exists || path.exists;
  exists(self.basePath + "/" + sid, function(exists) {
      if (exists) {
          fs.readFile(self.basePath + "/" + sid, function(err, data) {
              if (err) {
                  fn && fn(err);
              }
              else {
                  var sess;
                  try {
                      sess = JSON.parse(data);
                  } catch(e) {
                      console.warn("Error '" + e + "' reading session: " + sid, data);
github Morgul / rpgkeeper / server / main.js View on Github external
//----------------------------------------------------------------------------------------------------------------------

// Build the express app
var app = express();

// Basic request logging
app.use(routeUtils.requestLogger(logger));

// Basic error logging
app.use(routeUtils.errorLogger(logger));

// Auth support
app.use(cookieParser());
app.use(bodyParser.json());
app.use(session({
    secret: config.secret || 'nosecret',
    key: config.key || 'sid',
    resave: false,
    rolling: true,

    // maxAge = 12hrs
    cookie: { maxAge: 1000 * 60 * 60 * 12},
    saveUninitialized: false,
    store: new FileStore({ path: './server/db/sessions' })
    //saveUninitialized: true
}));
app.use(passport.initialize());
app.use(passport.session());

// Set up our authentication support
localAuth.initialize(app);
github catamphetamine / webapp / code / api / server (express).js View on Github external
import session       from 'express-session'
import body_parser   from 'body-parser'

import configuration from '../configuration'
global.configuration = configuration

import json_rpc      from './json rpc'
import utility       from './api/utility'

import log           from './log'

json_rpc.add('utility', utility)

const web = express()

web.use(session
({
	secret: 'beast breaker',
	resave: false,
	saveUninitialized: false,
	cookie: { maxAge: 60000 }
}))

web.use(body_parser.json())

function api()
{
	return new Promise((resolve, reject) =>
	{
		web.post('/', (http_request, http_response) =>
		{
			// const version = http_request.params[0]