Ohm-Management - Projektarbeit B-ME
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

index.js 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  1. 'use strict'
  2. const MongoClient = require('mongodb')
  3. function withCallback(promise, cb) {
  4. // Assume that cb is a function - type checks and handling type errors
  5. // can be done by caller
  6. if (cb) {
  7. promise.then(res => cb(null, res)).catch(cb)
  8. }
  9. return promise
  10. }
  11. function defaultSerializeFunction(session) {
  12. // Copy each property of the session to a new object
  13. const obj = {}
  14. let prop
  15. for (prop in session) {
  16. if (prop === 'cookie') {
  17. // Convert the cookie instance to an object, if possible
  18. // This gets rid of the duplicate object under session.cookie.data property
  19. obj.cookie = session.cookie.toJSON
  20. ? session.cookie.toJSON()
  21. : session.cookie
  22. } else {
  23. obj[prop] = session[prop]
  24. }
  25. }
  26. return obj
  27. }
  28. function computeTransformFunctions(options) {
  29. if (options.serialize || options.unserialize) {
  30. return {
  31. serialize: options.serialize || defaultSerializeFunction,
  32. unserialize: options.unserialize || (x => x),
  33. }
  34. }
  35. if (options.stringify === false) {
  36. return {
  37. serialize: defaultSerializeFunction,
  38. unserialize: x => x,
  39. }
  40. }
  41. // Default case
  42. return {
  43. serialize: JSON.stringify,
  44. unserialize: JSON.parse,
  45. }
  46. }
  47. module.exports = function(connect) {
  48. const Store = connect.Store || connect.session.Store
  49. const MemoryStore = connect.MemoryStore || connect.session.MemoryStore
  50. class MongoStore extends Store {
  51. constructor(options) {
  52. options = options || {}
  53. /* Fallback */
  54. if (options.fallbackMemory && MemoryStore) {
  55. return new MemoryStore()
  56. }
  57. super(options)
  58. /* Use crypto? */
  59. if (options.secret) {
  60. try {
  61. this.Crypto = require('./crypto.js')
  62. this.Crypto.init(options)
  63. delete options.secret
  64. } catch (error) {
  65. throw error
  66. }
  67. }
  68. /* Options */
  69. this.ttl = options.ttl || 1209600 // 14 days
  70. this.collectionName = options.collection || 'sessions'
  71. this.autoRemove = options.autoRemove || 'native'
  72. this.autoRemoveInterval = options.autoRemoveInterval || 10 // Minutes
  73. this.writeOperationOptions = options.writeOperationOptions || {}
  74. this.transformFunctions = computeTransformFunctions(options)
  75. this.options = options
  76. this.changeState('init')
  77. const newConnectionCallback = (err, client) => {
  78. if (err) {
  79. this.connectionFailed(err)
  80. } else {
  81. this.handleNewConnectionAsync(client)
  82. }
  83. }
  84. if (options.url) {
  85. // New native connection using url + mongoOptions
  86. const _options = options.mongoOptions || {}
  87. if (typeof _options.useNewUrlParser !== 'boolean') {
  88. _options.useNewUrlParser = true
  89. }
  90. MongoClient.connect(options.url, _options, newConnectionCallback)
  91. } else if (options.mongooseConnection) {
  92. // Re-use existing or upcoming mongoose connection
  93. if (options.mongooseConnection.readyState === 1) {
  94. this.handleNewConnectionAsync(options.mongooseConnection)
  95. } else {
  96. options.mongooseConnection.once('open', () =>
  97. this.handleNewConnectionAsync(options.mongooseConnection)
  98. )
  99. }
  100. } else if (options.client) {
  101. if (options.client.isConnected()) {
  102. this.handleNewConnectionAsync(options.client)
  103. } else {
  104. options.client.once('open', () =>
  105. this.handleNewConnectionAsync(options.client)
  106. )
  107. }
  108. } else if (options.clientPromise) {
  109. options.clientPromise
  110. .then(client => this.handleNewConnectionAsync(client))
  111. .catch(err => this.connectionFailed(err))
  112. } else {
  113. throw new Error('Connection strategy not found')
  114. }
  115. this.changeState('connecting')
  116. }
  117. connectionFailed(err) {
  118. this.changeState('disconnected')
  119. throw err
  120. }
  121. handleNewConnectionAsync(client) {
  122. this.client = client
  123. this.db = typeof client.db !== 'function' ? client.db : client.db()
  124. return this.setCollection(this.db.collection(this.collectionName))
  125. .setAutoRemoveAsync()
  126. .then(() => this.changeState('connected'))
  127. }
  128. setAutoRemoveAsync() {
  129. const removeQuery = () => {
  130. return { expires: { $lt: new Date() } }
  131. }
  132. switch (this.autoRemove) {
  133. case 'native':
  134. return this.collection.createIndex(
  135. { expires: 1 },
  136. Object.assign({ expireAfterSeconds: 0 }, this.writeOperationOptions)
  137. )
  138. case 'interval':
  139. this.timer = setInterval(
  140. () =>
  141. this.collection.deleteMany(
  142. removeQuery(),
  143. Object.assign({}, this.writeOperationOptions, {
  144. w: 0,
  145. j: false,
  146. })
  147. ),
  148. this.autoRemoveInterval * 1000 * 60
  149. )
  150. this.timer.unref()
  151. return Promise.resolve()
  152. default:
  153. return Promise.resolve()
  154. }
  155. }
  156. changeState(newState) {
  157. if (newState !== this.state) {
  158. this.state = newState
  159. this.emit(newState)
  160. }
  161. }
  162. setCollection(collection) {
  163. if (this.timer) {
  164. clearInterval(this.timer)
  165. }
  166. this.collectionReadyPromise = undefined
  167. this.collection = collection
  168. return this
  169. }
  170. collectionReady() {
  171. let promise = this.collectionReadyPromise
  172. if (!promise) {
  173. promise = new Promise((resolve, reject) => {
  174. if (this.state === 'connected') {
  175. return resolve(this.collection)
  176. }
  177. if (this.state === 'connecting') {
  178. return this.once('connected', () => resolve(this.collection))
  179. }
  180. reject(new Error('Not connected'))
  181. })
  182. this.collectionReadyPromise = promise
  183. }
  184. return promise
  185. }
  186. computeStorageId(sessionId) {
  187. if (
  188. this.options.transformId &&
  189. typeof this.options.transformId === 'function'
  190. ) {
  191. return this.options.transformId(sessionId)
  192. }
  193. return sessionId
  194. }
  195. /* Public API */
  196. get(sid, callback) {
  197. return withCallback(
  198. this.collectionReady()
  199. .then(collection =>
  200. collection.findOne({
  201. _id: this.computeStorageId(sid),
  202. $or: [
  203. { expires: { $exists: false } },
  204. { expires: { $gt: new Date() } },
  205. ],
  206. })
  207. )
  208. .then(session => {
  209. if (session) {
  210. if (this.Crypto) {
  211. const tmpSession = this.transformFunctions.unserialize(
  212. session.session
  213. )
  214. session.session = this.Crypto.get(tmpSession)
  215. }
  216. const s = this.transformFunctions.unserialize(session.session)
  217. if (this.options.touchAfter > 0 && session.lastModified) {
  218. s.lastModified = session.lastModified
  219. }
  220. this.emit('get', sid)
  221. return s
  222. }
  223. }),
  224. callback
  225. )
  226. }
  227. set(sid, session, callback) {
  228. // Removing the lastModified prop from the session object before update
  229. if (this.options.touchAfter > 0 && session && session.lastModified) {
  230. delete session.lastModified
  231. }
  232. let s
  233. if (this.Crypto) {
  234. try {
  235. session = this.Crypto.set(session)
  236. } catch (error) {
  237. return withCallback(Promise.reject(error), callback)
  238. }
  239. }
  240. try {
  241. s = {
  242. _id: this.computeStorageId(sid),
  243. session: this.transformFunctions.serialize(session),
  244. }
  245. } catch (err) {
  246. return withCallback(Promise.reject(err), callback)
  247. }
  248. if (session && session.cookie && session.cookie.expires) {
  249. s.expires = new Date(session.cookie.expires)
  250. } else {
  251. // If there's no expiration date specified, it is
  252. // browser-session cookie or there is no cookie at all,
  253. // as per the connect docs.
  254. //
  255. // So we set the expiration to two-weeks from now
  256. // - as is common practice in the industry (e.g Django) -
  257. // or the default specified in the options.
  258. s.expires = new Date(Date.now() + this.ttl * 1000)
  259. }
  260. if (this.options.touchAfter > 0) {
  261. s.lastModified = new Date()
  262. }
  263. return withCallback(
  264. this.collectionReady()
  265. .then(collection =>
  266. collection.updateOne(
  267. { _id: this.computeStorageId(sid) },
  268. { $set: s },
  269. Object.assign({ upsert: true }, this.writeOperationOptions)
  270. )
  271. )
  272. .then(rawResponse => {
  273. if (rawResponse.result) {
  274. rawResponse = rawResponse.result
  275. }
  276. if (rawResponse && rawResponse.upserted) {
  277. this.emit('create', sid)
  278. } else {
  279. this.emit('update', sid)
  280. }
  281. this.emit('set', sid)
  282. }),
  283. callback
  284. )
  285. }
  286. touch(sid, session, callback) {
  287. const updateFields = {}
  288. const touchAfter = this.options.touchAfter * 1000
  289. const lastModified = session.lastModified
  290. ? session.lastModified.getTime()
  291. : 0
  292. const currentDate = new Date()
  293. // If the given options has a touchAfter property, check if the
  294. // current timestamp - lastModified timestamp is bigger than
  295. // the specified, if it's not, don't touch the session
  296. if (touchAfter > 0 && lastModified > 0) {
  297. const timeElapsed = currentDate.getTime() - session.lastModified
  298. if (timeElapsed < touchAfter) {
  299. return withCallback(Promise.resolve(), callback)
  300. }
  301. updateFields.lastModified = currentDate
  302. }
  303. if (session && session.cookie && session.cookie.expires) {
  304. updateFields.expires = new Date(session.cookie.expires)
  305. } else {
  306. updateFields.expires = new Date(Date.now() + this.ttl * 1000)
  307. }
  308. return withCallback(
  309. this.collectionReady()
  310. .then(collection =>
  311. collection.updateOne(
  312. { _id: this.computeStorageId(sid) },
  313. { $set: updateFields },
  314. this.writeOperationOptions
  315. )
  316. )
  317. .then(result => {
  318. if (result.nModified === 0) {
  319. throw new Error('Unable to find the session to touch')
  320. } else {
  321. this.emit('touch', sid, session)
  322. }
  323. }),
  324. callback
  325. )
  326. }
  327. all(callback) {
  328. return withCallback(
  329. this.collectionReady()
  330. .then(collection =>
  331. collection.find({
  332. $or: [
  333. { expires: { $exists: false } },
  334. { expires: { $gt: new Date() } },
  335. ],
  336. })
  337. )
  338. .then(sessions => {
  339. return new Promise((resolve, reject) => {
  340. const results = []
  341. sessions.forEach(
  342. session =>
  343. results.push(
  344. this.transformFunctions.unserialize(session.session)
  345. ),
  346. err => {
  347. if (err) {
  348. reject(err)
  349. }
  350. this.emit('all', results)
  351. resolve(results)
  352. }
  353. )
  354. })
  355. }),
  356. callback
  357. )
  358. }
  359. destroy(sid, callback) {
  360. return withCallback(
  361. this.collectionReady()
  362. .then(collection =>
  363. collection.deleteOne(
  364. { _id: this.computeStorageId(sid) },
  365. this.writeOperationOptions
  366. )
  367. )
  368. .then(() => this.emit('destroy', sid)),
  369. callback
  370. )
  371. }
  372. length(callback) {
  373. return withCallback(
  374. this.collectionReady().then(collection =>
  375. collection.countDocuments({})
  376. ),
  377. callback
  378. )
  379. }
  380. clear(callback) {
  381. return withCallback(
  382. this.collectionReady().then(collection =>
  383. collection.drop(this.writeOperationOptions)
  384. ),
  385. callback
  386. )
  387. }
  388. close() {
  389. if (this.client) {
  390. return this.client.close()
  391. }
  392. }
  393. }
  394. return MongoStore
  395. }