test_auth.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. /**
  2. * Created by bmf on 11/2/13.
  3. */
  4. var assert = require('assert');
  5. var sodium = require('../build/Release/sodium');
  6. var Auth = require('../lib/auth');
  7. if (process.env.COVERAGE) {
  8. Auth = require('../lib-cov/auth');
  9. }
  10. describe("Auth", function () {
  11. it("generate token and validate message", function (done) {
  12. var auth = new Auth();
  13. var token = auth.generate("This is a test", 'utf8');
  14. assert.ok(auth.validate(token, "This is a test", 'utf8'));
  15. done();
  16. });
  17. it("key size should match that of sodium", function (done) {
  18. var auth = new Auth();
  19. assert.equal(auth.key().size(), sodium.crypto_auth_KEYBYTES);
  20. done();
  21. });
  22. it("generate return false on a bad token", function (done) {
  23. var auth = new Auth();
  24. auth.key().generate();
  25. var token = auth.generate("This is a test", 'utf8');
  26. token[0] = 99;
  27. token[1] = 99;
  28. token[2] = 99;
  29. assert.equal(auth.validate(token, "This is a test", 'utf8'), false);
  30. done();
  31. });
  32. it("set bad secretKey should fail", function (done) {
  33. var auth = new Auth();
  34. assert.throws(function() {
  35. auth.set(Buffer.allocUnsafe(2));
  36. });
  37. done();
  38. });
  39. it("set/get secretKey", function (done) {
  40. var auth = new Auth();
  41. auth.key().generate();
  42. var k = auth.key().get();
  43. var auth2 = new Auth();
  44. auth2.key().set(k);
  45. k2 = auth2.key().get();
  46. assert.equal(k2, k);
  47. done();
  48. });
  49. it('should fail call validate before having a key', function() {
  50. var auth = new Auth();
  51. assert.throws(function() {
  52. auth.validate("123123", "123123");
  53. });
  54. });
  55. it('should set an encoding if a supported encoding is passed to setEncoding', function() {
  56. var auth = new Auth();
  57. auth.setEncoding('base64');
  58. assert.equal(auth.defaultEncoding, 'base64');
  59. });
  60. it('should fail to set an encoding if an unsupported encoding is passed to setEncoding', function() {
  61. var auth = new Auth();
  62. assert.throws(function () {
  63. auth.setEncoding('unsupported-encoding');
  64. });
  65. });
  66. });