ProjectTokenGenerator.coffee 1.2 KB

123456789101112131415161718192021222324252627282930
  1. crypto = require 'crypto'
  2. # This module mirrors the token generation in Overleaf (`random_token.rb`),
  3. # for the purposes of implementing token-based project access, like the
  4. # 'unlisted-projects' feature in Overleaf
  5. module.exports = ProjectTokenGenerator =
  6. # (From Overleaf `random_token.rb`)
  7. # Letters (not numbers! see generate_token) used in tokens. They're all
  8. # consonsants, to avoid embarassing words (I can't think of any that use only
  9. # a y), and lower case "l" is omitted, because in many fonts it is
  10. # indistinguishable from an upper case "I" (and sometimes even the number 1).
  11. TOKEN_ALPHA: 'bcdfghjkmnpqrstvwxyz'
  12. # Generate a 12-char token with only characters from TOKEN_ALPHA,
  13. # suitable for use as a read-only token for a project
  14. readOnlyToken: () ->
  15. length = 12
  16. tokenAlpha = ProjectTokenGenerator.TOKEN_ALPHA
  17. result = ''
  18. crypto.randomBytes(length).map( (a) -> result += tokenAlpha[a % tokenAlpha.length] )
  19. return result
  20. # Generate a longer token, with a numeric prefix,
  21. # suitable for use as a read-and-write token for a project
  22. readAndWriteToken: () ->
  23. numerics = Math.random().toString().slice(2, 12)
  24. token = ProjectTokenGenerator.readOnlyToken()
  25. return "#{numerics}#{token}"