pomodoro/bin/create-user.js
2016-08-14 19:18:09 +02:00

99 lines
2.2 KiB
JavaScript
Executable File

#!/bin/env node
'use strict';
const p = require('path');
const crypto = require('crypto');
const chalk = require('chalk');
const MongoClient = require('mongodb').MongoClient;
const successPrefix = '[' + chalk.green('SUCCESS') + '] ';
const errorPrefix = '[' + chalk.red('ERROR') + '] ';
global.PWD = p.dirname(__dirname);
global.ENV = process.env.NODE_ENV || 'development';
function _mongo(collection, cb) {
const mongoConfig = require(p.join(PWD, 'server/config/mongo'));
MongoClient.connect(mongoConfig.uri, function (err, db) {
if (err) {
console.error(errorPrefix);
console.error(err);
process.exit(1);
}
cb(db.collection(collection), db);
});
}
const SALT_LENGTH = 16;
function _hash(password) {
// generate salt
password = password.trim();
const chars = '0123456789abcdefghijklmnopqurstuvwxyz';
let salt = '';
for (let i = 0; i < SALT_LENGTH; i++) {
const j = Math.floor(Math.random() * chars.length);
salt += chars[j];
}
// hash the password
const passwordHash = crypto.createHash('sha512').update(salt + password).digest('hex');
// entangle the hashed password with the salt and save to the model
return _entangle(passwordHash, salt, password.length);
}
function _entangle(string, salt, t) {
string = salt + string;
const length = string.length;
const arr = string.split('');
for (let i = 0; i < salt.length; i++) {
const num = ((i + 1) * t) % length;
const tmp = arr[i];
arr[i] = arr[num];
arr[num] = tmp;
}
return arr.join('');
}
function createUser(email, password, roles) {
if (!email || !password) {
console.log('Usage: bin/create-user.js [email] [password] [?roles]');
process.exit(1);
}
const user = {
email: email,
local: {
password: _hash(password)
},
roles: roles ? roles.split(',') : [ 'admin' ],
isVerified: true,
dateCreated: new Date()
};
_mongo('users', function (users, db) {
users.insert(user, function (err, user) {
db.close();
if (err) {
console.error(errorPrefix);
console.error(err);
process.exit(1);
} else {
console.log(successPrefix + 'Saved user: ' + user.ops[0].email);
process.exit(0);
}
});
});
}
createUser.apply(null, process.argv.slice(2));