2017-10-12 06:36:45 -04:00
|
|
|
crypto = require 'crypto'
|
|
|
|
|
2017-10-13 06:37:38 -04:00
|
|
|
# This module mirrors the token generation in Overleaf (`random_token.rb`),
|
|
|
|
# for the purposes of implementing token-based project access, like the
|
|
|
|
# 'unlisted-projects' feature in Overleaf
|
|
|
|
|
2017-10-04 11:31:24 -04:00
|
|
|
module.exports = ProjectTokenGenerator =
|
|
|
|
|
2017-10-13 06:37:38 -04:00
|
|
|
# (From Overleaf `random_token.rb`)
|
|
|
|
# Letters (not numbers! see generate_token) used in tokens. They're all
|
2017-10-19 06:47:47 -04:00
|
|
|
# consonants, to avoid embarassing words (I can't think of any that use only
|
2017-10-13 06:37:38 -04:00
|
|
|
# a y), and lower case "l" is omitted, because in many fonts it is
|
|
|
|
# indistinguishable from an upper case "I" (and sometimes even the number 1).
|
|
|
|
TOKEN_ALPHA: 'bcdfghjkmnpqrstvwxyz'
|
2017-10-26 11:01:53 -04:00
|
|
|
TOKEN_NUMERICS: '123456789'
|
|
|
|
|
|
|
|
_randomString: (length, alphabet) ->
|
2017-10-27 05:38:55 -04:00
|
|
|
result = crypto.randomBytes(length).toJSON().data.map(
|
|
|
|
(b) -> alphabet[b % alphabet.length]
|
|
|
|
).join('')
|
2017-10-26 11:01:53 -04:00
|
|
|
return result
|
2017-10-13 06:37:38 -04:00
|
|
|
|
|
|
|
# Generate a 12-char token with only characters from TOKEN_ALPHA,
|
|
|
|
# suitable for use as a read-only token for a project
|
2017-10-04 11:31:24 -04:00
|
|
|
readOnlyToken: () ->
|
2017-10-26 11:01:53 -04:00
|
|
|
return ProjectTokenGenerator._randomString(
|
|
|
|
12,
|
|
|
|
ProjectTokenGenerator.TOKEN_ALPHA
|
|
|
|
)
|
2017-10-04 11:31:24 -04:00
|
|
|
|
2017-10-13 06:37:38 -04:00
|
|
|
# Generate a longer token, with a numeric prefix,
|
|
|
|
# suitable for use as a read-and-write token for a project
|
2017-10-04 11:31:24 -04:00
|
|
|
readAndWriteToken: () ->
|
2017-10-26 11:01:53 -04:00
|
|
|
numerics = ProjectTokenGenerator._randomString(
|
|
|
|
10,
|
|
|
|
ProjectTokenGenerator.TOKEN_NUMERICS
|
|
|
|
)
|
|
|
|
token = ProjectTokenGenerator._randomString(
|
|
|
|
12,
|
|
|
|
ProjectTokenGenerator.TOKEN_ALPHA
|
|
|
|
)
|
|
|
|
fullToken = "#{numerics}#{token}"
|
|
|
|
return fullToken
|