我有一个UserAuth
类来管理我的用户访问控制。该类在这样的模块中:
const user_permission = require("../middleware/user_permission.json");
class UserAuth {
constructor(keys) {
this.keys = keys;
}
// returning true if user have permission
can(id, perm) {
let auth = false;
if (!id || !perm) {
console.log("error");
} else {
this.keys.forEach(key => {
if (key.userId == id && key.permissionId == perm) {
auth = true;
}
});
}
return auth;
}
// return permission array
allow(id, perm) {
const data = { userId: id, permissionId: perm };
if (!id || !perm) {
console.log("no input");
} else {
this.keys.forEach(key => {
if (id !== key.userId || perm === key.permissionId) {
console.log("id non esiste oppure permesso esiste");
} else {
this.keys.push(data);
}
});
}
return (this.keys = this.removeDuplicates(this.keys));
}
// return permission array
disallow(id, perm) {
if (!id || !perm) {
console.log("error");
} else {
const result = this.keys.findIndex(data => {
return data.userId === id && data.permissionId === perm;
});
this.keys.splice(result, 1);
}
return (this.keys = this.removeDuplicates(this.keys));
}
removeDuplicates(arr) {
const userIds = [];
const result = arr.filter((element, index, array) => {
var tempArr = element.userId + "" + element.permissionId;
if (userIds.indexOf(tempArr) === -1) {
userIds.push(tempArr);
return element;
}
});
result.sort((a, b) => {
return a.userId - b.userId;
});
return result
}
}
//const auth = new UserAuth(user_permission);
module.exports.UserAuth = UserAuth;
//module.exports.auth = auth;
我不知道导出类或类本身的距离是否更好。如果导出类,则可以在新模块中将config json数组user_permission
传递到auth模块之外,但是我不知道是否有副作用。我也想在中间代码中继续使用该类作为中间件
最好的方法是什么?
谢谢