2015-05-11 22:39:28 +00:00
|
|
|
/* jslint node: true */
|
|
|
|
'use strict';
|
|
|
|
|
2018-06-23 03:26:46 +00:00
|
|
|
const userDb = require('./database.js').dbs.user;
|
2015-05-11 22:39:28 +00:00
|
|
|
|
2018-06-23 03:26:46 +00:00
|
|
|
const async = require('async');
|
|
|
|
const _ = require('lodash');
|
2015-05-11 22:39:28 +00:00
|
|
|
|
2018-06-23 03:26:46 +00:00
|
|
|
exports.getGroupsForUser = getGroupsForUser;
|
|
|
|
exports.addUserToGroup = addUserToGroup;
|
|
|
|
exports.addUserToGroups = addUserToGroups;
|
|
|
|
exports.removeUserFromGroup = removeUserFromGroup;
|
2015-05-11 22:39:28 +00:00
|
|
|
|
|
|
|
function getGroupsForUser(userId, cb) {
|
2018-06-22 05:15:04 +00:00
|
|
|
const sql =
|
2018-06-23 03:26:46 +00:00
|
|
|
`SELECT group_name
|
|
|
|
FROM user_group_member
|
|
|
|
WHERE user_id=?;`;
|
2015-05-11 22:39:28 +00:00
|
|
|
|
2018-06-22 05:15:04 +00:00
|
|
|
const groups = [];
|
2015-05-11 22:39:28 +00:00
|
|
|
|
2018-06-22 05:15:04 +00:00
|
|
|
userDb.each(sql, [ userId ], (err, row) => {
|
|
|
|
if(err) {
|
|
|
|
return cb(err);
|
|
|
|
}
|
2018-01-15 19:22:11 +00:00
|
|
|
|
2018-06-22 05:15:04 +00:00
|
|
|
groups.push(row.group_name);
|
|
|
|
},
|
|
|
|
() => {
|
|
|
|
return cb(null, groups);
|
|
|
|
});
|
2015-05-11 22:39:28 +00:00
|
|
|
}
|
|
|
|
|
2017-09-16 23:13:11 +00:00
|
|
|
function addUserToGroup(userId, groupName, transOrDb, cb) {
|
2018-06-22 05:15:04 +00:00
|
|
|
if(!_.isFunction(cb) && _.isFunction(transOrDb)) {
|
|
|
|
cb = transOrDb;
|
|
|
|
transOrDb = userDb;
|
|
|
|
}
|
2017-09-16 23:13:11 +00:00
|
|
|
|
2018-06-22 05:15:04 +00:00
|
|
|
transOrDb.run(
|
|
|
|
`REPLACE INTO user_group_member (group_name, user_id)
|
2018-06-23 03:26:46 +00:00
|
|
|
VALUES(?, ?);`,
|
2018-06-22 05:15:04 +00:00
|
|
|
[ groupName, userId ],
|
|
|
|
err => {
|
|
|
|
return cb(err);
|
|
|
|
}
|
|
|
|
);
|
2015-05-11 22:39:28 +00:00
|
|
|
}
|
|
|
|
|
2017-09-16 23:13:11 +00:00
|
|
|
function addUserToGroups(userId, groups, transOrDb, cb) {
|
2015-08-21 04:29:16 +00:00
|
|
|
|
2018-06-22 05:15:04 +00:00
|
|
|
async.each(groups, (groupName, nextGroupName) => {
|
|
|
|
return addUserToGroup(userId, groupName, transOrDb, nextGroupName);
|
|
|
|
}, err => {
|
|
|
|
return cb(err);
|
|
|
|
});
|
2015-05-11 22:39:28 +00:00
|
|
|
}
|
|
|
|
|
2015-08-21 04:29:16 +00:00
|
|
|
function removeUserFromGroup(userId, groupName, cb) {
|
2018-06-22 05:15:04 +00:00
|
|
|
userDb.run(
|
|
|
|
`DELETE FROM user_group_member
|
2018-06-23 03:26:46 +00:00
|
|
|
WHERE group_name=? AND user_id=?;`,
|
2018-06-22 05:15:04 +00:00
|
|
|
[ groupName, userId ],
|
|
|
|
err => {
|
|
|
|
return cb(err);
|
|
|
|
}
|
|
|
|
);
|
2015-05-11 22:39:28 +00:00
|
|
|
}
|