Skip to content

Instantly share code, notes, and snippets.

@ishan1608
Created February 8, 2015 12:18
Show Gist options
  • Save ishan1608/9b87247e129513367cef to your computer and use it in GitHub Desktop.
Save ishan1608/9b87247e129513367cef to your computer and use it in GitHub Desktop.
A node.js server to set the cookies and check them.
var http = require( "http" )
var Cookies = require( "cookies" )
var keygrip = require("keygrip")
var assert = require("assert")
server = http.createServer( function( req, res ) {
var keys = keygrip(["SEKRIT2", "SEKRIT1"], 'sha256', 'hex')
var cookies = new Cookies( req, res, keys )
, unsigned, signed, tampered
if ( req.url == "/set" ) {
cookies
// set a regular cookie
.set( "unsigned", "foo", { httpOnly: false } )
// set a signed cookie
.set( "signed", "bar", { signed: true } )
// mimic a signed cookie, but with a bogus signature
.set( "tampered", "baz" )
.set( "tampered.sig", "bogus" )
res.writeHead( 302, { "Location": "/" } )
return res.end( "Now let's check." )
}
unsigned = cookies.get( "unsigned" )
signed = cookies.get( "signed", { signed: true } )
tampered = cookies.get( "tampered", { signed: true } )
var assertionError = false;
try{
assert.equal( unsigned, "foo" )
assert.equal( signed, "bar" )
assert.notEqual( tampered, "baz" )
assert.equal( tampered, undefined )
} catch(err) {
assertionError = true;
}
res.writeHead( 200, { "Content-Type": "text/html" } )
res.write("<!doctype html><html><body>");
if(assertionError) res.write("There was an error while checking for cookies, maybe they are not set.<a href='/set'>Click here</a> to set the cookies first.<br/><br/>");
res.end(
"unsigned expected: foo\n\n" + "<br/><br/>" +
"unsigned actual: " + unsigned + "<br/><br/>" +
"signed expected: bar" + "<br/><br/>" +
"signed actual: " + signed + "<br/><br/>" +
"tampered expected: undefined"+ "<br/><br/>" +
"tampered: " + tampered + "<br/><br/>" + "</body></html>"
)
}).listen(3000);
console.log('Server started at port : 3000');
{
"name": "CookieTest",
"version": "0.0.0",
"description": "Cookie Testing server.",
"main": "app.js",
"engines": {
"node": "0.10.x"
},
"dependencies": {
"cookies": "^0.5.0",
"keygrip": "^1.0.1"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment