* Better view inheritance. Experimental ButtonView. User stuff

This commit is contained in:
NuSkooler 2014-10-23 22:18:38 -06:00
parent 8cd062be72
commit 668fdd9166
8 changed files with 171 additions and 202 deletions

View File

@ -2,9 +2,12 @@
'use strict'; 'use strict';
var TextView = require('./text_view.js').TextView; var TextView = require('./text_view.js').TextView;
var miscUtil = require('./misc_util.js');
var util = require('util'); var util = require('util');
var assert = require('assert'); var assert = require('assert');
exports.ButtonView = ButtonView;
function ButtonView(client, options) { function ButtonView(client, options) {
options.acceptsFocus = miscUtil.valueWithDefault(options.acceptsFocus, true); options.acceptsFocus = miscUtil.valueWithDefault(options.acceptsFocus, true);
options.acceptsInput = miscUtil.valueWithDefault(options.acceptsInput, true); options.acceptsInput = miscUtil.valueWithDefault(options.acceptsInput, true);
@ -15,15 +18,10 @@ function ButtonView(client, options) {
util.inherits(ButtonView, TextView); util.inherits(ButtonView, TextView);
ButtonView.prototype.onKeyPress = function(key, isSpecial) { ButtonView.prototype.onKeyPress = function(key, isSpecial) {
// we accept input so this must be implemented -- nothing to do here, however ButtonView.super_.prototype.onKeyPress.call(this, key, isSpecial);
// :TODO: Move this to View along with default asserts; update EditTextView to call View
}
ButtonView.prototype.onSpecialKeyPress = function(keyName) { // allow spacebar to 'click' buttons
assert(this.hasFocus); if(' ' === key) {
assert(this.acceptsInput); this.emit('action', 'accept');
assert(this.specialKeyMap); }
};
// :TODO: see notes about making base handle 'enter' key(s)
// ...just make enter = enter | space for a button by default
}

View File

@ -23,9 +23,6 @@ function EditTextView(client, options) {
util.inherits(EditTextView, TextView); util.inherits(EditTextView, TextView);
EditTextView.prototype.onKeyPress = function(key, isSpecial) { EditTextView.prototype.onKeyPress = function(key, isSpecial) {
assert(this.hasFocus);
assert(this.acceptsInput);
if(isSpecial) { if(isSpecial) {
return; return;
} }
@ -43,26 +40,19 @@ EditTextView.prototype.onKeyPress = function(key, isSpecial) {
this.client.term.write(key); this.client.term.write(key);
} }
} }
EditTextView.super_.prototype.onKeyPress.call(this, key, isSpecial);
}; };
EditTextView.prototype.onSpecialKeyPress = function(keyName) { EditTextView.prototype.onSpecialKeyPress = function(keyName) {
assert(this.hasFocus); // :TODO: handle 'enter' & others for multiLine
assert(this.acceptsInput);
assert(this.specialKeyMap);
if(this.isSpecialKeyMapped('backspace', keyName)) { if(this.isSpecialKeyMapped('backspace', keyName)) {
if(this.text.length > 0) { if(this.text.length > 0) {
this.text = this.text.substr(0, this.text.length - 1); this.text = this.text.substr(0, this.text.length - 1);
this.clientBackspace(); this.clientBackspace();
} }
} else if(this.isSpecialKeyMapped('enter', keyName)) {
if(this.multiLine) {
} else {
// :TODO: by default handle this in View/base. Can always "absorb" the call here for special handling
this.emit('action', 'accepted');
}
} else if(this.isSpecialKeyMapped('next', keyName)) {
// :TODO: by default handle next in View/base
this.emit('action', 'next');
} }
EditTextView.super_.prototype.onSpecialKeyPress.call(this, keyName);
}; };

View File

@ -3,6 +3,7 @@
var TextView = require('./text_view.js').TextView; var TextView = require('./text_view.js').TextView;
var EditTextView = require('./edit_text_view.js').EditTextView; var EditTextView = require('./edit_text_view.js').EditTextView;
var ButtonView = require('./button_view.js').ButtonView;
var assert = require('assert'); var assert = require('assert');
exports.MCIViewFactory = MCIViewFactory; exports.MCIViewFactory = MCIViewFactory;
@ -37,6 +38,15 @@ MCIViewFactory.prototype.createFromMCI = function(mci) {
view = new EditTextView(this.client, options); view = new EditTextView(this.client, options);
break; break;
case 'BV' :
if(mci.args.length > 0) {
options.text = mci.args[0];
options.dimens = { width : options.text.length };
}
view = new ButtonView(this.client, options);
break;
} }
return view; return view;

View File

@ -1,40 +1,103 @@
/* jslint node: true */ /* jslint node: true */
'use strict'; 'use strict';
var userDb = require('./database.js').dbs.user;
var crypto = require('crypto'); var crypto = require('crypto');
var assert = require('assert'); var assert = require('assert');
//var database = require('./database.js');
var userDb = require('./database.js').dbs.user; exports.User = User;
exports.getUserId = getUserId;
exports.createNew = createNew;
exports.generatePasswordDerivedKey = generatePasswordDerivedKey;
exports.persistAll = persistAll;
exports.User = User; function User() {
var self = this;
var PBKDF2 = { this.id = 0;
this.userName = '';
this.isValid = function() {
if(self.id <= 0 || self.userName.length < 2) {
return false;
}
return this.hasValidPassword();
};
this.hasValidPassword = function() {
if(!this.properties || !this.properties.pw_pbkdf2_salt || !this.properties.pw_pbkdf2_dk) {
return false;
}
return this.properties.pw_pbkdf2_salt.length === User.PBKDF2.saltLen * 2 &&
this.prop_name.pw_pbkdf2_dk.length === User.PBKDF2.keyLen * 2;
};
this.isRoot = function() {
return 1 === this.id;
};
this.isSysOp = this.isRoot; // alias
}
User.PBKDF2 = {
iterations : 1000, iterations : 1000,
keyLen : 128, keyLen : 128,
saltLen : 32, saltLen : 32,
}; };
var UserErrorCodes = Object.freeze({ function getUserId(userName, cb) {
NONE : 'No error', userDb.get(
INVALID_USER : 'Invalid user', 'SELECT id ' +
INVALID_PASSWORD : 'Invalid password', 'FROM user ' +
}); 'WHERE user_name LIKE ?;',
[ userName ],
function User() { function onResults(err, row) {
var self = this; cb(err, row.id);
}
this.id = 0; );
this.userName = '';
this.groups = [];
this.permissions = [];
this.properties = {};
} }
User.generatePasswordDerivedKey = function(password, cb) { function createNew(user, cb) {
crypto.randomBytes(PBKDF2.saltLen, function onRandomSalt(err, salt) { assert(user.userName && user.userName.length > 1, 'Invalid userName');
userDb.run(
'INSERT INTO user (user_name) ' +
'VALUES (?);',
[ user.userName ],
function onUserInsert(err) {
if(err) {
cb(err);
} else {
user.id = this.lastID;
//
// Allow converting user.password -> Salt/DK
//
if(user.password && user.password.length > 0) {
generatePasswordDerivedKey(user.password, function onDkGenerated(err, dk) {
user.properties = user.properties || {
pw_pbkdf2_salt : dk.salt,
pw_pbkdf2_dk : dk.dk,
};
persistAll(user, function onUserPersisted() {
cb(null, user.id);
});
});
} else {
persistAll(user, function onUserPersisted() {
cb(null, user.id);
});
}
}
}
);
}
function generatePasswordDerivedKey(password, cb) {
crypto.randomBytes(User.PBKDF2.saltLen, function onRandomSalt(err, salt) {
if(err) { if(err) {
cb(err); cb(err);
return; return;
@ -44,171 +107,44 @@ User.generatePasswordDerivedKey = function(password, cb) {
password = new Buffer(password).toString('hex'); password = new Buffer(password).toString('hex');
crypto.pbkdf2(password, salt, PBKDF2.iterations, PBKDF2.keyLen, function onDerivedKey(err, dk) { crypto.pbkdf2(password, salt, User.PBKDF2.iterations, User.PBKDF2.keyLen, function onDerivedKey(err, dk) {
if(err) { if(err) {
cb(err); cb(err);
return; } else {
cb(null, { dk : dk.toString('hex'), salt : salt } );
} }
cb(null, { dk : dk.toString('hex'), salt : salt });
}); });
}); });
}; }
// function persistProperties(user, cb) {
// :TODO: createNewUser(userName, password, groups) assert(user.id > 0);
User.addNew = function(user, cb) { var stmt = userDb.prepare(
userDb.run('INSERT INTO user (user_name) VALUES(?);', [ user.userName ], function onUserInsert(err) { 'REPLACE INTO user_property (user_id, prop_name, prop_value) ' +
if(err) { 'VALUES (?, ?, ?);');
cb(err);
return;
}
user.id = this.lastID; Object.keys(user.properties).forEach(function onProp(name) {
user.persist(cb); stmt.run(user.id, name, user.properties[name]);
}); });
};
User.prototype.persist = function(cb) { stmt.finalize(function onFinalized() {
var self = this; if(cb) {
cb();
}
});
}
if(0 === this.id || 0 === this.userName.length) { function persistAll(user, cb) {
cb(new Error(UserErrorCodes.INVALID_USER)); assert(user.id > 0);
return;
}
userDb.serialize(function onSerialized() { userDb.serialize(function onSerialized() {
userDb.run('BEGIN;'); userDb.run('BEGIN;');
// :TODO: Create persistProperties(id, {props}) persistProperties(user);
var stmt = userDb.prepare('REPLACE INTO user_property (user_id, prop_name, prop_value) VALUES(?, ?, ?);');
Object.keys(self.properties).forEach(function onPropName(propName) {
stmt.run(self.id, propName, self.properties[propName]);
});
stmt.finalize(function onFinalized() { userDb.run('COMMIT;');
userDb.run('COMMIT;');
cb(null, self.id);
});
}); });
};
// :TODO: make standalone function(password, dk, salt) cb();
User.prototype.validatePassword = function(password, cb) {
assert(this.properties.pw_pbkdf2_salt);
assert(this.properties.pw_pbkdf2_dk);
var self = this;
password = new Buffer(password).toString('hex');
crypto.pbkdf2(password, this.properties.pw_pbkdf2_salt, PBKDF2.iterations, PBKDF2.keyLen, function onDerivedKey(err, dk) {
if(err) {
cb(err);
return;
}
// Constant time compare
var propDk = new Buffer(self.properties.pw_pbkdf2_dk, 'hex');
console.log(propDk);
console.log(dk);
if(propDk.length !== dk.length) {
cb(new Error('Unexpected buffer length'));
return;
}
var c = 0;
for(var i = 0; i < dk.length; i++) {
c |= propDk[i] ^ dk[i];
}
cb(null, c === 0);
});
};
// :TODO: make this something like getUserProperties(id, [propNames], cb)
function getUserDerivedKeyAndSalt(id, cb) {
var properties = {};
userDb.each(
'SELECT prop_name, prop_value ' +
'FROM user_property ' +
'WHERE user_id = ? AND prop_name="pw_pbkdf2_salt" OR prop_name="pw_pbkdf2_dk";',
[ id ],
function onPwPropRow(err, propRow) {
if(err) {
cb(err);
} else {
properties[propRow.prop_name] = propRow.prop_value;
}
},
function onComplete() {
cb(null, properties);
}
);
} }
User.loadWithCredentials = function(userName, password, cb) {
userDb.get('SELECT id, user_name FROM user WHERE user_name LIKE ? LIMIT 1;"', [ userName ], function onUserIds(err, userRow) {
if(err) {
cb(err);
return;
}
if(!userRow) {
cb(new Error(UserErrorCodes.INVALID_USER));
return;
}
// Load dk & salt properties for password validation
getUserDerivedKeyAndSalt(userRow.id, function onDkAndSalt(err, props) {
var user = new User();
user.properties = props;
user.validatePassword(password, function onValidatePw(err, isCorrect) {
if(err) {
cb(err);
return;
}
if(!isCorrect) {
cb(new Error(UserErrorCodes.INVALID_PASSWORD));
return;
}
// userName and password OK -- load the rest.
user.id = userRow.id;
user.userName = userRow.user_name;
cb(null, user);
});
});
});
};
User.prototype.setPassword = function(password, cb) {
// :TODO: validate min len, etc. here?
crypto.randomBytes(PBKDF2.saltLen, function onRandomSalt(err, salt) {
if(err) {
cb(err);
return;
}
password = Buffer.isBuffer(password) ? password : new Buffer(password, 'hex');
crypto.pbkdf2(password, salt, PBKDF2.iterations, PBKDF2.keyLen, function onPbkdf2Generated(err, dk) {
if(err) {
cb(err);
return;
}
cb(null, dk);
this.properties['pw.pbkdf2.salt'] = salt;
this.properties['pw.pbkdf2.dk'] = dk;
});
});
};

View File

@ -6,10 +6,11 @@ var util = require('util');
var assert = require('assert'); var assert = require('assert');
var ansi = require('./ansi_term.js'); var ansi = require('./ansi_term.js');
exports.View = View; exports.View = View;
exports.VIEW_SPECIAL_KEY_MAP_DEFAULT = VIEW_SPECIAL_KEY_MAP_DEFAULT;
var VIEW_SPECIAL_KEY_MAP_DEFAULT = { var VIEW_SPECIAL_KEY_MAP_DEFAULT = {
enter : [ 'enter' ], accept : [ 'enter' ],
exit : [ 'esc' ], exit : [ 'esc' ],
backspace : [ 'backspace' ], backspace : [ 'backspace' ],
del : [ 'del' ], del : [ 'del' ],
@ -106,3 +107,20 @@ View.prototype.setFocus = function(focused) {
this.hasFocus = focused; this.hasFocus = focused;
}; };
View.prototype.onKeyPress = function(key, isSpecial) {
assert(this.hasFocus, 'View does not have focus');
assert(this.acceptsInput, 'View does not accept input');
};
View.prototype.onSpecialKeyPress = function(keyName) {
assert(this.hasFocus, 'View does not have focus');
assert(this.acceptsInput, 'View does not accept input');
assert(this.specialKeyMap, 'No special key map defined');
if(this.isSpecialKeyMapped('accept', keyName)) {
this.emit('action', 'accept');
} else if(this.isSpecialKeyMapped('next', keyName)) {
this.emit('action', 'next');
}
};

View File

@ -40,7 +40,7 @@ function ViewController(client) {
self.nextFocus(); self.nextFocus();
break; break;
case 'accepted' : case 'accept' :
// :TODO: check if id is submit, etc. // :TODO: check if id is submit, etc.
self.nextFocus(); self.nextFocus();
break; break;

Binary file not shown.

View File

@ -60,8 +60,25 @@ function entryPoint(client) {
etv.redraw();*/ etv.redraw();*/
user.createNew({
userName : 'Scooby',
password : 'password',
//properties : {
// pw_pbkdf2_salt : '81b45dc699c716ac1913039138b64e3057844128cf1f9291c6475d26dab3d4a5',
// pw_pbkdf2_dk : '14856dc5d6d277e29c5bb2ca4511695203fc48260128d2a4a611be4eefa1acfa80f8656e80d3361baa3a10ce5918829e9e3a4197b0c552978b6546d2b885d93e933a1270a5e4a81af06818d1fa9f7df830bc46f6f5870f46be818a05114f77b5605477c09e987dc4faf2a939c6869dcf2a28652d5607e5cca2e987ea2003ab4e',
//}
}, function onCreated(err, id) {
if(err) {
console.log(err);
} else {
console.log('new user created: ' + id);
}
});
var vc = new viewController.ViewController(client); var vc = new viewController.ViewController(client);
vc.loadFromMCIMap(mci); vc.loadFromMCIMap(mci);
//vc.getView(3).setText('New');
//vc.getView(4).setText('Login');
vc.setViewOrder(); vc.setViewOrder();
vc.switchFocus(1); vc.switchFocus(1);
//vc.addView(etv); //vc.addView(etv);