2014-05-15 12:16:20 -04:00
|
|
|
Settings = require('settings-sharelatex')
|
2014-05-16 05:52:31 -04:00
|
|
|
crypto = require("crypto")
|
2014-05-15 13:08:21 -04:00
|
|
|
logger = require("logger-sharelatex")
|
2018-06-20 12:27:22 -04:00
|
|
|
{db} = require "../../infrastructure/mongojs"
|
|
|
|
Errors = require "../Errors/Errors"
|
2014-05-15 12:16:20 -04:00
|
|
|
|
2014-05-15 12:58:25 -04:00
|
|
|
ONE_HOUR_IN_S = 60 * 60
|
|
|
|
|
2014-05-15 12:16:20 -04:00
|
|
|
module.exports =
|
2018-06-20 12:27:22 -04:00
|
|
|
getNewToken: (use, data, options = {}, callback = (error, data) ->)->
|
2015-03-19 10:22:48 -04:00
|
|
|
# options is optional
|
|
|
|
if typeof options == "function"
|
|
|
|
callback = options
|
|
|
|
options = {}
|
|
|
|
expiresIn = options.expiresIn or ONE_HOUR_IN_S
|
2018-06-20 12:27:22 -04:00
|
|
|
createdAt = new Date()
|
|
|
|
expiresAt = new Date(createdAt.getTime() + expiresIn * 1000)
|
2014-05-16 05:52:31 -04:00
|
|
|
token = crypto.randomBytes(32).toString("hex")
|
2018-06-20 12:27:22 -04:00
|
|
|
logger.log {data, expiresIn, token_start: token.slice(0,8)}, "generating token for #{use}"
|
|
|
|
db.tokens.insert {
|
|
|
|
use: use
|
|
|
|
token: token,
|
|
|
|
data: data,
|
|
|
|
createdAt: createdAt,
|
|
|
|
expiresAt: expiresAt
|
|
|
|
}, (error) ->
|
|
|
|
return callback(error) if error?
|
|
|
|
callback null, token
|
2014-05-15 12:16:20 -04:00
|
|
|
|
2018-06-20 12:27:22 -04:00
|
|
|
getValueFromTokenAndExpire: (use, token, callback = (error, data) ->)->
|
|
|
|
logger.log token_start: token.slice(0,8), "getting data from #{use} token"
|
|
|
|
now = new Date()
|
|
|
|
db.tokens.findAndModify {
|
|
|
|
query: {
|
|
|
|
use: use,
|
|
|
|
token: token,
|
|
|
|
expiresAt: { $gt: now },
|
|
|
|
usedAt: { $exists: false }
|
|
|
|
},
|
|
|
|
update: {
|
|
|
|
$set: {
|
|
|
|
usedAt: now
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}, (error, token) ->
|
|
|
|
return callback(error) if error?
|
|
|
|
if !token?
|
|
|
|
return callback(new Errors.NotFoundError('no token found'))
|
|
|
|
return callback null, token.data
|
2014-05-15 12:20:42 -04:00
|
|
|
|