mirror of
https://gitcode.com/gh_mirrors/hy/Hydro.git
synced 2026-10-20 01:38:19 +08:00
fix role manage
This commit is contained in:
1 parent
15d43636c0
commit
42e534615e
34 files changed
+221
-314
No files matched your search
@@ -34,6 +34,8 @@ async function run() {
|
||||
require('./handler/user');
|
||||
require('./handler/contest');
|
||||
require('./handler/training');
|
||||
require('./handler/discussion');
|
||||
require('./handler/manage');
|
||||
require('./handler/import');
|
||||
server.start();
|
||||
}
|
||||
|
||||
@@ -46,12 +46,14 @@ class DiscussionHandler extends Handler {
|
||||
const pdoc = await problem.getById(docId);
|
||||
if (!pdoc) throw new DiscussionNodeNotFoundError(type, docId);
|
||||
if (pdoc.hidden) this.checkPerm(PERM_VIEW_PROBLEM_HIDDEN);
|
||||
this.title = pdoc.title;
|
||||
this.vnode = pdoc;
|
||||
} else if (type === 'contest') {
|
||||
const tdoc = await contest.get(docId);
|
||||
if (!tdoc) throw new DiscussionNodeNotFoundError(type, docId);
|
||||
this.title = tdoc.title;
|
||||
this.vnode = tdoc;
|
||||
} else throw new DiscussionNodeNotFoundError(type, docId);
|
||||
this.vnode.parentType = type;
|
||||
this.vnode.parentId = docId;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -62,7 +64,7 @@ class DiscussionMainHandler extends DiscussionHandler {
|
||||
const udict = await user.getList(ddocs.map((ddoc) => ddoc.owner));
|
||||
this.response.template = 'discussion_main_or_node.html';
|
||||
this.response.body = {
|
||||
ddocs, dpcount, udict, page,
|
||||
ddocs, dpcount, udict, page, page_name: 'discussion_main', vnode: {},
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -77,11 +79,17 @@ class DiscussionNodeHandler extends DiscussionHandler {
|
||||
const udict = await user.getList(ddocs.map((ddoc) => ddoc.owner));
|
||||
const path = [
|
||||
['discussion_main', '/discuss'],
|
||||
[this.title, null, true],
|
||||
[this.vnode.title, null, true],
|
||||
];
|
||||
this.response.template = 'discussion_main_or_node.html';
|
||||
this.response.body = {
|
||||
ddocs, dpcount, udict, path, page,
|
||||
ddocs,
|
||||
dpcount,
|
||||
udict,
|
||||
path,
|
||||
page,
|
||||
vnode: this.vnode,
|
||||
page_name: 'discussion_node',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -95,11 +103,11 @@ class DiscussionCreateHandler extends DiscussionHandler {
|
||||
async get({ type, docId }) {
|
||||
const path = [
|
||||
['discussion_main', '/discuss'],
|
||||
[this.title, `/discuss/${type}/${docId}`, true],
|
||||
[this.vnode.title, `/discuss/${type}/${docId}`, true],
|
||||
['discussion_create', null],
|
||||
];
|
||||
this.response.template = 'discussion_create.html';
|
||||
this.response.body = { path, title: this.title };
|
||||
this.response.body = { path, vnode: this.vnode };
|
||||
}
|
||||
|
||||
async post({
|
||||
@@ -139,7 +147,7 @@ class DiscussionDetailHandler extends DiscussionHandler {
|
||||
const udict = await user.getList(uids);
|
||||
const path = [
|
||||
['discussion_main', '/discuss'],
|
||||
[this.title, '/discuss/{type}', true],
|
||||
[this.vnode.title, '/discuss/{type}', true],
|
||||
[this.ddoc.title, null, true],
|
||||
];
|
||||
this.response.template = 'discussion_detail.html';
|
||||
|
||||
+19
-12
@@ -3,11 +3,12 @@ const user = require('../model/user');
|
||||
const builtin = require('../model/builtin');
|
||||
const { Route, Handler } = require('../service/server');
|
||||
const { PERM_ADMIN } = require('../permission');
|
||||
const { RoleAlreadyExistError } = require('../error');
|
||||
const { RoleAlreadyExistError, ValidationError } = require('../error');
|
||||
|
||||
class ManageHandler extends Handler {
|
||||
async prepare() {
|
||||
this.checkPerm(PERM_ADMIN);
|
||||
this.system = await user.getById(0);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,20 +21,21 @@ class ManageMainHandler extends ManageHandler {
|
||||
class ManageDashboardHandler extends ManageHandler {
|
||||
async get() {
|
||||
this.response.template = 'domain_manage_dashboard.html';
|
||||
this.response.body = { system: this.system };
|
||||
}
|
||||
}
|
||||
|
||||
class ManageEditHandler extends ManageHandler {
|
||||
async get() {
|
||||
this.response.template = 'domain_manage_edit.html';
|
||||
this.response.body = { system: this.system };
|
||||
}
|
||||
|
||||
async post({ name, gravatar, bulletin }) {
|
||||
await Promise.all([
|
||||
system.set('name', name),
|
||||
system.set('gravatar', gravatar),
|
||||
system.set('bulletin', bulletin),
|
||||
]);
|
||||
async post({ uname, gravatar, bio }) {
|
||||
const unameLower = uname.trim().toLowerCase();
|
||||
await user.setById(0, {
|
||||
uname, unameLower, gravatar, bio,
|
||||
});
|
||||
this.back();
|
||||
}
|
||||
}
|
||||
@@ -92,14 +94,19 @@ class ManageRoleHandler extends ManageHandler {
|
||||
}
|
||||
|
||||
async postAdd({ role }) {
|
||||
const roles = await user.getRoles();
|
||||
if (roles.includes(role)) throw new RoleAlreadyExistError(role);
|
||||
await user.setRole(role, builtin.PERM_DEFAULT);
|
||||
const r = await user.getRole(role);
|
||||
if (r) throw new RoleAlreadyExistError(role);
|
||||
await user.addRole(role, builtin.PERM_DEFAULT);
|
||||
this.back();
|
||||
}
|
||||
|
||||
async postDelete({ role }) {
|
||||
await user.deleteRoles(role);
|
||||
async postDelete({ roles }) {
|
||||
for (const role of roles) {
|
||||
if (['admin', 'default', 'guest'].includes(role)) {
|
||||
throw new ValidationError('role');
|
||||
}
|
||||
}
|
||||
await user.deleteRoles(roles);
|
||||
this.back();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,7 +4,6 @@ const token = require('../model/token');
|
||||
const system = require('../model/system');
|
||||
const { sendMail } = require('../lib/mail');
|
||||
const misc = require('../lib/misc');
|
||||
const validator = require('../lib/validator');
|
||||
const options = require('../options');
|
||||
const { PERM_REGISTER_USER, PERM_LOGGEDIN } = require('../permission');
|
||||
const {
|
||||
@@ -55,7 +54,6 @@ class UserRegisterHandler extends Handler {
|
||||
}
|
||||
|
||||
async post({ mail }) {
|
||||
validator.checkEmail(mail);
|
||||
if (await user.getByEmail(mail, true)) throw new UserAlreadyExistError(mail);
|
||||
this.limitRate('send_mail', 3600, 30);
|
||||
const t = await token.add(
|
||||
@@ -112,7 +110,6 @@ class UserLostPassHandler extends Handler {
|
||||
}
|
||||
|
||||
async post({ mail }) {
|
||||
validator.checkEmail(mail);
|
||||
const udoc = await user.getByEmail(mail);
|
||||
if (!udoc) throw new UserNotFoundError(mail);
|
||||
const tid = await token.add(
|
||||
|
||||
+5
-28
@@ -3,6 +3,7 @@ const { ValidationError } = require('../error');
|
||||
const RE_UID = /^-?\d+$/i;
|
||||
const RE_PID = /^([a-zA-Z]+[a-zA-Z0-9]*)|$/i;
|
||||
const RE_UNAME = /[^\s\u3000](.{,254}[^\s\u3000])?$/i;
|
||||
const RE_ROLE = /^[_0-9A-Za-z]{1,256}$/i;
|
||||
const RE_MAIL = /^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)+$/i;
|
||||
|
||||
const isTitle = (s) => s && s.length < 64;
|
||||
@@ -11,6 +12,8 @@ const isUid = (s) => RE_UID.test(s);
|
||||
const checkUid = (s) => { if (!isUid(s)) throw new ValidationError('uid'); else return s; };
|
||||
const isUname = (s) => RE_UNAME.test(s);
|
||||
const checkUname = (s) => { if (!isUname(s)) throw new ValidationError('uname'); else return s; };
|
||||
const isRole = (s) => RE_ROLE.test(s);
|
||||
const checkRole = (s) => { if (!isRole(s)) throw new ValidationError('role'); else return s; };
|
||||
const isPassword = (s) => s.length >= 5;
|
||||
const checkPassword = (s) => { if (!isPassword(s)) throw new ValidationError('password'); else return s; };
|
||||
const isEmail = (s) => RE_MAIL.test(s);
|
||||
@@ -33,6 +36,8 @@ module.exports = {
|
||||
checkUid,
|
||||
isUname,
|
||||
checkUname,
|
||||
isRole,
|
||||
checkRole,
|
||||
isPassword,
|
||||
checkPassword,
|
||||
isEmail,
|
||||
@@ -50,8 +55,6 @@ module.exports = {
|
||||
};
|
||||
/*
|
||||
ID_RE = re.compile(r'[^\\/\s\u3000]([^\\/\n\r]*[^\\/\s\u3000])?')
|
||||
ROLE_RE = re.compile(r'[_0-9A-Za-z]{1,256}')
|
||||
|
||||
|
||||
def is_id(s):
|
||||
return bool(ID_RE.fullmatch(s))
|
||||
@@ -67,14 +70,6 @@ def check_node_name(s):
|
||||
raise error.ValidationError('node_name')
|
||||
|
||||
|
||||
def is_role(s):
|
||||
return bool(ROLE_RE.fullmatch(s))
|
||||
|
||||
|
||||
def check_role(s):
|
||||
if not is_role(s):
|
||||
raise error.ValidationError('role')
|
||||
|
||||
def is_intro(s):
|
||||
return isinstance(s, str) and 0 < len(s.strip()) < 500
|
||||
|
||||
@@ -93,15 +88,6 @@ def check_description(s):
|
||||
raise error.ValidationError('description')
|
||||
|
||||
|
||||
def is_bulletin(s):
|
||||
return isinstance(s, str) and len(s) < 65536
|
||||
|
||||
|
||||
def check_bulletin(s):
|
||||
if not is_bulletin(s):
|
||||
raise error.ValidationError('bulletin')
|
||||
|
||||
|
||||
def is_lang(i):
|
||||
return i in constant.language.LANG_TEXTS
|
||||
|
||||
@@ -110,13 +96,4 @@ def check_lang(i):
|
||||
if not is_lang(i):
|
||||
raise error.ValidationError('lang')
|
||||
|
||||
|
||||
def is_domain_invitation_code(s):
|
||||
return bool(DOMAIN_INVITATION_CODE_RE.fullmatch(s))
|
||||
|
||||
|
||||
def check_domain_invitation_code(s):
|
||||
if not is_domain_invitation_code(s):
|
||||
raise error.ValidationError('invitation_code')
|
||||
|
||||
*/
|
||||
@@ -2,8 +2,8 @@ const perm = require('../permission');
|
||||
|
||||
const BUILTIN_ROLES = [
|
||||
{ _id: 'guest', perm: perm.PERM_BASIC },
|
||||
{ _id: 'default', perm: perm.PERM_DEFAULT },
|
||||
{ _id: 'admin', perm: perm.PERM_ADMIN },
|
||||
{ _id: 'default', perm: perm.PERM_DEFAULT, count: 0 },
|
||||
{ _id: 'admin', perm: perm.PERM_ADMIN, count: 0 },
|
||||
];
|
||||
const CATEGORIES = {
|
||||
动态规划: [
|
||||
|
||||
@@ -41,7 +41,7 @@ function count(query) {
|
||||
}
|
||||
|
||||
function getMulti(query) {
|
||||
return coll.find(query).sort([{ updateAt: -1 }, { _id: -1 }]);
|
||||
return coll.find(query).sort('updateAt', -1);
|
||||
}
|
||||
|
||||
async function addReply(did, owner, content, ip) {
|
||||
|
||||
+56
-25
@@ -1,7 +1,6 @@
|
||||
const system = require('./system');
|
||||
const { UserNotFoundError, UserAlreadyExistError } = require('../error');
|
||||
const pwhash = require('../lib/pwhash');
|
||||
const validator = require('../lib/validator');
|
||||
const db = require('../service/db');
|
||||
|
||||
const coll = db.collection('user');
|
||||
@@ -33,6 +32,7 @@ class USER {
|
||||
return pwhash.check(password, this.salt, this.hash);
|
||||
}
|
||||
}
|
||||
|
||||
async function getById(_id) {
|
||||
const udoc = await coll.findOne({ _id });
|
||||
if (!udoc) throw new UserNotFoundError(_id);
|
||||
@@ -40,11 +40,13 @@ async function getById(_id) {
|
||||
udoc.perm = role.perm;
|
||||
return new USER(udoc);
|
||||
}
|
||||
|
||||
async function getList(uids) {
|
||||
const r = {};
|
||||
for (const uid of uids) r[uid] = await getById(uid); // eslint-disable-line no-await-in-loop
|
||||
return r;
|
||||
}
|
||||
|
||||
async function getByUname(uname) {
|
||||
const unameLower = uname.trim().toLowerCase();
|
||||
const udoc = await coll.findOne({ unameLower });
|
||||
@@ -53,6 +55,7 @@ async function getByUname(uname) {
|
||||
udoc.perm = role.perm;
|
||||
return new USER(udoc);
|
||||
}
|
||||
|
||||
async function getByEmail(mail, ignoreMissing = false) {
|
||||
const mailLower = mail.trim().toLowerCase();
|
||||
const udoc = await coll.findOne({ mailLower });
|
||||
@@ -64,22 +67,23 @@ async function getByEmail(mail, ignoreMissing = false) {
|
||||
udoc.perm = role.perm;
|
||||
return new USER(udoc);
|
||||
}
|
||||
|
||||
function setPassword(uid, password) {
|
||||
validator.checkPassword(password);
|
||||
const salt = pwhash.salt();
|
||||
return coll.findOneAndUpdate({ _id: uid }, {
|
||||
$set: { salt, hash: pwhash.hash(password, salt) },
|
||||
});
|
||||
}
|
||||
|
||||
function setById(uid, args) {
|
||||
coll.findOneAndUpdate({ _id: uid }, { $set: args });
|
||||
return coll.findOneAndUpdate({ _id: uid }, { $set: args });
|
||||
}
|
||||
|
||||
function setEmail(uid, mail) {
|
||||
validator.checkEmail(mail);
|
||||
return setById(uid, { mail, mailLower: mail.trim().toLowerCase() });
|
||||
}
|
||||
|
||||
async function changePassword(uid, currentPassword, newPassword) {
|
||||
validator.checkPassword(newPassword);
|
||||
const udoc = await getById(uid);
|
||||
udoc.checkPassword(currentPassword);
|
||||
const salt = pwhash.salt();
|
||||
@@ -89,59 +93,86 @@ async function changePassword(uid, currentPassword, newPassword) {
|
||||
$set: { salt, hash: pwhash.hash(newPassword, salt) },
|
||||
});
|
||||
}
|
||||
|
||||
async function inc(_id, field, n) {
|
||||
await coll.findOneAndUpdate({ _id }, { $inc: { [field]: n } });
|
||||
const udoc = await getById(_id);
|
||||
return udoc;
|
||||
}
|
||||
|
||||
async function create({
|
||||
uid, mail, uname, password, regip = '127.0.0.1', role = 'default',
|
||||
}) {
|
||||
validator.checkUname(uname);
|
||||
validator.checkPassword(password);
|
||||
validator.checkEmail(mail);
|
||||
const salt = pwhash.salt();
|
||||
if (!uid) uid = system.inc('user');
|
||||
try {
|
||||
await coll.insertOne({
|
||||
_id: uid,
|
||||
mail,
|
||||
mailLower: mail.trim().toLowerCase(),
|
||||
uname,
|
||||
unameLower: uname.trim().toLowerCase(),
|
||||
password: pwhash.hash(password, salt),
|
||||
salt,
|
||||
regat: new Date(),
|
||||
regip,
|
||||
loginat: new Date(),
|
||||
loginip: regip,
|
||||
role,
|
||||
gravatar: mail,
|
||||
});
|
||||
await Promise.all([
|
||||
coll.insertOne({
|
||||
_id: uid,
|
||||
mail,
|
||||
mailLower: mail.trim().toLowerCase(),
|
||||
uname,
|
||||
unameLower: uname.trim().toLowerCase(),
|
||||
password: pwhash.hash(password, salt),
|
||||
salt,
|
||||
regat: new Date(),
|
||||
regip,
|
||||
loginat: new Date(),
|
||||
loginip: regip,
|
||||
role,
|
||||
gravatar: mail,
|
||||
}),
|
||||
collRole.updateOne({ _id: role }, { $inc: { count: 1 } })
|
||||
]);
|
||||
} catch (e) {
|
||||
throw new UserAlreadyExistError([uid, uname, mail]);
|
||||
}
|
||||
}
|
||||
|
||||
function getMany(params) {
|
||||
function getMulti(params) {
|
||||
return coll.find(params);
|
||||
}
|
||||
|
||||
async function setRole(uid, role) {
|
||||
const udoc = await getById(uid);
|
||||
return await Promise.all([
|
||||
coll.findOneAndUpdate({ _id: uid }, { role }),
|
||||
collRole.updateOne({ _id: udoc.role }, { $inc: { count: -1 } }),
|
||||
collRole.updateOne({ _id: role }, { $inc: { count: 1 } }),
|
||||
]);
|
||||
}
|
||||
|
||||
function getRoles() {
|
||||
return collRole.find().toArray();
|
||||
}
|
||||
|
||||
function getRole(name) {
|
||||
return collRole.findOne({ _id: name });
|
||||
}
|
||||
|
||||
function addRole(name, perm) {
|
||||
return collRole.insertOne({ _id: name, perm, count: 0 });
|
||||
}
|
||||
|
||||
function deleteRoles(roles) {
|
||||
return collRole.deleteMany({ _id: { $in: roles } });
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
changePassword,
|
||||
create,
|
||||
getByEmail,
|
||||
getById,
|
||||
getByUname,
|
||||
getMany,
|
||||
getMulti,
|
||||
inc,
|
||||
setById,
|
||||
setEmail,
|
||||
setPassword,
|
||||
setRole,
|
||||
getRole,
|
||||
getList,
|
||||
getRoles,
|
||||
addRole,
|
||||
deleteRoles,
|
||||
};
|
||||
@@ -43,6 +43,7 @@ let options = {
|
||||
SOLUTION_PER_PAGE: 20,
|
||||
CONTEST_PER_PAGE: 20,
|
||||
TRAINING_PER_PAGE: 10,
|
||||
DISCUSSION_PER_PAGE: 50,
|
||||
CONTESTS_ON_MAIN: 5,
|
||||
TRAININGS_ON_MAIN: 5,
|
||||
DISCUSSIONS_ON_MAIN: 20,
|
||||
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
const Mongo = require('mongodb');
|
||||
const bus = require('../service/bus');
|
||||
const bus = require('./bus');
|
||||
const options = require('../options');
|
||||
|
||||
let mongourl = 'mongodb://';
|
||||
|
||||
+29
-14
@@ -113,6 +113,7 @@ class Handler {
|
||||
|
||||
back(body) {
|
||||
if (body) this.response.body = body;
|
||||
else if (this.preferJson) this.response.body = {};
|
||||
this.response.redirect = this.request.headers.referer || '/';
|
||||
}
|
||||
|
||||
@@ -165,17 +166,19 @@ class Handler {
|
||||
}
|
||||
|
||||
async renderBody() {
|
||||
if (!(this.response.body || this.response.template)) {
|
||||
this.response.body = { error: new NotFoundError() };
|
||||
this.response.template = 'error.html';
|
||||
}
|
||||
if (!this.preferJson) {
|
||||
if (this.response.body || this.response.template) {
|
||||
if (this.request.query.noTemplate || this.preferJson) return;
|
||||
const templateName = this.request.query.template || this.response.template;
|
||||
if (templateName) {
|
||||
this.response.body = this.response.body || {};
|
||||
await this.render(templateName, this.response.body);
|
||||
if (!this.response.redirect) {
|
||||
if (!(this.response.body || this.response.template)) {
|
||||
this.response.body = { error: new NotFoundError() };
|
||||
this.response.template = 'error.html';
|
||||
}
|
||||
if (!this.preferJson) {
|
||||
if (this.response.body || this.response.template) {
|
||||
if (this.request.query.noTemplate || this.preferJson) return;
|
||||
const templateName = this.request.query.template || this.response.template;
|
||||
if (templateName) {
|
||||
this.response.body = this.response.body || {};
|
||||
await this.render(templateName, this.response.body);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -192,7 +195,11 @@ class Handler {
|
||||
this.ctx.response.body = this.response.body;
|
||||
this.ctx.response.status = this.response.status || 200;
|
||||
}
|
||||
if (this.response.type) this.ctx.response.type = this.response.type;
|
||||
this.ctx.response.type = this.preferJson
|
||||
? 'application/json'
|
||||
: this.response.type
|
||||
? this.response.type
|
||||
: this.ctx.response.type;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -233,7 +240,7 @@ class Handler {
|
||||
console.error(error.message, error.params);
|
||||
console.error(error.stack);
|
||||
this.response.template = error instanceof UserFacingError ? 'error.html' : 'bsod.html';
|
||||
this.response.body = { error };
|
||||
this.response.body = { error: { message: error.message, params: error.params, stack: error.stack } };
|
||||
await this.___cleanup().catch(() => { });
|
||||
}
|
||||
}
|
||||
@@ -247,6 +254,8 @@ function Route(route, RouteHandler) {
|
||||
const method = ctx.method.toLowerCase();
|
||||
const args = { ...ctx.params, ...ctx.query, ...ctx.request.body };
|
||||
|
||||
if (h.___prepare) await h.___prepare(args);
|
||||
|
||||
for (const l of check) {
|
||||
if (args[l]) {
|
||||
args[l] = new ObjectID(args[l]);
|
||||
@@ -256,11 +265,17 @@ function Route(route, RouteHandler) {
|
||||
if (args.content) validator.checkContent(args.content);
|
||||
if (args.title) validator.checkContent(args.title);
|
||||
if (args.uid) args.uid = parseInt(validator.checkUid(args.uid));
|
||||
if (args.password) validator.checkPassword(args.password);
|
||||
if (args.mail) validator.checkEmail(args.mail);
|
||||
if (args.uname) validator.checkUname(args.uname);
|
||||
if (args.page) args.page = parseInt(args.page);
|
||||
if (args.duration) args.duration = parseFloat(args.duration);
|
||||
if (args.pids) args.pids = args.pids.split(',').map((i) => i.trim());
|
||||
if (args.role) validator.checkRole(args.role);
|
||||
if (args.roles) {
|
||||
for (const i of args.roles) validator.checkRole(i);
|
||||
}
|
||||
|
||||
if (h.___prepare) await h.___prepare(args);
|
||||
if (h.__prepare) await h.__prepare(args);
|
||||
if (h._prepare) await h._prepare(args);
|
||||
if (h.prepare) await h.prepare(args);
|
||||
|
||||
Reference in new issue
Block a user