diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..3c3629e --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +node_modules diff --git a/.jshintrc b/.jshintrc new file mode 100644 index 0000000..0277e25 --- /dev/null +++ b/.jshintrc @@ -0,0 +1,15 @@ +{ + "curly": true, + "eqeqeq": true, + "immed": true, + "latedef": "nofunc", + "newcap": true, + "noarg": true, + "sub": true, + "undef": true, + "unused": true, + "boss": true, + "eqnull": true, + "node": true, + "predef": ["describe", "it", "before", "beforeEach", "after", "afterEach", "module"] +} diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000..fc99440 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,6 @@ +language: node_js +node_js: + - "0.10" + - "0.8" +before_install: + - "npm install -g grunt-cli" \ No newline at end of file diff --git a/Gruntfile.js b/Gruntfile.js new file mode 100644 index 0000000..4957f87 --- /dev/null +++ b/Gruntfile.js @@ -0,0 +1,39 @@ +'use strict'; + +module.exports = function(grunt) { + + grunt.initConfig({ + pkg: grunt.file.readJSON('package.json'), + jshint: { + all: ['src/**/*.js', 'test/**/*.js', 'Gruntfile.js'], + checkstyle: 'checkstyle.xml', + options: { + jshintrc: '.jshintrc' + }, + gruntfile: { + src: 'Gruntfile.js' + }, + src: { + src: ['src/**/*.js'] + }, + test: { + src: ['test/**/*.js'] + } + }, + simplemocha: { + all: { src: 'test/**/*-test.js' }, + options: { + ui: 'bdd', + reporter: 'spec' + } + } + + }); + + // task loading + grunt.loadNpmTasks('grunt-contrib-jshint'); + grunt.loadNpmTasks('grunt-simple-mocha'); + + // ci task + grunt.registerTask('default', ['simplemocha', 'jshint:all']); +}; \ No newline at end of file diff --git a/LICENSE-MIT b/LICENSE-MIT new file mode 100644 index 0000000..5c1764b --- /dev/null +++ b/LICENSE-MIT @@ -0,0 +1,22 @@ +Copyright (c) 2014 Nikolay Tsenkov + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..c794d24 --- /dev/null +++ b/README.md @@ -0,0 +1,192 @@ +# license-key [![Build Status](https://secure.travis-ci.org/nicroto/license-key.png?branch=master)](http://travis-ci.org/nicroto/license-key) + +License-key generator for NodeJS. + +## Getting Started +Install license-key with: +```bash +$ npm install license-key --save +``` + +## Description +NodeJS module for generation of license-keys. This module supports DSA and ECDSA keys (this is the current state-of-the-art, since it provides the same level of security as RSA, but in shorter keys). The generated license-key is intended as a copy-paste type of text, not to be rewritten letter-by-letter by the end-user. The serial number part of the license is encoded in base64 (usually people implement their own base32 scheme, but since there is no clear standard, and since this is a copy-paste solution - keys get smaller with base64, it is therefore the better solution). + +## Dependencies +The module requires openssl. You can specify a custom path if you want to use a custom build/install, that isn't on the PATH. **Supported are versions starting from 1.0.1**. + +## Init +The module exports the LicenseGenerator type, which is initialized with the **absolute** path to your private key, and optionally the **absolute** path to a custom build of OpenSSSL (otherwise it will try to use the one on the PATH if any): +```javascript +var pathUtils = require('path'), + LicenseGenerator = require('license-key'); + +var lgen = new LicenseGenerator( { + privateKeyPath: pathUtils.resolve( "custom/path/to/your/private/key" ), + opensslPath: pathUtils.resolve( "custom/path/to/openssl" ) +} ); +``` + +## Generating Licenses +Once you create an instance of the generator the default way of generating a key is: +```javascript +var signThis = "Nikolay Tsenkov"; +lgen.generateLicense( { + signThis: signThis +}, function(license) { + // ... +} ); +``` + +This will produce a license key, which uses the default template and will look similar to this: +``` +====BEGIN LICENSE==== +Nikolay Tsenkov +xxxxxxxxxxxxxxxxxxxxx +=====END LICENSE===== +``` + +Templates are standard mustache tempaltes. If the default tempalte is used, then the model bound the default tempalte has 2 default fields - name and serial. + +## Custom License templates +You can create your own mustache template (this sounds weird :smile:). If you provide your own template, then the only field in the model data will be automatically added will be the produced serial. You need to specify the serial field in the template, or otherwise will get license with no serial. + +Here is a sample of a custom template: +```javascript +var signThis = "Nikolay Tsenkov", + template = [ + "====Custom Begin====", + "Name: {{&name}}", + "", + "{{&serial}}", + "=====Custom End=====" + ].join( "\n" ); +lgen.generateLicense( { + signThis: signThis, + template: template +}, function(license) { + // ... +} ); +``` + +This will produce something like: + + +``` +====Custom Begin==== +Name: Nikolay Tsenkov + +xxxxxxxxxxxxxxxxxxxxx +=====Custom End===== +``` + +As you can see, you don't specify the model and your ```name``` and ```serial``` fields are automatically mapped (they are the default fields). + +If you pass a model, though, then only serial is being dynamically added to it - it's up to you, what else you want and how you want to display it. + +Here is an example with a bit more data: +```javascript +var name = "Nikolay Tsenkov", + email = "some@email.com", + licenseMeta = "Quantity: 1", + appMeta = "appVersion: 1", + signThis = [ name, email, licenseMeta, appMeta ].join( " | " ), + template = [ + "====BEGIN LICENSE====", + "{{&name}}", + "{{&email}}", + "{{&licenseMeta}}", + "{{&appMeta}}", + "{{&serial}}", + "=====END LICENSE=====" + ].join( "\n" ); +lgen.generateLicense( { + signThis: signThis, + template: template, + model: { + name: name, + email: email, + licenseMeta: licenseMeta, + appMeta: appMeta + } +}, function(license) { + // ... +} ); +``` + +As you can see, here you generate the license serial, from something that you don't display (check signThis). Here is the approximate result: +``` +====BEGIN LICENSE==== +Nikolay Tsenkov +some@email.com +Quantity: 1 +appVersion: 1 +xxxxxxxxxxxxxxxxxxxxx +=====END LICENSE===== +``` + +## Custom serial formatting +Since serial numbers are generally pretty big and messy strings, you might want to format the serial into pretty columns. You can do so, by passing a serialFormat function in the model: +```javascript +var name = "Nikolay Tsenkov", + email = "some@email.com", + licenseMeta = "Quantity: 1", + appMeta = "appVersion: 1", + signThis = [ name, email, licenseMeta, appMeta ].join( " | " ), + template = [ + "====BEGIN LICENSE====", + "{{&name}}", + "{{&email}}", + "{{&licenseMeta}}", + "{{&appMeta}}", + "{{&serial}}", + "=====END LICENSE=====" + ].join( "\n" ); +lgen.generateLicense( { + signThis: signThis, + template: template, + model: { + name: name, + email: email, + licenseMeta: licenseMeta, + appMeta: appMeta, + serialFormat: function(serial) { + var colLength = 4, + numOfColPerRow = 4, + length = serial.length, + numberOfColumns = (length % colLength) === 0 ? length / colLength : Math.ceil( length / colLength ), + regex = new RegExp( ".{1," + colLength + "}", "g" ), + colData = serial.match( regex ), + resultLines = []; + while ( colData.length ) { + var row = colData.splice( 0, numOfColPerRow ); + resultLines.push( row.join( " " ) ); + } + return resultLines.join( "\n" ); + } + } +}, function(license) { + // ... +} ); +``` + +This should produce something like this: +``` +====BEGIN LICENSE==== +Nikolay Tsenkov +some@email.com +Quantity: 1 +appVersion: 1 +xxxx xxxx xxxx xxxx +xxxx xxxx xxxx xxxx +=====END LICENSE===== +``` + +## Contributing +In lieu of a formal styleguide, take care to maintain the existing coding style. Add unit tests for any new or changed functionality. Lint and test your code using [Grunt](http://gruntjs.com/). + +## Release History + - 0.1.0 + +## License +Copyright (c) 2014 Nikolay Tsenkov +Licensed under the MIT license. diff --git a/bin/sign.sh b/bin/sign.sh new file mode 100755 index 0000000..e9b7a2d --- /dev/null +++ b/bin/sign.sh @@ -0,0 +1,3 @@ +#!/bin/bash + +$1 dgst -sign $2 <(echo -n "$3") | openssl enc -base64 \ No newline at end of file diff --git a/package.json b/package.json new file mode 100644 index 0000000..32eeb39 --- /dev/null +++ b/package.json @@ -0,0 +1,48 @@ +{ + "name": "license-key", + "description": "License-key generator for NodeJS.", + "version": "0.1.0", + "homepage": "https://github.com/nicroto/license-key", + "author": { + "name": "Nikolay Tsenkov", + "email": "nikolay@tsenkov.net", + "url": "http://about.me/tsenkov" + }, + "repository": { + "type": "git", + "url": "hhttps://github.com/nicroto/license-key.git" + }, + "bugs": { + "url": "https://github.com/nicroto/license-key/issues" + }, + "licenses": [ + { + "type": "MIT", + "url": "https://github.com/nicroto/license-key/blob/master/LICENSE-MIT" + } + ], + "main": "src/generator", + "engines": { + "node": ">= 0.8.0" + }, + "scripts": { + "test": "grunt" + }, + "dependencies": { + "mustache": "~0.8.1", + "semver": "~2.2.1" + }, + "devDependencies": { + "grunt-contrib-jshint": "~0.6.4", + "grunt": "~0.4.1", + "grunt-simple-mocha": "~0.4.0", + "mocha": "~1.13.0", + "should": "~3.3.1" + }, + "keywords": [ + "license", + "generator", + "serial", + "number" + ] +} diff --git a/src/default.template b/src/default.template new file mode 100644 index 0000000..80537f2 --- /dev/null +++ b/src/default.template @@ -0,0 +1,4 @@ +====BEGIN LICENSE==== +{{name}} +{{serial}} +=====END LICENSE===== \ No newline at end of file diff --git a/src/generator.js b/src/generator.js new file mode 100644 index 0000000..4340c76 --- /dev/null +++ b/src/generator.js @@ -0,0 +1,156 @@ +/* + * license-key + * https://github.com/nicroto/license-key + * + * Copyright (c) 2014 Nikolay Tsenkov + * Licensed under the MIT license. + */ + +/* jshint -W098 */ + +'use strict'; + +var fs = require('fs'), + pathUtils = require('path'), + exec = require('child_process').exec, + semver = require('semver'), + Mustache = require('mustache'); + +var defaultTemplate = fs.readFileSync( pathUtils.resolve( __dirname, "default.template" ), "utf8" ); + +function Generator(options) { + + var self = this; + + if ( !options || typeof options !== "object" || !Object.keys( options ).length ) { + throw new Error( "No options are provided!" ); + } + + var fileCheck = function(path, str) { + if ( !path ) { + throw new Error( "No " + str + " is specified!" ); + } + if ( !fs.existsSync( path ) ) { + throw new Error( str + " doesn't exist!" ); + } + if ( !fs.statSync( path ).isFile() ) { + throw new Error( str + " isn't a file!" ); + } + }; + + fileCheck( options.privateKeyPath ); + self.privateKeyPath = options.privateKeyPath; + + var opensslPath = options.opensslPath; + if ( opensslPath ) { + fileCheck( opensslPath ); + self.opensslPath = opensslPath; + } + +} + +Generator.prototype = { + + privateKeyPath: null, + opensslPath: "openssl", + isOpensslChecked: false, + isOpensslVersionSupported: false, + + generateLicense: function(args, callback) { + var self = this, + signThis = args.signThis, + template = args.template, + model = args.model ? args.model : { name: signThis }, + serialFormat = model.serialFormat; + + // checks + if ( !signThis || typeof signThis !== "string" ) { + throw new Error( "Invalid data to be signed!" ); + } + if ( model && typeof model !== "object" ) { + throw new Error( "Model should be an object!" ); + } + if ( serialFormat !== undefined && typeof serialFormat !== "function" ) { + throw new Error( "model.serialFormat should be a function!" ); + } + if ( template && typeof template !== "string" ) { + throw new Error( "Template should be a string!" ); + } + if ( !callback ) { + throw new Error( "No callback is assigned!" ); + } + if ( typeof callback !== "function" ) { + throw new Error( "No callback is assigned!" ); + } + + // clean model from non-data props + delete model.serialFormat; + + // should default template be used? + if ( !template ) { + template = template ? template : defaultTemplate; + + // default model props + model.name = ( model.name !== undefined ) ? model.name : signThis; + } + + self._checkOpenssl( function() { + self._generateSerial( signThis, function(serial) { + model.serial = serialFormat ? serialFormat( serial ) : serial; + callback( Mustache.render( template, model ) ); + } ); + } ); + }, + + _checkOpenssl: function(callback) { + var self = this; + var throwError = function() { + throw new Error( "Openssl version isn't supported! Should be >= 1.0.1" ); + }; + + if ( !self.isOpensslChecked ) { + exec( self.opensslPath + " version", function(error, stdout, stderror) { + self.isOpensslChecked = true; + self.isOpensslVersionSupported = self._isOpensslVersionSupported( stdout ); + if ( self.isOpensslVersionSupported ) { + callback(); + } else { + throwError(); + } + } ); + } else if ( !self.isOpensslVersionSupported ) { + throwError(); + } else if ( self.isOpensslVersionSupported ) { + callback(); + } + }, + + _isOpensslVersionSupported: function(str) { + var matchs = str.match(/([0-9][0-9]*)\.([0-9][0-9]*)\.([0-9][0-9]*)/g); + + if ( matchs.length === 1 ) { + var version = matchs[0]; + + return semver.satisfies( version, ">=1.0.1" ); + } + + return false; + }, + + _generateSerial: function(signThis, callback) { + var self = this, + opensslPath = self.opensslPath, + privateKeyPath = self.privateKeyPath, + signScriptPath = pathUtils.resolve( __dirname, "..", "bin", "sign.sh" ); + + var command = [ + signScriptPath, opensslPath, privateKeyPath, JSON.stringify( signThis ) + ].join(" "); + exec( command, function(error, stdout, stderror) { + callback( stdout.replace( /(\n|\s|\=)/g, "" ) ); + } ); + } + +}; + +module.exports = Generator; \ No newline at end of file diff --git a/test/data/private.pem b/test/data/private.pem new file mode 100644 index 0000000..6f8105c --- /dev/null +++ b/test/data/private.pem @@ -0,0 +1,6 @@ +-----BEGIN EC PRIVATE KEY----- +MIGkAgEBBDCE5uM3lhZ8vhEzAoWHRE5JB5wtOjO2H0f9PghUJ1TtVhMNBproAjYk +ybnRDGr1NVygBwYFK4EEACKhZANiAARkan+Y8kA5wRtVYiA1SYjqI7TycrSZoCRS +1IxlUIomn9e9DkiuBGTIMau9bBBmbm39S7DZxjIRbcPa5lqNHJKT4lFIS2AywdvB +Ybl6xeNG0mOFNHP2djYpqpLobbjX9Mk= +-----END EC PRIVATE KEY----- diff --git a/test/data/public.pem b/test/data/public.pem new file mode 100644 index 0000000..260db8a --- /dev/null +++ b/test/data/public.pem @@ -0,0 +1,5 @@ +-----BEGIN PUBLIC KEY----- +MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAEZGp/mPJAOcEbVWIgNUmI6iO08nK0maAk +UtSMZVCKJp/XvQ5IrgRkyDGrvWwQZm5t/Uuw2cYyEW3D2uZajRySk+JRSEtgMsHb +wWG5esXjRtJjhTRz9nY2KaqS6G241/TJ +-----END PUBLIC KEY----- diff --git a/test/gen-test.js b/test/gen-test.js new file mode 100644 index 0000000..75101a1 --- /dev/null +++ b/test/gen-test.js @@ -0,0 +1,301 @@ +/* jshint -W030 */ +/* jshint -W098 */ + +'use strict'; + +var should = require('should'), + fs = require('fs'), + pathUtils = require('path'), + Mustache = require('mustache'), + LicenseGenerator = require(".."), + defaultTemplate = fs.readFileSync( pathUtils.resolve( __dirname, "..", "src", "default.template" ), "utf8" ); + +var privateKeyPath = pathUtils.resolve( __dirname, "data", "private.pem" ), + nonFilePath = pathUtils.resolve( __dirname, "data" ); + +describe( "license-key", function() { + describe( "new LicenseGenerator( { privateKeyPath:.., opensslPath:.. } )", function() { + it( "should throw an error if no options are provided", function() { + should( function() { + var lgen = new LicenseGenerator(); + } ).throw(); + should( function() { + var lgen = new LicenseGenerator( {} ); + } ).throw(); + } ); + it( "should throw an error if privateKeyPath isn't provided", function() { + should( function() { + var lgen = new LicenseGenerator( {} ); + } ).throw(); + } ); + it( "should throw an error if privateKeyPath doesn't exist", function() { + should( function() { + var lgen = new LicenseGenerator( { + privateKeyPath: "non-existent-path" + } ); + } ).throw(); + } ); + it( "should throw an error if privateKeyPath is not a file", function() { + should( function() { + var lgen = new LicenseGenerator( { + privateKeyPath: nonFilePath + } ); + } ).throw(); + } ); + it( "should use global openssl if no path provided", function() { + var lgen = new LicenseGenerator( { + privateKeyPath: privateKeyPath + } ); + lgen.opensslPath.should.equal( "openssl" ); + } ); + it( "should throw an error if opensslPath doesn't exist", function() { + should( function() { + var lgen = new LicenseGenerator( { + privateKeyPath: privateKeyPath, + opensslPath: "non-existent-path" + } ); + } ).throw(); + } ); + it( "shouldn't throw an error if privateKeyPath is valid and openssl is on PATH", function() { + should( function() { + var lgen = new LicenseGenerator( { + privateKeyPath: privateKeyPath + } ); + } ).not.throw(); + } ); + } ); + describe( "prototype_isOpensslVersionSupported", function() { + it( "should return false if version isn't supported", function() { + LicenseGenerator.prototype._isOpensslVersionSupported( "OpenSSL 0.9.8g 7 Apr 2009" ).should.not.be.ok; + LicenseGenerator.prototype._isOpensslVersionSupported( "OpenSSL 0.9.7b 7 Apr 2004" ).should.not.be.ok; + LicenseGenerator.prototype._isOpensslVersionSupported( "OpenSSL 0.9.9b 7 Apr 2005" ).should.not.be.ok; + LicenseGenerator.prototype._isOpensslVersionSupported( "OpenSSL 1.0.0b 7 Apr 2013" ).should.not.be.ok; + LicenseGenerator.prototype._isOpensslVersionSupported( "some unpredictable format 0.9.7b 21/04/2004" ).should.not.be.ok; + LicenseGenerator.prototype._isOpensslVersionSupported( "0.9.9b 21/04/2004" ).should.not.be.ok; + LicenseGenerator.prototype._isOpensslVersionSupported( "1.0.0b 21/04/2004" ).should.not.be.ok; + } ); + it( "should return true if version is supported", function() { + LicenseGenerator.prototype._isOpensslVersionSupported( "OpenSSL 1.0.1g 7 Apr 2014" ).should.be.ok; + LicenseGenerator.prototype._isOpensslVersionSupported( "OpenSSL 1.0.8g 8 Apr 2014" ).should.be.ok; + LicenseGenerator.prototype._isOpensslVersionSupported( "OpenSSL 1.0.9g 10 Apr 2014" ).should.be.ok; + LicenseGenerator.prototype._isOpensslVersionSupported( "OpenSSL 2.0.1g 7 Apr 2014" ).should.be.ok; + LicenseGenerator.prototype._isOpensslVersionSupported( "some unpredictable format 2.0.1b 21/04/2016" ).should.be.ok; + LicenseGenerator.prototype._isOpensslVersionSupported( "1.0.1g 21/04/2014" ).should.be.ok; + LicenseGenerator.prototype._isOpensslVersionSupported( "1.0.7g 21/04/2018" ).should.be.ok; + } ); + } ); + describe( "generateLicense( { signThis:.., serialFormat:.., model:.., template:.. }, callback )", function() { + var lgen = new LicenseGenerator( { + privateKeyPath: privateKeyPath + } ), + serial = "xxxxxxxxxxxxxxxx"; // 16 symbols + // mock serial creation for predictability + lgen._generateSerial = function(signThis, callback) { + callback( serial ); + }; + it( "should throw an error if signThis is not a valid string (at least 1 character)", function() { + should( function() { + lgen.generateLicense( {} ); + } ).throw(); + should( function() { + lgen.generateLicense( { signThis: null } ); + } ).throw(); + should( function() { + lgen.generateLicense( { signThis: 1 } ); + } ).throw(); + should( function() { + lgen.generateLicense( { signThis: {} } ); + } ).throw(); + should( function() { + lgen.generateLicense( { signThis: "" } ); + } ).throw(); + } ); + it( "should throw an error if no callback is passed", function() { + should( function() { + lgen.generateLicense( { signThis: "data to sign" } ); + } ).throw(); + should( function() { + lgen.generateLicense( { signThis: "data to sign" }, 1 ); + } ).throw(); + should( function() { + lgen.generateLicense( { signThis: "data to sign" }, {} ); + } ).throw(); + } ); + it( "shouldn't throw an error if no model is passed", function() { + should( function() { + lgen.generateLicense( { signThis: "data to sign" }, function() {} ); + } ).not.throw(); + should( function() { + lgen.generateLicense( { + signThis: "data to sign", + model: {} + }, function() {} ); + } ).not.throw(); + } ); + it( "should throw an error if model is passed but not an object", function() { + should( function() { + lgen.generateLicense( { + signThis: "data to sign", + model: 1 + } ); + } ).throw(); + } ); + it( "should throw an error if template is passed but isn't a string", function() { + should( function() { + lgen.generateLicense( { + signThis: "data to sign", + template: 1 + } ); + } ).throw(); + should( function() { + lgen.generateLicense( { + signThis: "data to sign", + template: {} + } ); + } ).throw(); + } ); + it( "generates a license key with the default tempalte", function(done) { + var signThis = "Nikolay Tsenkov"; + lgen.generateLicense( { + signThis: signThis + }, function(license) { + license.should.equal( Mustache.render( defaultTemplate, { + name: signThis, + serial: serial + } ) ); + done(); + } ); + } ); + it( "uses model.name if provided, instead of signed data", function(done) { + var signThis = "Nikolay Tsenkov | some@email.domain", + name = "Nikolay Tsenkov"; + lgen.generateLicense( { + signThis: signThis, + model: { + name: name + } + }, function(license) { + license.should.equal( Mustache.render( defaultTemplate, { + name: name, + serial: serial + } ) ); + done(); + } ); + } ); + it( "generates a license key with custom tempalte", function(done) { + var signThis = "Nikolay Tsenkov", + template = [ + "====Custom Begin====", + "Name: {{&name}}", + "{{&serial}}", + "=====Custom End=====" + ].join( "\n" ); + lgen.generateLicense( { + signThis: signThis, + template: template + }, function(license) { + license.should.equal( Mustache.render( template, { + name: signThis, + serial: serial + } ) ); + done(); + } ); + } ); + it( "should throw an error if model.serialFormat is passed, but it's not a function", function() { + should( function() { + lgen.generateLicense( { + signThis: "data to sign", + model: { + serialFormat: {} + } + } ); + } ).throw(); + should( function() { + lgen.generateLicense( { + signThis: "data to sign", + model: { + serialFormat: 1 + } + } ); + } ).throw(); + should( function() { + lgen.generateLicense( { + signThis: "data to sign", + model: { + serialFormat: "" + } + } ); + } ).throw(); + } ); + it( "uses serialFormat function for serial if provided in the model", function(done) { + var signThis = "Nikolay Tsenkov", + formattedSerial = "||" + serial + "||"; + lgen.generateLicense( { + signThis: signThis, + model: { + serialFormat: function() { + return formattedSerial; + } + } + }, function(license) { + license.should.equal( Mustache.render( defaultTemplate, { + name: signThis, + serial: formattedSerial + } ) ); + done(); + } ); + } ); + it( "works in a real-world example", function(done) { + var name = "Nikolay Tsenkov", + email = "some@email.com", + licenseMeta = "Quantity: 1", + appMeta = "appVersion: 1", + signThis = [ name, email, licenseMeta, appMeta ].join( " | " ), + template = [ + "====BEGIN LICENSE====", + "{{&name}}", + "{{&email}}", + "{{&licenseMeta}}", + "{{&appMeta}}", + "{{&serial}}", + "=====END LICENSE=====" + ].join( "\n" ); + lgen.generateLicense( { + signThis: signThis, + template: template, + model: { + name: name, + email: email, + licenseMeta: licenseMeta, + appMeta: appMeta, + serialFormat: function(serial) { + var colLength = 4, + numOfColPerRow = 2, + length = serial.length, + numberOfColumns = (length % colLength) === 0 ? length / colLength : Math.ceil( length / colLength ), + regex = new RegExp( ".{1," + colLength + "}", "g" ), + colData = serial.match( regex ), + resultLines = []; + while ( colData.length ) { + var row = colData.splice( 0, numOfColPerRow ); + resultLines.push( row.join( " " ) ); + } + return resultLines.join( "\n" ); + } + } + }, function(license) { + license.should.equal( Mustache.render( template, { + name: name, + email: email, + licenseMeta: licenseMeta, + appMeta: appMeta, + serial: [ + "xxxx xxxx", + "xxxx xxxx" + ].join( "\n" ) + } ) ); + done(); + } ); + } ); + } ); +} ); \ No newline at end of file