@@ -142,11 +142,7 @@ function session(options){
142
142
store . generate = function ( req ) {
143
143
req . sessionID = generateId ( req ) ;
144
144
req . session = new Session ( req ) ;
145
- req . session . cookie = new Cookie ( cookieOptions ) ;
146
-
147
- if ( cookieOptions . secure === 'auto' ) {
148
- req . session . cookie . secure = issecure ( req , trustProxy ) ;
149
- }
145
+ req . session . cookie = createCookie ( cookieOptions , req , trustProxy ) ;
150
146
} ;
151
147
152
148
var storeImplementsTouch = typeof store . touch === 'function' ;
@@ -187,26 +183,46 @@ function session(options){
187
183
188
184
// set-cookie
189
185
onHeaders ( res , function ( ) {
186
+ // Is this an existing session that is being destroyed?
187
+ var isBeingDestroyed = ! ! cookieId && shouldDestroy ( req ) ;
188
+
190
189
if ( ! req . session ) {
191
190
debug ( 'no session' ) ;
192
- return ;
191
+ if ( ! isBeingDestroyed ) {
192
+ return ;
193
+ }
193
194
}
194
195
195
- if ( ! shouldSetCookie ( req ) ) {
196
- return ;
196
+ var cookie = req . session ? req . session . cookie : undefined ;
197
+
198
+ if ( isBeingDestroyed ) {
199
+ if ( cookie == null ) {
200
+ debug ( 'creating expired cookie' ) ;
201
+ cookie = createCookie ( cookieOptions , req , trustProxy ) ;
202
+ }
203
+
204
+ // Set the cookie to immediately expire on the client
205
+ cookie . maxAge = 0 ;
197
206
}
198
207
199
208
// only send secure cookies via https
200
- if ( req . session . cookie . secure && ! issecure ( req , trustProxy ) ) {
209
+ if ( cookie . secure && ! issecure ( req , trustProxy ) ) {
201
210
debug ( 'not secured' ) ;
202
211
return ;
203
212
}
204
213
205
- // touch session
206
- req . session . touch ( ) ;
214
+ if ( ! isBeingDestroyed ) {
215
+ if ( ! shouldSetCookie ( req ) ) {
216
+ return ;
217
+ }
218
+ else {
219
+ // touch session
220
+ req . session . touch ( ) ;
221
+ }
222
+ }
207
223
208
224
// set cookie
209
- setcookie ( res , name , req . sessionID , secrets [ 0 ] , req . session . cookie . data ) ;
225
+ setcookie ( res , name , req . sessionID , secrets [ 0 ] , cookie . data ) ;
210
226
} ) ;
211
227
212
228
// proxy end() to commit the session
@@ -436,6 +452,25 @@ function session(options){
436
452
} ;
437
453
} ;
438
454
455
+ /**
456
+ * Create a new Cookie for this request.
457
+ *
458
+ * @param {Object } cookieOptions
459
+ * @param {Object } req
460
+ * @param {Boolean } [trustProxy]
461
+ * @return {Cookie }
462
+ * @private
463
+ */
464
+ function createCookie ( cookieOptions , req , trustProxy ) {
465
+ var cookieOpts = cookieOptions || { } ;
466
+
467
+ var cookie = new Cookie ( cookieOpts ) ;
468
+ if ( cookieOpts . secure === 'auto' ) {
469
+ cookie . secure = issecure ( req , trustProxy ) ;
470
+ }
471
+ return cookie ;
472
+ }
473
+
439
474
/**
440
475
* Generate a session ID for a new session.
441
476
*
0 commit comments