artdaq_node_server  v1_00_07
 All Classes Namespaces Files Variables Pages
cookies.js
1 
6 function Cookies() {
7  this.cookies = {}
8 }
9 
10 Cookies.prototype = {
17  get: function(name) {
18  var cookie = this.cookies[name]
19  if (cookie && this.checkNotExpired(name)) {
20  return this.cookies[name].value
21  }
22  return null
23  },
24 
33  set: function(name, value, options) {
34  var cookie = typeof options == 'object'
35  ? {value: value, expires: options.expires, secure: options.secure || false, new: options.new || false}
36  : {value: value}
37  if (this.checkNotExpired(name, cookie)) {
38  this.cookies[name] = cookie
39  }
40  },
41 
42  // For testing purposes
43  getExpirationDate: function(name) {
44  return this.cookies[name] ? this.cookies[name].expires : null
45  },
46 
47  // Internal function
48  checkNotExpired: function(name, cookie) {
49  if (typeof cookie === 'undefined') {
50  cookie = this.cookies[name]
51  }
52  var now = new Date()
53  if (cookie && cookie.expires && now > cookie.expires) {
54  delete this.cookies[name]
55  return false
56  }
57  return true
58  },
59 
60 
66  parseResponse: function(headers) {
67  var cookies = headers['set-cookie']
68  if (cookies) {
69  cookies.forEach(function(c) {
70  var cookiesParams = c.split(';')
71  var cookiePair = cookiesParams.shift().split('=')
72  var options = {}
73  cookiesParams.forEach(function(param) {
74  param = param.trim()
75  if (param.toLowerCase().indexOf('expires') == 0) {
76  var date = param.split('=')[1].trim()
77  options.expires = new Date(date)
78  }
79  })
80  this.set(cookiePair[0].trim(), cookiePair[1].trim(), options)
81  }.bind(this))
82  }
83  },
84 
90  composeRequest: function(headers) {
91  if (Object.keys(this.cookies).length == 0) {
92  return
93  }
94  headers['Cookie'] = this.toString()
95  },
96 
97 
102  toString: function() {
103  return Object.keys(this.cookies)
104  .filter(this.checkNotExpired.bind(this))
105  .map(function(name) {
106  return name + '=' + this.cookies[name].value
107  }.bind(this)).join(';')
108  }
109 }
110 
111 module.exports = Cookies