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