token.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. const crypto = require('crypto');
  2. class Token {
  3. constructor (secret, time) {
  4. if(typeof secret != 'string' || typeof time != 'number') {
  5. throw new Error('Bad type: secret = string and time = number');
  6. }
  7. this.secret = secret;
  8. this.time = time;
  9. }
  10. generate(data) {
  11. data = JSON.stringify(data) || '';
  12. // Calcul timestamp actuel + timestamp expiration token
  13. const timestamp = Math.floor(new Date().getTime() / 1000);
  14. const endtime = timestamp + this.time;
  15. // Création d'un hash
  16. let hash = data.toLowerCase() + this.secret + endtime;
  17. hash = crypto.createHash('sha512').update(hash).digest('base64');
  18. hash = hash.replace(/=/g, '');
  19. // Le token correspond au timestamp de fin + le hash
  20. return endtime + '.' + hash;
  21. }
  22. validate(token, data) {
  23. // Verification que le token correspond au format attendu
  24. if(typeof token != 'string') {
  25. return false;
  26. }
  27. const split = token.split('.');
  28. if(split.length != 2) {
  29. return false;
  30. }
  31. // Recreation du hash supposé du token
  32. data = JSON.stringify(data) || '';
  33. let hash = data.toLowerCase() + this.secret + split[0];
  34. hash = crypto.createHash('sha512').update(hash).digest('base64');
  35. hash = hash.replace(/=/g, '');
  36. // Verification que la hash est le même que celui du token passé en parametre
  37. return hash == split[1];
  38. }
  39. }
  40. module.exports = Token;