remove domain system

This commit is contained in:
masnn committed 2020-04-03 20:56:08 +08:00
1 parent 7fa4a58abe
commit fc26af30ef
31 files changed
+709 -1242

No files matched your search

+2 -25
View File
@@ -1,20 +1,17 @@
const
{ MIDDLEWARE } = require('../service/server.js'),
user = require('../model/user'),
domain = require('../model/domain'),
blacklist = require('../model/blacklist'),
token = require('../model/token'),
options = require('../options'),
{
UserNotFoundError,
BlacklistedError,
PermissionError,
PrivilegeError
PermissionError
} = require('../error');
MIDDLEWARE(async (ctx, next) => {
try {
ctx.state.domainId = 'system';
let sid = ctx.cookies.get('sid');
let save = ctx.cookies.get('save');
let tokenType, expireSeconds;
@@ -33,11 +30,7 @@ MIDDLEWARE(async (ctx, next) => {
if (!ctx.session) ctx.session = { uid: 1 };
let bdoc = await blacklist.get(ctx.request.ip);
if (bdoc) throw new BlacklistedError(ctx.request.ip);
console.log(ctx.session.uid);
[ctx.state.user, ctx.state.domain] = await Promise.all([
user.getById(ctx.session.uid, ctx.state.domainId),
domain.get(ctx.state.domainId)
]);
ctx.state.user = await user.getById(ctx.session.uid);
if (!ctx.state.user) throw new UserNotFoundError(ctx.session.uid);
ctx.checkPerm = function (perm) {
for (let i in arguments) {
@@ -55,22 +48,6 @@ MIDDLEWARE(async (ctx, next) => {
}
}
};
ctx.checkPriv = function (priv) {
for (let i in arguments) {
if (arguments[i] instanceof Array) {
let p = false;
for (let j in arguments)
if (ctx.state.user.hasPriv(arguments[i][j])) {
p = true;
break;
}
if (!p) throw new PrivilegeError([arguments[i]]);
} else {
if (ctx.state.user.hasPriv(arguments[i])) continue;
else throw new PrivilegeError([[arguments[i]]]);
}
}
};
await next();
if (ctx.session.sid)
await token.update(ctx.session.sid, tokenType, expireSeconds, Object.assign({
+19 -418
View File
@@ -1,434 +1,35 @@
const
{ GET, SOCKET } = require('../service/server'),
{ assertQueue, consume } = require('../service/queue'),
{ requirePriv } = require('./tools'),
{ CONTEXT } = require('../service/server'),
queue = require('../service/queue'),
record = require('../model/record'),
token = require('../model/token'),
user = require('../model/user'),
{ PRIV_JUDGE } = require('../privilege');
{ requirePerm } = require('./tools'),
{ PERM_JUDGE } = require('../permission');
assertQueue('judge');
queue.assert('judge');
GET('/judge/noop', requirePriv(PRIV_JUDGE), async ctx => {
const { MIDDLEWARE, GET, POST } = CONTEXT();
MIDDLEWARE(requirePerm(PERM_JUDGE));
GET('/judge/noop', async ctx => {
ctx.body = {};
});
SOCKET('/judge/conn', async conn => {
let sid = await new Promise((resolve, reject) => {
setTimeout(reject, 5000);
conn.once('data', async (data) => {
console.log(data);
resolve(data);
});
});
let session = await token.get(sid, token.TYPE_SESSION);
let u = await user.getById(session.uid);
if (!u.hasPriv(PRIV_JUDGE)) conn.close(1000, 'PrivilegeError');
let h = 1;
let interval = setInterval(() => {
if (!h) h.close();
h = 0;
conn.write('h');
}, 30000);
conn.on('data', (data) => {
data = JSON.parse(data);
h++;
if (data.event == 'next') {
// TODO (masnn)
} else if (data.event == 'end') {
// TODO (masnn)
}
});
consume('judge', async rid => {
rid = rid.toString();
GET('/judge/fetch', async ctx => {
let rid = await queue.get('judge', false);
if (rid) {
let rdoc = await record.get(rid);
let data = {
event: 'judge',
rid, type: 0,
domainId: rdoc.domainId,
pid: rdoc.pid,
data: rdoc.data,
lang: rdoc.lang,
code: rdoc.code
};
conn.write(JSON.stringify(data));
});
conn.on('close', () => {
clearInterval(interval);
});
ctx.body = data;
}
});
POST('/judge/next', async ctx => {
console.log(ctx.request.body);
});
POST('/judge/end', async ctx => {
console.log(ctx.request.body);
});
/*
@app.route('/p/category/{category:[^/]*}/random', 'problem_category_random')
class ProblemCategoryRandomHandler(base.Handler):
@base.requirePerm(builtin.PERM_VIEW_PROBLEM)
@base.get_argument
@base.route_argument
@base.sanitize
async def get(self, *, category: str):
if not self.has_perm(builtin.PERM_VIEW_PROBLEM_HIDDEN):
f = {'hidden': False}
else:
f = {}
query = ProblemCategoryHandler.build_query(category)
pid = await problem.get_random_id(self.domainId, **query, **f)
if pid:
self.json_or_redirect(self.reverse_url('problem_detail', pid=pid))
else:
self.json_or_redirect(self.referer_or_main)
@app.route('/p/{pid}/submit', 'problem_submit')
class ProblemSubmitHandler(base.Handler):
@base.requirePerm(builtin.PERM_SUBMIT_PROBLEM)
@base.route_argument
@base.sanitize
async def get(self, *, pid: document.convert_doc_id):
# TODO(twd2): check status, eg. test, hidden problem, ...
uid = self.user['_id'] if self.has_priv(builtin.PRIV_USER_PROFILE) else None
pdoc = await problem.get(self.domainId, pid, uid)
if pdoc.get('hidden', False):
self.check_perm(builtin.PERM_VIEW_PROBLEM_HIDDEN)
udoc, dudoc = await asyncio.gather(user.get_by_uid(pdoc['owner_uid']),
domain.get_user(self.domainId, pdoc['owner_uid']))
if uid == None:
rdocs = []
else:
# TODO(iceboy): needs to be in sync with contest_detail_problem_submit
rdocs = await record \
.get_user_in_problem_multi(uid, self.domainId, pdoc['doc_id']) \
.sort([('_id', -1)]) \
.limit(10) \
.to_list()
if not self.prefer_json:
path_components = self.build_path(
(self.translate('problem_main'), self.reverse_url('problem_main')),
(pdoc['title'], self.reverse_url('problem_detail', pid=pdoc['doc_id'])),
(self.translate('problem_submit'), None))
self.render('problem_submit.html', pdoc=pdoc, udoc=udoc, rdocs=rdocs, dudoc=dudoc,
page_title=pdoc['title'], path_components=path_components)
else:
self.json({'rdocs': rdocs})
@base.requirePriv(builtin.PRIV_USER_PROFILE)
@base.requirePerm(builtin.PERM_SUBMIT_PROBLEM)
@base.route_argument
@base.post_argument
@base.require_csrf_token
@base.sanitize
@base.limitRate('add_record', 60, 100)
async def post(self, *, pid: document.convert_doc_id, lang: str, code: str):
# TODO(twd2): check status, eg. test, hidden problem, ...
pdoc = await problem.get(self.domainId, pid)
if pdoc.get('hidden', False):
self.check_perm(builtin.PERM_VIEW_PROBLEM_HIDDEN)
rid = await record.add(self.domainId, pdoc['doc_id'], constant.record.TYPE_SUBMISSION,
self.user['_id'], lang, code)
self.json_or_redirect(self.reverse_url('record_detail', rid=rid))
@app.route('/p/{pid}/pretest', 'problem_pretest')
class ProblemPretestHandler(base.Handler):
@base.requirePerm(builtin.PERM_SUBMIT_PROBLEM)
@base.route_argument
@base.post_argument
@base.require_csrf_token
@base.sanitize
@base.limitRate('add_record', 60, 100)
async def post(self, *, pid: document.convert_doc_id, lang: str, code: str,
data_input: str, data_output: str):
pdoc = await problem.get(self.domainId, pid)
# don't need to check hidden status
# create zip file, TODO(twd2): check file size
post = await self.request.post()
content = list(zip(post.getall('data_input'), post.getall('data_output')))
output_buffer = io.BytesIO()
zip_file = zipfile.ZipFile(output_buffer, 'a', zipfile.ZIP_DEFLATED)
config_content = str(len(content)) + '\n'
for i, (data_input, data_output) in enumerate(content):
input_file = 'input{0}.txt'.format(i)
output_file = 'output{0}.txt'.format(i)
config_content += '{0}|{1}|1|10|262144\n'.format(input_file, output_file)
zip_file.writestr('Input/{0}'.format(input_file), data_input)
zip_file.writestr('Output/{0}'.format(output_file), data_output)
zip_file.writestr('Config.ini', config_content)
# mark all files as created in Windows :p
for zfile in zip_file.filelist:
zfile.create_system = 0
zip_file.close()
fid = await fs.add_data('application/zip', output_buffer.getvalue())
output_buffer.close()
rid = await record.add(self.domainId, pdoc['doc_id'], constant.record.TYPE_PRETEST,
self.user['_id'], lang, code, fid)
self.json_or_redirect(self.reverse_url('record_detail', rid=rid))
@app.connection_route('/p/{pid}/pretest-conn', 'problem_pretest-conn')
class ProblemPretestConnection(record_handler.RecordVisibilityMixin, base.Connection):
async def on_open(self):
await super(ProblemPretestConnection, self).on_open()
self.pid = document.convert_doc_id(self.request.match_info['pid'])
bus.subscribe(self.on_record_change, ['record_change'])
async def on_record_change(self, e):
rdoc = e['value']
if rdoc['uid'] != self.user['_id'] or \
rdoc['domainId'] != self.domainId or rdoc['pid'] != self.pid:
return
# check permission for visibility: contest
if rdoc['tid']:
show_status, tdoc = await self.rdoc_contest_visible(rdoc)
if not show_status:
return
self.send(rdoc=rdoc)
async def on_close(self):
bus.unsubscribe(self.on_record_change)
@app.route('/p/{pid}/data', 'problem_data')
class ProblemDataHandler(base.Handler):
@base.route_argument
@base.sanitize
async def get(self, *, pid: document.convert_doc_id):
# Judges will have PRIV_READ_PROBLEM_DATA,
# domain administrators will have PERM_READ_PROBLEM_DATA,
# problem owner will have PERM_READ_PROBLEM_DATA_SELF.
pdoc = await problem.get(self.domainId, pid)
if type(pdoc['data']) is dict:
return self.redirect(self.reverse_url('problem_data',
domainId=pdoc['data']['domain'],
pid=pdoc['data']['pid']))
if (not self.own(pdoc, builtin.PERM_READ_PROBLEM_DATA_SELF)
and not self.has_perm(builtin.PERM_READ_PROBLEM_DATA)):
self.check_priv(builtin.PRIV_READ_PROBLEM_DATA)
fdoc = await problem.get_data(pdoc)
if not fdoc:
raise error.ProblemDataNotFoundError(self.domainId, pid)
self.redirect(options.cdn_prefix.rstrip('/') + \
self.reverse_url('fs_get', domainId=builtin.domainId_SYSTEM,
secret=fdoc['metadata']['secret']))
@app.route('/p/copy', 'problem_copy')
class ProblemCopyHandler(base.Handler):
MAX_PROBLEMS_PER_REQUEST = 20
@base.requirePriv(builtin.PRIV_USER_PROFILE)
@base.requirePerm(builtin.PERM_CREATE_PROBLEM)
async def get(self):
self.render('problem_copy.html')
@base.requirePriv(builtin.PRIV_USER_PROFILE)
@base.requirePerm(builtin.PERM_CREATE_PROBLEM)
@base.post_argument
@base.require_csrf_token
@base.sanitize
@base.limitRate('copy_problems', 30, 10)
async def post(self, *, src_domainId: str, src_pids: str,
numeric_pid: bool=False, hidden: bool=False):
src_ddoc, src_dudoc = await asyncio.gather(domain.get(src_domainId),
domain.get_user(src_domainId, self.user['_id']))
if not src_dudoc:
src_dudoc = {}
if not self.dudoc_has_perm(ddoc=src_ddoc, dudoc=src_dudoc, udoc=self.user,
perm=builtin.PERM_VIEW_PROBLEM):
# TODO: This is the source domain's PermissionError.
raise error.PermissionError(builtin.PERM_VIEW_PROBLEM)
src_pids = misc.dedupe(map(document.convert_doc_id, src_pids.replace('\r\n', '\n').split('\n')))
if len(src_pids) > self.MAX_PROBLEMS_PER_REQUEST:
raise error.BatchCopyLimitExceededError(self.MAX_PROBLEMS_PER_REQUEST, len(src_pids))
pdocs = await problem.get_multi(domainId=src_domainId, doc_id={'$in': src_pids}) \
.sort('doc_id', 1) \
.to_list()
exist_pids = [pdoc['doc_id'] for pdoc in pdocs]
if len(src_pids) != len(exist_pids):
for pid in src_pids:
if pid not in exist_pids:
raise error.ProblemNotFoundError(src_domainId, pid)
for pdoc in pdocs:
if pdoc.get('hidden', False):
if not self.dudoc_has_perm(ddoc=src_ddoc, dudoc=src_dudoc, udoc=self.user,
perm=builtin.PERM_VIEW_PROBLEM_HIDDEN):
# TODO: This is the source domain's PermissionError.
raise error.PermissionError(builtin.PERM_VIEW_PROBLEM_HIDDEN)
for pdoc in pdocs:
pid = None
if numeric_pid:
pid = await domain.inc_pid_counter(self.domainId)
await problem.copy(pdoc, self.domainId, self.user['_id'], pid, hidden)
self.redirect(self.reverse_url('problem_main'))
@app.route('/p/{pid}/edit', 'problem_edit')
class ProblemEditHandler(base.Handler):
@base.requirePriv(builtin.PRIV_USER_PROFILE)
@base.route_argument
@base.sanitize
async def get(self, *, pid: document.convert_doc_id):
uid = self.user['_id'] if self.has_priv(builtin.PRIV_USER_PROFILE) else None
pdoc = await problem.get(self.domainId, pid, uid)
if not self.own(pdoc, builtin.PERM_EDIT_PROBLEM_SELF):
self.check_perm(builtin.PERM_EDIT_PROBLEM)
udoc, dudoc = await asyncio.gather(user.get_by_uid(pdoc['owner_uid']),
domain.get_user(self.domainId, pdoc['owner_uid']))
path_components = self.build_path(
(self.translate('problem_main'), self.reverse_url('problem_main')),
(pdoc['title'], self.reverse_url('problem_detail', pid=pdoc['doc_id'])),
(self.translate('problem_edit'), None))
self.render('problem_edit.html', pdoc=pdoc, udoc=udoc, dudoc=dudoc,
page_title=pdoc['title'], path_components=path_components)
@base.requirePriv(builtin.PRIV_USER_PROFILE)
@base.route_argument
@base.post_argument
@base.require_csrf_token
@base.sanitize
async def post(self, *, pid: document.convert_doc_id, title: str, content: str):
pdoc = await problem.get(self.domainId, pid)
if not self.own(pdoc, builtin.PERM_EDIT_PROBLEM_SELF):
self.check_perm(builtin.PERM_EDIT_PROBLEM)
await problem.edit(self.domainId, pdoc['doc_id'], title=title, content=content)
self.json_or_redirect(self.reverse_url('problem_detail', pid=pid))
@app.route('/p/{pid}/settings', 'problem_settings')
class ProblemSettingsHandler(base.Handler):
@base.requirePriv(builtin.PRIV_USER_PROFILE)
@base.route_argument
@base.sanitize
async def get(self, *, pid: document.convert_doc_id):
uid = self.user['_id'] if self.has_priv(builtin.PRIV_USER_PROFILE) else None
pdoc = await problem.get(self.domainId, pid, uid)
if not self.own(pdoc, builtin.PERM_EDIT_PROBLEM_SELF):
self.check_perm(builtin.PERM_EDIT_PROBLEM)
udoc, dudoc = await asyncio.gather(user.get_by_uid(pdoc['owner_uid']),
domain.get_user(self.domainId, pdoc['owner_uid']))
path_components = self.build_path(
(self.translate('problem_main'), self.reverse_url('problem_main')),
(pdoc['title'], self.reverse_url('problem_detail', pid=pdoc['doc_id'])),
(self.translate('problem_settings'), None))
self.render('problem_settings.html', pdoc=pdoc, udoc=udoc, dudoc=dudoc,
categories=problem.get_categories(),
page_title=pdoc['title'], path_components=path_components)
def split_tags(self, s):
s = s.replace(',', ',') # Chinese ', '
return list(filter(lambda _: _ != '', map(lambda _: _.strip(), s.split(','))))
@base.requirePriv(builtin.PRIV_USER_PROFILE)
@base.route_argument
@base.post_argument
@base.require_csrf_token
@base.sanitize
async def post(self, *, pid: document.convert_doc_id, hidden: bool=False,
category: str, tag: str,
difficulty_setting: int, difficulty_admin: str=''):
pdoc = await problem.get(self.domainId, pid)
if not self.own(pdoc, builtin.PERM_EDIT_PROBLEM_SELF):
self.check_perm(builtin.PERM_EDIT_PROBLEM)
category = self.split_tags(category)
tag = self.split_tags(tag)
for c in category:
if not (c in builtin.PROBLEM_CATEGORIES
or c in builtin.PROBLEM_SUB_CATEGORIES):
raise error.ValidationError('category')
if difficulty_setting not in problem.SETTING_DIFFICULTY_RANGE:
raise error.ValidationError('difficulty_setting')
if difficulty_admin:
try:
difficulty_admin = int(difficulty_admin)
except ValueError:
raise error.ValidationError('difficulty_admin')
else:
difficulty_admin = None
await problem.edit(self.domainId, pdoc['doc_id'], hidden=hidden,
category=category, tag=tag,
difficulty_setting=difficulty_setting, difficulty_admin=difficulty_admin)
await job.difficulty.update_problem(self.domainId, pdoc['doc_id'])
self.json_or_redirect(self.reverse_url('problem_detail', pid=pid))
@app.route('/p/{pid}/upload', 'problem_upload')
class ProblemUploadHandler(base.Handler):
def get_content_type(self, filename):
if os.path.splitext(filename)[1].lower() != '.zip':
raise error.FileTypeNotAllowedError(filename)
return 'application/zip'
@base.requirePriv(builtin.PRIV_USER_PROFILE)
@base.route_argument
@base.sanitize
async def get(self, *, pid: document.convert_doc_id):
pdoc = await problem.get(self.domainId, pid)
if not self.own(pdoc, builtin.PERM_EDIT_PROBLEM_SELF):
self.check_perm(builtin.PERM_EDIT_PROBLEM)
if (not self.own(pdoc, builtin.PERM_READ_PROBLEM_DATA_SELF)
and not self.has_perm(builtin.PERM_READ_PROBLEM_DATA)):
self.check_priv(builtin.PRIV_READ_PROBLEM_DATA)
md5 = await fs.get_md5(await problem.get_data(pdoc))
self.render('problem_upload.html', pdoc=pdoc, md5=md5)
@base.requirePriv(builtin.PRIV_USER_PROFILE)
@base.route_argument
@base.multipart_argument
@base.require_csrf_token
@base.sanitize
async def post(self, *, pid: document.convert_doc_id, file: objectid.ObjectId):
pdoc = await problem.get(self.domainId, pid)
if not self.own(pdoc, builtin.PERM_EDIT_PROBLEM_SELF):
self.check_perm(builtin.PERM_EDIT_PROBLEM)
if (not self.own(pdoc, builtin.PERM_READ_PROBLEM_DATA_SELF)
and not self.has_perm(builtin.PERM_READ_PROBLEM_DATA)):
self.check_priv(builtin.PRIV_READ_PROBLEM_DATA)
if pdoc.get('data') and type(pdoc['data']) is objectid.ObjectId:
await fs.unlink(pdoc['data'])
await problem.set_data(self.domainId, pid, file)
self.json_or_redirect(self.url)
@app.route('/p/{pid}/statistics', 'problem_statistics')
class ProblemStatisticsHandler(base.Handler):
@base.route_argument
@base.sanitize
async def get(self, *, pid: document.convert_doc_id):
# TODO(twd2)
uid = self.user['_id'] if self.has_priv(builtin.PRIV_USER_PROFILE) else None
pdoc = await problem.get(self.domainId, pid, uid)
if pdoc.get('hidden', False):
self.check_perm(builtin.PERM_VIEW_PROBLEM_HIDDEN)
udoc, dudoc = await asyncio.gather(user.get_by_uid(pdoc['owner_uid']),
domain.get_user(self.domainId, pdoc['owner_uid']))
path_components = self.build_path(
(self.translate('problem_main'), self.reverse_url('problem_main')),
(pdoc['title'], self.reverse_url('problem_detail', pid=pdoc['doc_id'])),
(self.translate('problem_statistics'), None))
self.render('problem_statistics.html', pdoc=pdoc, udoc=udoc, dudoc=dudoc,
page_title=pdoc['title'], path_components=path_components)
@app.route('/p/search', 'problem_search')
class ProblemSearchHandler(base.Handler):
@base.get_argument
@base.route_argument
@base.sanitize
async def get(self, *, q: str):
q = q.strip()
if not q:
self.json_or_redirect(self.referer_or_main)
return
try:
pdoc = await problem.get(self.domainId, document.convert_doc_id(q))
except error.ProblemNotFoundError:
pdoc = None
if pdoc:
self.redirect(self.reverse_url('problem_detail', pid=pdoc['doc_id']))
return
self.redirect('http://cn.bing.com/search?q={0}+site%3A{1}' \
.format(parse.quote(q), parse.quote(options.url_prefix)))
*/
+37 -49
View File
@@ -1,75 +1,63 @@
const
{ GET, POST } = require('../service/server'),
{ assertQueue, publish } = require('../service/queue'),
{ requirePerm, requirePriv } = require('./tools'),
validator = require('../lib/validator'),
problem = require('../model/problem'),
training = require('../model/training'),
contest = require('../model/contest'),
record = require('../model/record'),
domain = require('../model/domain'),
user = require('../model/user'),
{ GET, POST } = require('../service/server'),
queue = require('../service/queue'),
{ requirePerm } = require('./tools'),
{ NoProblemError } = require('../error'),
{ PRIV_USER_PROFILE } = require('../privilege'),
{ constants } = require('../options'),
{
PERM_VIEW_PROBLEM,
PERM_VIEW_PROBLEM_HIDDEN,
PERM_VIEW_TRAINING,
PERM_VIEW_CONTEST,
PERM_VIEW_HOMEWORK,
PERM_SUBMIT_PROBLEM,
PERM_CREATE_PROBLEM
} = require('../permission');
const PROBLEMS_PER_PAGE = 100;
assertQueue('judge');
queue.assert('judge');
GET('/p', requirePerm(PERM_VIEW_PROBLEM), async ctx => {
let q = { domainId: ctx.state.domainId },
let q = {},
page = ctx.query.page || 1;
if (!ctx.state.user.hasPerm(PERM_VIEW_PROBLEM_HIDDEN)) q.hidden = false;
let pdocs = await problem.getMany(q, { pid: 1 }, page, PROBLEMS_PER_PAGE);
ctx.body = { code: 0, page, pdocs, category: '' };
let pdocs = await problem.getMany(q, { pid: 1 }, page, constants.PROBLEM_PER_PAGE);
ctx.templateName = 'problem_main.html';
ctx.body = { page_name: 'problem_list', page, pdocs, category: '' };
});
GET('/problem/random', requirePerm(PERM_VIEW_PROBLEM), async ctx => {
let q = { domainId: ctx.state.domainId };
let q = {};
if (!ctx.state.user.hasPerm(PERM_VIEW_PROBLEM_HIDDEN)) q.hidden = false;
let pid = await problem.random(q);
if (!pid) throw new NoProblemError();
ctx.body = { pid };
});
GET('/p/:pid', requirePerm(PERM_VIEW_PROBLEM), async ctx => {
let uid = ctx.state.user._id,
pid = ctx.params.pid;
let pdoc = await problem.get({ pid, uid });
if (pdoc.hidden) ctx.checkPerm(PERM_VIEW_PROBLEM_HIDDEN);
let udoc = await user.getById(pdoc.owner);
ctx.body = { pdoc, udoc, title: pdoc.title };
});
POST('/p/:pid/submit', requirePerm(PERM_SUBMIT_PROBLEM), async ctx => {
let rid = await record.add({
creator: ctx.state.user._id,
lang: ctx.request.body.language,
code: ctx.request.body.code,
domainId: ctx.state.domainId,
pid: ctx.params.pid
});
await publish('judge', rid);
await queue.push('judge', rid);
ctx.state.user.nSubmit++;
ctx.body = { rid };
});
GET('/p/:pid', requirePerm(PERM_VIEW_PROBLEM), async ctx => {
let uid = null,
pid = Number(ctx.params.pid);
if (ctx.state.user.hasPriv(PRIV_USER_PROFILE)) uid = ctx.state.user._id;
let pdoc = await problem.get({ domainId: ctx.state.domainId, pid, uid });
if (pdoc.hidden) ctx.checkPerm(PERM_VIEW_PROBLEM_HIDDEN);
let udoc = await user.getById(pdoc.owner);
ctx.body = { pdoc, udoc, title: pdoc.title };
POST('/problem/create', requirePerm(PERM_CREATE_PROBLEM), async ctx => {
let { title, pid, content, hidden } = ctx.request.body;
validator.checkPid(pid);
pid = pid || await system.incPidCounter();
await problem.add({ title, content, owner: ctx.state.user._id, pid, hidden });
ctx.body = { pid };
});
POST('/problem/create',
requirePriv(PRIV_USER_PROFILE),
requirePerm(PERM_CREATE_PROBLEM),
async ctx => {
let { title, pid, content, hidden } = ctx.request.body;
validator.checkPid(pid);
pid = pid || await domain.incPidCounter(ctx.state.domainId);
await problem.add({ domainId: ctx.state.domainId, title, content, owner: ctx.state.user._id, pid, hidden });
ctx.body = { pid };
}
);
/*
@@ -110,14 +98,14 @@ class ProblemSubmitHandler(base.Handler):
else:
# TODO(iceboy): needs to be in sync with contest_detail_problem_submit
rdocs = await record \
.get_user_in_problem_multi(uid, self.domainId, pdoc['doc_id']) \
.get_user_in_problem_multi(uid, self.domainId, pdoc['_id']) \
.sort([('_id', -1)]) \
.limit(10) \
.to_list()
if not self.prefer_json:
path_components = self.build_path(
(self.translate('problem_main'), self.reverse_url('problem_main')),
(pdoc['title'], self.reverse_url('problem_detail', pid=pdoc['doc_id'])),
(pdoc['title'], self.reverse_url('problem_detail', pid=pdoc['_id'])),
(self.translate('problem_submit'), None))
self.render('problem_submit.html', pdoc=pdoc, udoc=udoc, rdocs=rdocs, dudoc=dudoc,
page_title=pdoc['title'], path_components=path_components)
@@ -136,7 +124,7 @@ class ProblemSubmitHandler(base.Handler):
pdoc = await problem.get(self.domainId, pid)
if pdoc.get('hidden', False):
self.check_perm(builtin.PERM_VIEW_PROBLEM_HIDDEN)
rid = await record.add(self.domainId, pdoc['doc_id'], constant.record.TYPE_SUBMISSION,
rid = await record.add(self.domainId, pdoc['_id'], constant.record.TYPE_SUBMISSION,
self.user['_id'], lang, code)
self.json_or_redirect(self.reverse_url('record_detail', rid=rid))
@@ -172,7 +160,7 @@ class ProblemPretestHandler(base.Handler):
zip_file.close()
fid = await fs.add_data('application/zip', output_buffer.getvalue())
output_buffer.close()
rid = await record.add(self.domainId, pdoc['doc_id'], constant.record.TYPE_PRETEST,
rid = await record.add(self.domainId, pdoc['_id'], constant.record.TYPE_PRETEST,
self.user['_id'], lang, code, fid)
self.json_or_redirect(self.reverse_url('record_detail', rid=rid))
@@ -256,7 +244,7 @@ class ProblemCopyHandler(base.Handler):
.sort('doc_id', 1) \
.to_list()
exist_pids = [pdoc['doc_id'] for pdoc in pdocs]
exist_pids = [pdoc['_id'] for pdoc in pdocs]
if len(src_pids) != len(exist_pids):
for pid in src_pids:
if pid not in exist_pids:
@@ -292,7 +280,7 @@ class ProblemEditHandler(base.Handler):
domain.get_user(self.domainId, pdoc['owner_uid']))
path_components = self.build_path(
(self.translate('problem_main'), self.reverse_url('problem_main')),
(pdoc['title'], self.reverse_url('problem_detail', pid=pdoc['doc_id'])),
(pdoc['title'], self.reverse_url('problem_detail', pid=pdoc['_id'])),
(self.translate('problem_edit'), None))
self.render('problem_edit.html', pdoc=pdoc, udoc=udoc, dudoc=dudoc,
page_title=pdoc['title'], path_components=path_components)
@@ -306,7 +294,7 @@ class ProblemEditHandler(base.Handler):
pdoc = await problem.get(self.domainId, pid)
if not self.own(pdoc, builtin.PERM_EDIT_PROBLEM_SELF):
self.check_perm(builtin.PERM_EDIT_PROBLEM)
await problem.edit(self.domainId, pdoc['doc_id'], title=title, content=content)
await problem.edit(self.domainId, pdoc['_id'], title=title, content=content)
self.json_or_redirect(self.reverse_url('problem_detail', pid=pid))
@@ -324,7 +312,7 @@ class ProblemSettingsHandler(base.Handler):
domain.get_user(self.domainId, pdoc['owner_uid']))
path_components = self.build_path(
(self.translate('problem_main'), self.reverse_url('problem_main')),
(pdoc['title'], self.reverse_url('problem_detail', pid=pdoc['doc_id'])),
(pdoc['title'], self.reverse_url('problem_detail', pid=pdoc['_id'])),
(self.translate('problem_settings'), None))
self.render('problem_settings.html', pdoc=pdoc, udoc=udoc, dudoc=dudoc,
categories=problem.get_categories(),
@@ -360,10 +348,10 @@ class ProblemSettingsHandler(base.Handler):
raise error.ValidationError('difficulty_admin')
else:
difficulty_admin = None
await problem.edit(self.domainId, pdoc['doc_id'], hidden=hidden,
await problem.edit(self.domainId, pdoc['_id'], hidden=hidden,
category=category, tag=tag,
difficulty_setting=difficulty_setting, difficulty_admin=difficulty_admin)
await job.difficulty.update_problem(self.domainId, pdoc['doc_id'])
await job.difficulty.update_problem(self.domainId, pdoc['_id'])
self.json_or_redirect(self.reverse_url('problem_detail', pid=pid))
@@ -419,7 +407,7 @@ class ProblemStatisticsHandler(base.Handler):
domain.get_user(self.domainId, pdoc['owner_uid']))
path_components = self.build_path(
(self.translate('problem_main'), self.reverse_url('problem_main')),
(pdoc['title'], self.reverse_url('problem_detail', pid=pdoc['doc_id'])),
(pdoc['title'], self.reverse_url('problem_detail', pid=pdoc['_id'])),
(self.translate('problem_statistics'), None))
self.render('problem_statistics.html', pdoc=pdoc, udoc=udoc, dudoc=dudoc,
page_title=pdoc['title'], path_components=path_components)
@@ -440,7 +428,7 @@ class ProblemSearchHandler(base.Handler):
except error.ProblemNotFoundError:
pdoc = None
if pdoc:
self.redirect(self.reverse_url('problem_detail', pid=pdoc['doc_id']))
self.redirect(self.reverse_url('problem_detail', pid=pdoc['_id']))
return
self.redirect('http://cn.bing.com/search?q={0}+site%3A{1}' \
.format(parse.quote(q), parse.quote(options.url_prefix)))
+14 -21
View File
@@ -1,19 +1,12 @@
const
bson = require('bson'),
{ constants } = require('../options'),
{ GET, POST } = require('../service/server'),
{ publish } = require('../service/queue'),
{ requirePerm, requirePriv } = require('./tools'),
validator = require('../lib/validator'),
problem = require('../model/problem'),
{ GET } = require('../service/server'),
record = require('../model/record'),
domain = require('../model/domain'),
user = require('../model/user'),
{ PRIV_USER_PROFILE } = require('../privilege'),
{ PERM_READ_RECORD_CODE, PERM_VIEW_CONTEST_HIDDEN_SCOREBOARD } = require('../permission');
GET('/r', async ctx => {
let q = { domainId: ctx.state.domainId },
let q = {},
page = ctx.query.page || 1;
let rdocs = await record.getMany(q, { rid: 1 }, page, constants.RECORD_PER_PAGE);
ctx.body = { page, rdocs };
@@ -65,14 +58,14 @@ class ProblemSubmitHandler(base.Handler):
else:
# TODO(iceboy): needs to be in sync with contest_detail_problem_submit
rdocs = await record \
.get_user_in_problem_multi(uid, self.domainId, pdoc['doc_id']) \
.get_user_in_problem_multi(uid, self.domainId, pdoc['_id']) \
.sort([('_id', -1)]) \
.limit(10) \
.to_list()
if not self.prefer_json:
path_components = self.build_path(
(self.translate('problem_main'), self.reverse_url('problem_main')),
(pdoc['title'], self.reverse_url('problem_detail', pid=pdoc['doc_id'])),
(pdoc['title'], self.reverse_url('problem_detail', pid=pdoc['_id'])),
(self.translate('problem_submit'), None))
self.render('problem_submit.html', pdoc=pdoc, udoc=udoc, rdocs=rdocs, dudoc=dudoc,
page_title=pdoc['title'], path_components=path_components)
@@ -91,7 +84,7 @@ class ProblemSubmitHandler(base.Handler):
pdoc = await problem.get(self.domainId, pid)
if pdoc.get('hidden', False):
self.check_perm(builtin.PERM_VIEW_PROBLEM_HIDDEN)
rid = await record.add(self.domainId, pdoc['doc_id'], constant.record.TYPE_SUBMISSION,
rid = await record.add(self.domainId, pdoc['_id'], constant.record.TYPE_SUBMISSION,
self.user['_id'], lang, code)
self.json_or_redirect(self.reverse_url('record_detail', rid=rid))
@@ -127,7 +120,7 @@ class ProblemPretestHandler(base.Handler):
zip_file.close()
fid = await fs.add_data('application/zip', output_buffer.getvalue())
output_buffer.close()
rid = await record.add(self.domainId, pdoc['doc_id'], constant.record.TYPE_PRETEST,
rid = await record.add(self.domainId, pdoc['_id'], constant.record.TYPE_PRETEST,
self.user['_id'], lang, code, fid)
self.json_or_redirect(self.reverse_url('record_detail', rid=rid))
@@ -211,7 +204,7 @@ class ProblemCopyHandler(base.Handler):
.sort('doc_id', 1) \
.to_list()
exist_pids = [pdoc['doc_id'] for pdoc in pdocs]
exist_pids = [pdoc['_id'] for pdoc in pdocs]
if len(src_pids) != len(exist_pids):
for pid in src_pids:
if pid not in exist_pids:
@@ -247,7 +240,7 @@ class ProblemEditHandler(base.Handler):
domain.get_user(self.domainId, pdoc['owner_uid']))
path_components = self.build_path(
(self.translate('problem_main'), self.reverse_url('problem_main')),
(pdoc['title'], self.reverse_url('problem_detail', pid=pdoc['doc_id'])),
(pdoc['title'], self.reverse_url('problem_detail', pid=pdoc['_id'])),
(self.translate('problem_edit'), None))
self.render('problem_edit.html', pdoc=pdoc, udoc=udoc, dudoc=dudoc,
page_title=pdoc['title'], path_components=path_components)
@@ -261,7 +254,7 @@ class ProblemEditHandler(base.Handler):
pdoc = await problem.get(self.domainId, pid)
if not self.own(pdoc, builtin.PERM_EDIT_PROBLEM_SELF):
self.check_perm(builtin.PERM_EDIT_PROBLEM)
await problem.edit(self.domainId, pdoc['doc_id'], title=title, content=content)
await problem.edit(self.domainId, pdoc['_id'], title=title, content=content)
self.json_or_redirect(self.reverse_url('problem_detail', pid=pid))
@@ -279,7 +272,7 @@ class ProblemSettingsHandler(base.Handler):
domain.get_user(self.domainId, pdoc['owner_uid']))
path_components = self.build_path(
(self.translate('problem_main'), self.reverse_url('problem_main')),
(pdoc['title'], self.reverse_url('problem_detail', pid=pdoc['doc_id'])),
(pdoc['title'], self.reverse_url('problem_detail', pid=pdoc['_id'])),
(self.translate('problem_settings'), None))
self.render('problem_settings.html', pdoc=pdoc, udoc=udoc, dudoc=dudoc,
categories=problem.get_categories(),
@@ -315,10 +308,10 @@ class ProblemSettingsHandler(base.Handler):
raise error.ValidationError('difficulty_admin')
else:
difficulty_admin = None
await problem.edit(self.domainId, pdoc['doc_id'], hidden=hidden,
await problem.edit(self.domainId, pdoc['_id'], hidden=hidden,
category=category, tag=tag,
difficulty_setting=difficulty_setting, difficulty_admin=difficulty_admin)
await job.difficulty.update_problem(self.domainId, pdoc['doc_id'])
await job.difficulty.update_problem(self.domainId, pdoc['_id'])
self.json_or_redirect(self.reverse_url('problem_detail', pid=pid))
@@ -374,7 +367,7 @@ class ProblemStatisticsHandler(base.Handler):
domain.get_user(self.domainId, pdoc['owner_uid']))
path_components = self.build_path(
(self.translate('problem_main'), self.reverse_url('problem_main')),
(pdoc['title'], self.reverse_url('problem_detail', pid=pdoc['doc_id'])),
(pdoc['title'], self.reverse_url('problem_detail', pid=pdoc['_id'])),
(self.translate('problem_statistics'), None))
self.render('problem_statistics.html', pdoc=pdoc, udoc=udoc, dudoc=dudoc,
page_title=pdoc['title'], path_components=path_components)
@@ -395,7 +388,7 @@ class ProblemSearchHandler(base.Handler):
except error.ProblemNotFoundError:
pdoc = None
if pdoc:
self.redirect(self.reverse_url('problem_detail', pid=pdoc['doc_id']))
self.redirect(self.reverse_url('problem_detail', pid=pdoc['_id']))
return
self.redirect('http://cn.bing.com/search?q={0}+site%3A{1}' \
.format(parse.quote(q), parse.quote(options.url_prefix)))
+1 -20
View File
@@ -1,6 +1,6 @@
const
opcount = require('../model/opcount'),
{ PermissionError, PrivilegeError } = require('../error');
{ PermissionError } = require('../error');
module.exports = {
requirePerm(perm) {
@@ -22,25 +22,6 @@ module.exports = {
await next();
};
},
requirePriv(priv) {
return async (ctx, next) => {
for (let i in arguments) {
if (arguments[i] instanceof Array) {
let p = false;
for (let j in arguments)
if (ctx.state.user.hasPriv(arguments[i][j])) {
p = true;
break;
}
if (!p) throw new PrivilegeError([arguments[i]]);
} else {
if (ctx.state.user.hasPriv(arguments[i])) continue;
else throw new PrivilegeError([arguments[i]]);
}
}
await next();
};
},
limitRate(op, period_secs, max_operations) {
return async (ctx, next) => {
await opcount.inc(op, ctx.request.ip, period_secs, max_operations);
+65
View File
@@ -0,0 +1,65 @@
const
path = require('path'),
static = require('koa-static'),
nunjucks = require('nunjucks'),
options = require('../options'),
perm = require('../permission'),
builtin = require('../model/builtin'),
{ MIDDLEWARE } = require('../service/server'),
{ NotFoundError } = require('../error');
class Nunjucks extends nunjucks.Environment {
constructor() {
super(
new nunjucks.FileSystemLoader(path.resolve(options.template.path)),
{ autoescape: true, trimBlocks: true }
);
this.addFilter('json', function (data) {
return JSON.stringify(data);
}, false);
this.addFilter('assign', function (self, data) {
return Object.assign(self, data);
});
this.addGlobal('static_url', str => `/${str}`);
this.addGlobal('reverse_url', str => str);
this.addGlobal('perm', perm);
this.addGlobal('builtin', builtin);
}
}
const env = new Nunjucks();
MIDDLEWARE(static(path.resolve(process.cwd(), '.uibuild')));
MIDDLEWARE(async (ctx, next) => {
ctx.render_title = str => str;
ctx.ui_context = {};
ctx.user_context = {};
ctx.render = async (name, context) => {
ctx.user = ctx.state.user;
ctx.translate = str => {
return str.translate(ctx.state.user.language);
};
ctx.has_perm = perm => ctx.state.user.hasPerm(perm);
ctx.body = await new Promise((resolve, reject) => {
env.render(name, Object.assign(ctx.state, context, {
handler: ctx,
_: ctx.translate
}), (error, res) => {
if (error) reject(error);
else resolve(res);
});
});
ctx.response.type = 'text/html';
};
try {
try {
await next();
if (!ctx.body) throw new NotFoundError();
} catch (error) {
await ctx.render('error.html', { error });
}
Object.assign(ctx.body, JSON.parse(ctx.query.data || '{}'));
console.log(ctx.body);
if (ctx.query.template || ctx.templateName) await ctx.render(ctx.query.template || ctx.templateName, ctx.body);
} catch (error) {
await ctx.render('bsod.html', { error });
}
});
+14 -11
View File
@@ -1,13 +1,13 @@
const
{ GET, POST } = require('../service/server.js'),
{ GET, POST, CONTEXT } = require('../service/server.js'),
user = require('../model/user'),
token = require('../model/token'),
system = require('../model/system'),
mail = require('../lib/mail'),
validator = require('../lib/validator'),
options = require('../options'),
{ PRIV_REGISTER_USER, PRIV_USER_PROFILE } = require('../privilege'),
{ requirePriv, limitRate } = require('./tools'),
{ PERM_REGISTER_USER, PERM_LOGGEDIN } = require('../permission'),
{ requirePerm, limitRate } = require('./tools'),
{ UserAlreadyExistError, InvalidTokenError, VerifyPasswordError, UserNotFoundError, LoginError } = require('../error');
GET('/user', async ctx => {
@@ -27,17 +27,20 @@ POST('/login', async ctx => {
ctx.session.rememberme = rememberme;
ctx.body = { udoc };
});
POST('/logout', requirePriv(PRIV_USER_PROFILE), async ctx => {
POST('/logout', requirePerm(PERM_LOGGEDIN), async ctx => {
ctx.session = { uid: 1 };
ctx.body = {};
});
GET('/register/:code', requirePriv(PRIV_REGISTER_USER), async ctx => {
let { GET: _GET, POST: _POST, MIDDLEWARE: _MIDDLEWARE } = CONTEXT();
_MIDDLEWARE(requirePerm(PERM_REGISTER_USER));
_GET('/register/:code', async ctx => {
let code = ctx.request.body.code;
let { mail } = await token.get(code, token.TYPE_REGISTRATION);
if (!mail) throw new InvalidTokenError(token.TYPE_REGISTRATION, code);
ctx.body = { mail };
});
GET('/register/:code', requirePriv(PRIV_REGISTER_USER), async ctx => {
_GET('/register/:code', async ctx => {
let { code, password, verify_password, uname } = ctx.request.body;
let { mail } = await token.get(code, token.TYPE_REGISTRATION);
if (!mail) throw new InvalidTokenError(token.TYPE_REGISTRATION, code);
@@ -50,7 +53,7 @@ GET('/register/:code', requirePriv(PRIV_REGISTER_USER), async ctx => {
});
if (options.smtp.user) {
POST('/register', requirePriv(PRIV_REGISTER_USER), limitRate('send_mail', 3600, 30), async ctx => {
_POST('/register', limitRate('send_mail', 3600, 30), async ctx => {
let email = ctx.request.body.email;
validator.check_mail(email);
if (await user.get_by_mail(email)) throw new UserAlreadyExistError(email);
@@ -59,7 +62,7 @@ if (options.smtp.user) {
await mail.send_mail(email, 'Sign Up', 'user_register_mail', m);
ctx.body = {};
});
POST('/lostpass', requirePriv(PRIV_REGISTER_USER), limitRate('send_mail', 3600, 30), async ctx => {
POST('/lostpass', limitRate('send_mail', 3600, 30), async ctx => {
let email = ctx.request.body.mail;
validator.check_mail(email);
let udoc = await user.getByEmail(email);
@@ -73,14 +76,14 @@ if (options.smtp.user) {
await mail.send_mail(email, 'Lost Password', 'user_lostpass_mail', m);
ctx.body = {};
});
GET('/lostpass/:code', requirePriv(PRIV_REGISTER_USER), async ctx => {
GET('/lostpass/:code', async ctx => {
let code = ctx.params.code;
let tdoc = await token.get(code, token.TYPE_LOSTPASS);
if (!tdoc) throw new InvalidTokenError(token.TYPE_LOSTPASS, code);
let udoc = await user.getById(tdoc.uid);
ctx.body = { uname: udoc.uname };
});
POST('/lostpass/:code', requirePriv(PRIV_REGISTER_USER), async ctx => {
POST('/lostpass/:code', async ctx => {
let code = ctx.params.code;
let password = ctx.request.body.password;
let verify_password = ctx.request.body.verify_password;
@@ -92,7 +95,7 @@ if (options.smtp.user) {
ctx.redirect('/');
});
} else
POST('/register', requirePriv(PRIV_REGISTER_USER), async ctx => {
_POST('/register', async ctx => {
let email = ctx.request.body.email;
validator.check_mail(email);
if (await user.get_by_mail(email)) throw new UserAlreadyExistError(email);