142
St
startsInvasion / files
startsInvasion / node_modules / connect / lib / middleware / session.js
9.3 KB
1 2/*! 3 * Connect - session 4 * Copyright(c) 2010 Sencha Inc. 5 * Copyright(c) 2011 TJ Holowaychuk 6 * MIT Licensed 7 */ 8 9/** 10 * Module dependencies. 11 */ 12 13var Session = require('./session/session') 14 , MemoryStore = require('./session/memory') 15 , Cookie = require('./session/cookie') 16 , Store = require('./session/store') 17 , utils = require('./../utils') 18 , parse = require('url').parse 19 , crypto = require('crypto'); 20 21// environment 22 23var env = process.env.NODE_ENV; 24 25/** 26 * Expose the middleware. 27 */ 28 29exports = module.exports = session; 30 31/** 32 * Expose constructors. 33 */ 34 35exports.Store = Store; 36exports.Cookie = Cookie; 37exports.Session = Session; 38exports.MemoryStore = MemoryStore; 39 40/** 41 * Warning message for `MemoryStore` usage in production. 42 */ 43 44var warning = 'Warning: connection.session() MemoryStore is not\n' 45 + 'designed for a production environment, as it will leak\n' 46 + 'memory, and obviously only work within a single process.'; 47 48/** 49 * Default finger-printing function. 50 */ 51 52function defaultFingerprint(req) { 53 return req.headers['user-agent'] || ''; 54}; 55 56/** 57 * Paths to ignore, defaulting to `/favicon.ico`. 58 */ 59 60exports.ignore = ['/favicon.ico']; 61 62/** 63 * Setup session store with the given `options`. 64 * 65 * Session data is _not_ saved in the cookie itself, however 66 * cookies are used, so we must use the [cookieParser()](middleware-cookieParser.html) 67 * middleware _before_ `session()`. 68 * 69 * Examples: 70 * 71 * connect.createServer( 72 * connect.cookieParser() 73 * , connect.session({ secret: 'keyboard cat' }) 74 * ); 75 * 76 * Options: 77 * 78 * - `key` cookie name defaulting to `connect.sid` 79 * - `store` Session store instance 80 * - `fingerprint` Custom fingerprint generating function 81 * - `cookie` Session cookie settings, defaulting to `{ path: '/', httpOnly: true, maxAge: 14400000 }` 82 * - `secret` Secret string used to compute hash 83 * 84 * Ignore Paths: 85 * 86 * By default `/favicon.ico` is the only ignored path, all others 87 * will utilize sessions, to manipulate the paths ignored, use 88 * `connect.session.ignore.push('/my/path')`. This works for _full_ 89 * pathnames only, not segments nor substrings. 90 * 91 * connect.session.ignore.push('/robots.txt'); 92 * 93 * ## req.session 94 * 95 * To store or access session data, simply use the request property `req.session`, 96 * which is (generally) serialized as JSON by the store, so nested objects 97 * are typically fine. For example below is a user-specific view counter: 98 * 99 * connect( 100 * connect.cookieParser() 101 * , connect.session({ secret: 'keyboard cat', cookie: { maxAge: 60000 }}) 102 * , connect.favicon() 103 * , function(req, res, next){ 104 * var sess = req.session; 105 * if (sess.views) { 106 * res.setHeader('Content-Type', 'text/html'); 107 * res.write('<p>views: ' + sess.views + '</p>'); 108 * res.write('<p>expires in: ' + (sess.cookie.maxAge / 1000) + 's</p>'); 109 * res.end(); 110 * sess.views++; 111 * } else { 112 * sess.views = 1; 113 * res.end('welcome to the session demo. refresh!'); 114 * } 115 * } 116 * ).listen(3000); 117 * 118 * ## Session#regenerate() 119 * 120 * To regenerate the session simply invoke the method, once complete 121 * a new SID and `Session` instance will be initialized at `req.session`. 122 * 123 * req.session.regenerate(function(err){ 124 * // will have a new session here 125 * }); 126 * 127 * ## Session#destroy() 128 * 129 * Destroys the session, removing `req.session`, will be re-generated next request. 130 * 131 * req.session.destroy(function(err){ 132 * // cannot access session here 133 * }); 134 * 135 * ## Session#reload() 136 * 137 * Reloads the session data. 138 * 139 * req.session.reload(function(err){ 140 * // session updated 141 * }); 142 * 143 * ## Session#save() 144 * 145 * Save the session. 146 * 147 * req.session.save(function(err){ 148 * // session saved 149 * }); 150 * 151 * ## Session#touch() 152 * 153 * Updates the `.maxAge`, and `.lastAccess` properties. Typically this is 154 * not necessary to call, as the session middleware does this for you. 155 * 156 * ## Session#cookie 157 * 158 * Each session has a unique cookie object accompany it. This allows 159 * you to alter the session cookie per visitor. For example we can 160 * set `req.session.cookie.expires` to `false` to enable the cookie 161 * to remain for only the duration of the user-agent. 162 * 163 * ## Session#maxAge 164 * 165 * Alternatively `req.session.cookie.maxAge` will return the time 166 * remaining in milliseconds, which we may also re-assign a new value 167 * to adjust the `.expires` property appropriately. The following 168 * are essentially equivalent 169 * 170 * var hour = 3600000; 171 * req.session.cookie.expires = new Date(Date.now() + hour); 172 * req.session.cookie.maxAge = hour; 173 * 174 * For example when `maxAge` is set to `60000` (one minute), and 30 seconds 175 * has elapsed it will return `30000` until the current request has completed, 176 * at which time `req.session.touch()` is called to update `req.session.lastAccess`, 177 * and reset `req.session.maxAge` to its original value. 178 * 179 * req.session.cookie.maxAge; 180 * // => 30000 181 * 182 * Session Store Implementation: 183 * 184 * Every session store _must_ implement the following methods 185 * 186 * - `.get(sid, callback)` 187 * - `.set(sid, session, callback)` 188 * - `.destroy(sid, callback)` 189 * 190 * Recommended methods include, but are not limited to: 191 * 192 * - `.length(callback)` 193 * - `.clear(callback)` 194 * 195 * For an example implementation view the [connect-redis](http://github.com/visionmedia/connect-redis) repo. 196 * 197 * @param {Object} options 198 * @return {Function} 199 * @api public 200 */ 201 202function session(options){ 203 var options = options || {} 204 , key = options.key || 'connect.sid' 205 , secret = options.secret 206 , store = options.store || new MemoryStore 207 , fingerprint = options.fingerprint || defaultFingerprint 208 , cookie = options.cookie; 209 210 // notify user that this store is not 211 // meant for a production environment 212 if ('production' == env && store instanceof MemoryStore) { 213 console.warn(warning); 214 } 215 216 // ensure secret is present 217 if (!secret) { 218 throw new Error('connect.session({ secret: "string" }) required for security'); 219 } 220 221 // session hashing function 222 store.hash = function(req, base) { 223 return crypto 224 .createHmac('sha256', secret) 225 .update(base + fingerprint(req)) 226 .digest('base64') 227 .replace(/=*$/, ''); 228 }; 229 230 // generates the new session 231 store.generate = function(req){ 232 var base = utils.uid(24); 233 var sessionID = base + '.' + store.hash(req, base); 234 req.sessionID = sessionID; 235 req.session = new Session(req); 236 req.session.cookie = new Cookie(cookie); 237 }; 238 239 return function session(req, res, next) { 240 // self-awareness 241 if (req.session) return next(); 242 243 // parse url 244 var url = parse(req.url) 245 , path = url.pathname; 246 247 // ignorable paths 248 if (~exports.ignore.indexOf(path)) return next(); 249 250 // expose store 251 req.sessionStore = store; 252 253 // proxy writeHead() to Set-Cookie 254 var writeHead = res.writeHead; 255 res.writeHead = function(status, headers){ 256 if (req.session) { 257 var cookie = req.session.cookie; 258 // only send secure session cookies when there is a secure connection. 259 // proxySecure is a custom attribute to allow for a reverse proxy 260 // to handle SSL connections and to communicate to connect over HTTP that 261 // the incoming connection is secure. 262 var secured = cookie.secure && (req.connection.encrypted || req.connection.proxySecure); 263 if (secured || !cookie.secure) { 264 res.setHeader('Set-Cookie', cookie.serialize(key, req.sessionID)); 265 } 266 } 267 268 res.writeHead = writeHead; 269 return res.writeHead(status, headers); 270 }; 271 272 // proxy end() to commit the session 273 var end = res.end; 274 res.end = function(data, encoding){ 275 res.end = end; 276 if (req.session) { 277 // HACK: ensure Set-Cookie for implicit writeHead() 278 if (!res._header) res._implicitHeader(); 279 req.session.resetMaxAge(); 280 req.session.save(function(){ 281 res.end(data, encoding); 282 }); 283 } else { 284 res.end(data, encoding); 285 } 286 }; 287 288 // session hashing 289 function hash(base) { 290 return store.hash(req, base); 291 } 292 293 // generate the session 294 function generate() { 295 store.generate(req); 296 } 297 298 // get the sessionID from the cookie 299 req.sessionID = req.cookies[key]; 300 301 // make a new session if the browser doesn't send a sessionID 302 if (!req.sessionID) { 303 generate(); 304 next(); 305 return; 306 } 307 308 // check the fingerprint 309 var parts = req.sessionID.split('.'); 310 if (parts[1] != hash(parts[0])) { 311 generate(); 312 next(); 313 return; 314 } 315 316 // generate the session object 317 var pause = utils.pause(req); 318 store.get(req.sessionID, function(err, sess){ 319 // proxy to resume() events 320 var _next = next; 321 next = function(err){ 322 _next(err); 323 pause.resume(); 324 } 325 326 // error handling 327 if (err) { 328 if ('ENOENT' == err.code) { 329 generate(); 330 next(); 331 } else { 332 next(err); 333 } 334 // no session 335 } else if (!sess) { 336 generate(); 337 next(); 338 // populate req.session 339 } else { 340 store.createSession(req, sess); 341 next(); 342 } 343 }); 344 }; 345};