How to use cookie-parser - 10 common examples

To help you get started, we’ve selected a few cookie-parser 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 abecms / abecms / src / server / app.js View on Github external
if (coreUtils.file.exist(path.join(config.root, 'cert.pem'))) {
  opts = {
    key: fse.readFileSync(path.join(config.root, 'key.pem')),
    cert: fse.readFileSync(path.join(config.root, 'cert.pem'))
  }
}

var app = express(opts)
var server

// Instantiate Singleton Manager (which lists all blog files)
Manager.instance.init()
app.set('config', config.getConfigByWebsite())

app.use(flash())
app.use(cookieParser())
app.use(passport.initialize())
app.use(passport.session())
app.use(
  bodyParser.urlencoded({limit: '1gb', extended: true, parameterLimit: 50000})
)
app.use(expressValidator())
app.use(csrf({cookie: {secure: config.cookie.secure}}))
app.use(function(req, res, next) {
  if (req.url.indexOf('/abe/') > -1) {
    res.locals._csrf = req.csrfToken()
  }
  next()
})

app.use(bodyParser.json({limit: '1gb'}))
github ioBroker / ioBroker.iot / lib / socket.js View on Github external
function getUserFromSocket(socket, callback) {
        let wait = false;
        try {
            if (socket.handshake.headers.cookie && (!socket.request || !socket.request._query || !socket.request._query.user)) {
                const cookie = decodeURIComponent(socket.handshake.headers.cookie);
                const m = cookie.match(/connect\.sid=(.+)/);
                if (m) {
                    // If session cookie exists
                    const c = m[1].split(';')[0];
                    const sessionID = cookieParser.signedCookie(c, that.settings.secret);
                    if (sessionID) {
                        // Get user for session
                        wait = true;
                        that.settings.store.get(sessionID, function (err, obj) {
                            if (obj && obj.passport && obj.passport.user) {
                                socket._sessionID = sessionID;
                                if (typeof callback === 'function') {
                                    callback(null, obj.passport.user);
                                } else {
                                    that.adapter.log.warn('[getUserFromSocket] Invalid callback')
                                }
                            } else {
                                if (typeof callback === 'function') {
                                    callback('unknown user');
                                } else {
                                    that.adapter.log.warn('[getUserFromSocket] Invalid callback')
github pmlrsg / GISportal / app / lib / collaboration.js View on Github external
io.set('authorization', function (handshakeData, accept) {
      // check if there's a cookie header
      if (handshakeData.headers.cookie) {
         try {
            var cookies = cookieParser.signedCookies(cookie.parse(handshakeData.headers.cookie), config.session.secret);
            var sid = cookies.GISportal;

            var sessionStore = app.get('sessionStore');
            sessionStore.load(sid, function(err, session) {
               if(err || !session) {
                  return accept('Error retrieving session!', false);
               }
            });

         } catch(e) {
            console.log(e);
         }


      } else {
         // if there isn't, turn down the connection with a message
github danger / peril / api / source / api / auth / getJWTFromRequest.ts View on Github external
export const getJWTFromRequest = (req: any) => {
  // Support JWT via cookies from the user session
  const cookies = (req && req.cookies) || (req && req.headers && req.headers.cookie)
  if (cookies && isString(cookies)) {
    return cookies && parse(cookies).jwt
  }

  if (cookies && cookieParser.JSONCookies(cookies).jwt) {
    return cookieParser.JSONCookies(cookies).jwt
  }

  // Support standard auth: "Authorization: Basic YWxhZGRpbjpvcGVuc2VzYW1l"
  const basicAuth = req.headers.Authorization || req.headers.authorization
  if (basicAuth) {
    if (basicAuth.includes("Basic ")) {
      return basicAuth.split("Basic ")[1]
    }
  }

  // No other auth routes
  return undefined
}
github davidnguyen179 / typescript-graphql-postgres-boilerplate / src / app.ts View on Github external
apollo.applyMiddleware({ app });

// set
app.set('port', process.env.PORT || 4000);
app.set('env', process.env.NODE_ENV || 'development');

// get
app.get('/healthz', function(req, res) {
  res.send('OK');
});

// use
app.use(compression());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
github strues / boldr / packages / server / src / middleware / initCore.js View on Github external
export default function initCore(app) {
  if (process.env.NODE_ENV === 'development') {
    app.use(morgan('dev'));
  }

  app.use((req, res, next) => {
    res.set('Request-Id', nanoid());
    next();
  });
  app.disable('etag');
  app.set('json spaces', 2);
  // Parse cookies via standard express tooling
  app.use(cookieParser(config.get('token.secret')));
  // Parse application/json
  app.use(bodyParser.json({ type: 'application/json' }));
  // parse application/x-www-form-urlencoded
  app.use(bodyParser.urlencoded({ extended: true }));
}
github kunalkapadia / express-mongoose-es6-rest-api / config / express.js View on Github external
import winstonInstance from './winston';
import routes from '../server/routes/index.route';
import config from './config';
import APIError from '../server/helpers/APIError';

const app = express();

if (config.env === 'development') {
  app.use(logger('dev'));
}

// parse body params and attache them to req.body
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.use(cookieParser());
app.use(compress());
app.use(methodOverride());

// secure apps by setting various HTTP headers
app.use(helmet());

// enable CORS - Cross Origin Resource Sharing
app.use(cors());

// enable detailed API logging in dev env
if (config.env === 'development') {
  expressWinston.requestWhitelist.push('body');
  expressWinston.responseWhitelist.push('body');
  app.use(expressWinston.logger({
    winstonInstance,
    meta: true, // optional: log meta data about request (defaults to true)
github xugy0926 / community / src / app.js View on Github external
app.locals = Object.assign(app.locals, {
  config: config,
  apiPrefix: config.apiPrefix,
  marked,
  multiline,
  signupValid: config.signupValid,
  signinValid: config.signinValid,
  githubSigninValid: config.github.signinValid
});

// uncomment after placing your favicon in /public
app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser(config.sessionSecret));
app.use(useragent.express());
app.use('/static', express.static(path.join(__dirname, 'public')));
app.use('/static', express.static(path.join(__dirname, 'upload')));

app.use(
  connectBusboy({
    limits: {
      fileSize: bytes(config.fileLimit)
    }
  })
);

app.use(githubAuth());
app.use(authUser);
app.use(zone);
github dtonys / universal-web-boilerplate / src / server / server.js View on Github external
offlineMode = true;
  }

  const app = express();

  // middleware
  app.use( express.static('public') );
  app.all('/favicon.*', (req, res) => {
    res.status(404).end();
  });
  app.use(morgan('[:date[iso]] :method :url :status :response-time ms - :res[content-length]'));
  app.use(helmet.noSniff());
  app.use(helmet.ieNoOpen());
  app.use(helmet.hidePoweredBy());
  app.use(compression());
  app.use(cookieParser());

  app.use(handleErrorMiddleware);

  // Send dummy JSON response if offline
  if ( offlineMode ) {
    app.all('/api/*', (req, res) => res.send({}));
  }
  // Proxy to API
  app.all('/api/*', createProxy( process.env.API_URL ));

  await setupWebpack(app);
  await startServer(app);
}
github dont-fear-the-repo / fear-the-repo / server / app.js View on Github external
to: function(context) {
        return context.parsedUrl.pathname;
      }
    }
  ]
}));

/////////////////////////////////////////////////////////////////
//                                                             //
//  Linkedin Authorization passport                            //
//                                                             //
/////////////////////////////////////////////////////////////////


app.use(passport.initialize());
app.use(cookieParser());
passport.use( new LinkedinStrategy({  // request fields from facebook
  profileFields: ['summary','industry','positions','headline','picture-url','first-name','last-name','email-address','location','public-profile-url'],
  consumerKey: '75wbm6jxhrsauj',
  consumerSecret: 'qz9SGDHb53Hi6tnU',
  callbackURL: '/linkedin'
  //enableProof: false
  },
    (accessToken, refreshToken, profile, done) => {
    setTimeout(() => {
      return done(null, profile);
    },0);
  }
));
passport.serializeUser((user, done) => { // serialization is necessary for persistent sessions
  done(null, user);
});

cookie-parser

Parse HTTP request cookies

MIT
Latest version published 1 month ago

Package Health Score

89 / 100
Full package analysis