From c870dc8c15dd5a25a28b67316a4287480214f259 Mon Sep 17 00:00:00 2001 From: Mattias Erming Date: Wed, 13 Aug 2014 16:43:11 -0700 Subject: [PATCH] Added ClientManager class --- index.js | 28 +++++++++++++++++++ src/clientManager.js | 66 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 94 insertions(+) create mode 100644 src/clientManager.js diff --git a/index.js b/index.js index 2635e61b..eadee18d 100755 --- a/index.js +++ b/index.js @@ -4,6 +4,7 @@ process.chdir(__dirname); var config = require("./config.json"); var program = require("commander"); +var ClientManager = require("./src/clientManager"); var shout = require("./src/server.js"); program @@ -17,6 +18,33 @@ program shout(port); }); +program + .command("list-users") + .description("List all existing users") + .action(function() { + var manager = new ClientManager(); + var users = manager.getUsers(); + for (var u in users) { + console.log(users[u]); + } + }); + +program + .command("add-user ") + .description("Add a new user") + .action(function(name) { + var manager = new ClientManager(); + manager.addUser(name); + }); + +program + .command("remove-user ") + .description("Remove an existing user") + .action(function(name) { + var manager = new ClientManager(); + manager.removeUser(name); + }); + program.parse(process.argv) if (!program.args.length) { diff --git a/src/clientManager.js b/src/clientManager.js new file mode 100644 index 00000000..7a225b13 --- /dev/null +++ b/src/clientManager.js @@ -0,0 +1,66 @@ +var _ = require("lodash"); +var fs = require("fs"); + +module.exports = ClientManager; + +function ClientManager() { + this.clients = []; +} + +ClientManager.prototype.loadUsers = function() { + var users = this.getUsers(); + _.each(users, function(user) { + console.log(user); + }); +}; + +ClientManager.prototype.getUsers = function() { + var users = []; + try { + users = fs.readdirSync("users/"); + } catch(e) { + console.log(e); + return; + } + return users; +}; + +ClientManager.prototype.addUser = function(name) { + var users = this.getUsers(); + if (users.indexOf(name) !== -1) { + console.log("User '" + name + "' already exist."); + return; + } + + try { + var path = "users/" + name; + fs.mkdirSync(path); + fs.writeFileSync(path + "/user.json", "{}"); + } catch(e) { + throw e; + } + + console.log( + "Added '" + name + "'." + ); +}; + +ClientManager.prototype.removeUser = function(name) { + var users = this.getUsers(); + if (users.indexOf(name) === -1) { + console.log("User '" + name + "' doesn't exist."); + return; + } + + try { + var path = "users/" + name; + fs.unlinkSync(path + "/user.json"); + fs.rmdirSync(path); + } catch(e) { + throw e; + } + + console.log( + "Removed '" + name + "'." + ); +};