UNPKG

1.05 kBJavaScriptView Raw
1/*!
2 * cookie.js - cookie middleware for bweb
3 * Copyright (c) 2017, Christopher Jeffrey (MIT License).
4 * https://github.com/bcoin-org/bweb
5 */
6
7'use strict';
8
9/**
10 * Cookie parsing middleware.
11 * @param {String} prefix
12 * @returns {Function}
13 */
14
15function cookieParser() {
16 return async (req, res) => {
17 const hdr = req.headers['cookie'];
18
19 if (!hdr)
20 return;
21
22 req.cookies = parseCookies(hdr);
23 };
24}
25
26/*
27 * Helpers
28 */
29
30function parseCookies(hdr) {
31 const parts = hdr.split(/; */);
32 const cookies = Object.create(null);
33
34 for (const part of parts) {
35 const index = part.indexOf('=');
36
37 let key = part;
38 let value = '';
39
40 if (index !== -1) {
41 key = part.substring(0, index);
42 value = part.substring(index + 1);
43 if (value[0] === '"')
44 value = value.slice(1, -1);
45 }
46
47 if (key.length > 0) {
48 try {
49 value = decodeURIComponent(value);
50 } catch (e) {
51 ;
52 }
53 cookies[key] = value;
54 }
55 }
56
57 return cookies;
58}
59
60/*
61 * Expose
62 */
63
64module.exports = cookieParser;