mirror of
https://github.com/zebrajr/express.git
synced 2025-12-06 12:19:51 +01:00
Added res.signedCookie() and tests. Closes #880
This commit is contained in:
parent
7ac857acef
commit
58eddd5ab4
|
|
@ -346,6 +346,24 @@ res.clearCookie = function(name, options){
|
|||
: opts);
|
||||
};
|
||||
|
||||
/**
|
||||
* Set a signed cookie with the given `name` and `val`.
|
||||
* See `res.cookie()` for details.
|
||||
*
|
||||
* @param {String} name
|
||||
* @param {String|Object} val
|
||||
* @param {Object} options
|
||||
* @api public
|
||||
*/
|
||||
|
||||
res.signedCookie = function(name, val, options){
|
||||
var secret = this.req.secret;
|
||||
if (!secret) throw new Error('connect.cookieParser("secret") required for signed cookies');
|
||||
if ('object' == typeof val) val = 'j:' + JSON.stringify(val);
|
||||
val = utils.sign(val, secret);
|
||||
return this.cookie(name, val, options);
|
||||
};
|
||||
|
||||
/**
|
||||
* Set cookie `name` to `val`, with the given `options`.
|
||||
*
|
||||
|
|
@ -363,7 +381,7 @@ res.clearCookie = function(name, options){
|
|||
* res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })
|
||||
*
|
||||
* @param {String} name
|
||||
* @param {String} val
|
||||
* @param {String|Object} val
|
||||
* @param {Options} options
|
||||
* @api public
|
||||
*/
|
||||
|
|
|
|||
45
test/res.signedCookie.js
Normal file
45
test/res.signedCookie.js
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
|
||||
var express = require('../')
|
||||
, request = require('./support/http');
|
||||
|
||||
describe('res', function(){
|
||||
describe('.signedCook(name, object)', function(){
|
||||
it('should generate a signed JSON cookie', function(done){
|
||||
var app = express();
|
||||
|
||||
app.use(express.cookieParser('foo bar baz'));
|
||||
|
||||
app.use(function(req, res){
|
||||
res.signedCookie('user', { name: 'tobi' }).end();
|
||||
});
|
||||
|
||||
request(app)
|
||||
.get('/')
|
||||
.end(function(res){
|
||||
var val = ['user=j%3A%7B%22name%22%3A%22tobi%22%7D.aEbp4PGZo63zMX%2FcIMSn2M9pvms; path=/'];
|
||||
res.headers['set-cookie'].should.eql(val);
|
||||
done();
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('.signedCookie(name, string)', function(){
|
||||
it('should set a signed cookie', function(done){
|
||||
var app = express();
|
||||
|
||||
app.use(express.cookieParser('foo bar baz'));
|
||||
|
||||
app.use(function(req, res){
|
||||
res.signedCookie('name', 'tobi').end();
|
||||
});
|
||||
|
||||
request(app)
|
||||
.get('/')
|
||||
.end(function(res){
|
||||
var val = ['name=tobi.2HDdGQqJ6jQU1S9dagggYDPaxGE; path=/'];
|
||||
res.headers['set-cookie'].should.eql(val);
|
||||
done();
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
Loading…
Reference in New Issue
Block a user