OneTimeTokenHandler.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. /* eslint-disable
  2. handle-callback-err,
  3. max-len,
  4. no-unused-vars,
  5. */
  6. // TODO: This file was created by bulk-decaffeinate.
  7. // Fix any style issues and re-enable lint.
  8. /*
  9. * decaffeinate suggestions:
  10. * DS102: Remove unnecessary code created because of implicit returns
  11. * DS207: Consider shorter variations of null checks
  12. * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
  13. */
  14. const Settings = require('settings-sharelatex')
  15. const crypto = require('crypto')
  16. const logger = require('logger-sharelatex')
  17. const { db } = require('../../infrastructure/mongojs')
  18. const Errors = require('../Errors/Errors')
  19. const ONE_HOUR_IN_S = 60 * 60
  20. module.exports = {
  21. getNewToken(use, data, options, callback) {
  22. // options is optional
  23. if (options == null) {
  24. options = {}
  25. }
  26. if (callback == null) {
  27. callback = function(error, data) {}
  28. }
  29. if (typeof options === 'function') {
  30. callback = options
  31. options = {}
  32. }
  33. const expiresIn = options.expiresIn || ONE_HOUR_IN_S
  34. const createdAt = new Date()
  35. const expiresAt = new Date(createdAt.getTime() + expiresIn * 1000)
  36. const token = crypto.randomBytes(32).toString('hex')
  37. return db.tokens.insert(
  38. {
  39. use,
  40. token,
  41. data,
  42. createdAt,
  43. expiresAt
  44. },
  45. function(error) {
  46. if (error != null) {
  47. return callback(error)
  48. }
  49. return callback(null, token)
  50. }
  51. )
  52. },
  53. getValueFromTokenAndExpire(use, token, callback) {
  54. if (callback == null) {
  55. callback = function(error, data) {}
  56. }
  57. const now = new Date()
  58. return db.tokens.findAndModify(
  59. {
  60. query: {
  61. use,
  62. token,
  63. expiresAt: { $gt: now },
  64. usedAt: { $exists: false }
  65. },
  66. update: {
  67. $set: {
  68. usedAt: now
  69. }
  70. }
  71. },
  72. function(error, token) {
  73. if (error != null) {
  74. return callback(error)
  75. }
  76. if (token == null) {
  77. return callback(new Errors.NotFoundError('no token found'))
  78. }
  79. return callback(null, token.data)
  80. }
  81. )
  82. }
  83. }