3 * Copyright(c) 2014 TJ Holowaychuk
4 * Copyright(c) 2015 Douglas Christopher Wilson
11 * Module dependencies.
15 var cookie = require('cookie')
16 var signature = require('cookie-signature')
23 module.exports = cookieParser
24 module.exports.JSONCookie = JSONCookie
25 module.exports.JSONCookies = JSONCookies
26 module.exports.signedCookie = signedCookie
27 module.exports.signedCookies = signedCookies
30 * Parse Cookie header and populate `req.cookies`
31 * with an object keyed by the cookie names.
33 * @param {string|array} [secret] A string (or array of strings) representing cookie signing secret(s).
34 * @param {Object} [options]
39 function cookieParser (secret, options) {
40 var secrets = !secret || Array.isArray(secret)
44 return function cookieParser (req, res, next) {
49 var cookies = req.headers.cookie
51 req.secret = secrets[0]
52 req.cookies = Object.create(null)
53 req.signedCookies = Object.create(null)
60 req.cookies = cookie.parse(cookies, options)
62 // parse signed cookies
63 if (secrets.length !== 0) {
64 req.signedCookies = signedCookies(req.cookies, secrets)
65 req.signedCookies = JSONCookies(req.signedCookies)
69 req.cookies = JSONCookies(req.cookies)
76 * Parse JSON cookie string.
79 * @return {Object} Parsed object or undefined if not json cookie
83 function JSONCookie (str) {
84 if (typeof str !== 'string' || str.substr(0, 2) !== 'j:') {
89 return JSON.parse(str.slice(2))
103 function JSONCookies (obj) {
104 var cookies = Object.keys(obj)
108 for (var i = 0; i < cookies.length; i++) {
110 val = JSONCookie(obj[key])
121 * Parse a signed cookie string, return the decoded value.
123 * @param {String} str signed cookie string
124 * @param {string|array} secret
125 * @return {String} decoded value
129 function signedCookie (str, secret) {
130 if (typeof str !== 'string') {
134 if (str.substr(0, 2) !== 's:') {
138 var secrets = !secret || Array.isArray(secret)
142 for (var i = 0; i < secrets.length; i++) {
143 var val = signature.unsign(str.slice(2), secrets[i])
154 * Parse signed cookies, returning an object containing the decoded key/value
155 * pairs, while removing the signed key from obj.
157 * @param {Object} obj
158 * @param {string|array} secret
163 function signedCookies (obj, secret) {
164 var cookies = Object.keys(obj)
167 var ret = Object.create(null)
170 for (var i = 0; i < cookies.length; i++) {
173 dec = signedCookie(val, secret)