core: emit types for callable model operation

This commit is contained in:
undefined committed 2021-03-15 02:05:22 +08:00
1 parent 2fe5d37c03
commit 599c1f7c18
29 files changed
+174 -199

No files matched your search

+1
View File
@@ -24,6 +24,7 @@ rules:
'@typescript-eslint/naming-convention': off '@typescript-eslint/naming-convention': off
'@typescript-eslint/no-redeclare': off '@typescript-eslint/no-redeclare': off
class-methods-use-this: off
global-require: off global-require: off
guard-for-in: off guard-for-in: off
implicit-arrow-linebreak: off implicit-arrow-linebreak: off
+1
View File
@@ -13,6 +13,7 @@ const compilerOptionsBase = {
composite: true, composite: true,
strictBindCallApply: true, strictBindCallApply: true,
experimentalDecorators: true, experimentalDecorators: true,
emitDecoratorMetadata: true,
}; };
const config = { const config = {
compilerOptions: compilerOptionsBase, compilerOptions: compilerOptionsBase,
+4 -4
View File
@@ -21,12 +21,12 @@
"@shelf/jest-mongodb": "^1.2.3", "@shelf/jest-mongodb": "^1.2.3",
"@types/cross-spawn": "^6.0.2", "@types/cross-spawn": "^6.0.2",
"@types/jest": "^26.0.20", "@types/jest": "^26.0.20",
"@types/node": "^14.14.31", "@types/node": "^14.14.34",
"@types/semver": "^7.3.4", "@types/semver": "^7.3.4",
"@typescript-eslint/eslint-plugin": "^4.16.1", "@typescript-eslint/eslint-plugin": "^4.17.0",
"@typescript-eslint/parser": "^4.16.1", "@typescript-eslint/parser": "^4.17.0",
"cross-spawn": "^7.0.3", "cross-spawn": "^7.0.3",
"eslint": "^7.21.0", "eslint": "^7.22.0",
"eslint-config-airbnb-typescript": "^12.0.0", "eslint-config-airbnb-typescript": "^12.0.0",
"eslint-import-resolver-typescript": "^2.4.0", "eslint-import-resolver-typescript": "^2.4.0",
"eslint-plugin-import": "^2.22.1", "eslint-plugin-import": "^2.22.1",
+1 -1
View File
@@ -7,7 +7,7 @@
"author": "undefined <i@undefined.moe>", "author": "undefined <i@undefined.moe>",
"license": "AGPL-3.0-only", "license": "AGPL-3.0-only",
"dependencies": { "dependencies": {
"adm-zip": "^0.5.3", "adm-zip": "^0.5.4",
"decode-html": "^2.0.0", "decode-html": "^2.0.0",
"fs-extra": "^9.1.0", "fs-extra": "^9.1.0",
"xml2js": "^0.4.23" "xml2js": "^0.4.23"
+2 -2
View File
@@ -9,7 +9,7 @@
"author": "undefined <i@undefined.moe>", "author": "undefined <i@undefined.moe>",
"repository": "https://github.com/hydro-dev/Hydro.git", "repository": "https://github.com/hydro-dev/Hydro.git",
"dependencies": { "dependencies": {
"adm-zip": "^0.5.3", "adm-zip": "^0.5.4",
"axios": "^0.21.1", "axios": "^0.21.1",
"bson": "^4.2.3", "bson": "^4.2.3",
"fs-extra": "^9.1.0", "fs-extra": "^9.1.0",
@@ -17,7 +17,7 @@
"lodash": "^4.17.21", "lodash": "^4.17.21",
"p-queue": "^6.6.1", "p-queue": "^6.6.1",
"shell-quote": "^1.7.2", "shell-quote": "^1.7.2",
"systeminformation": "5.3.3", "systeminformation": "5.6.2",
"ws": "^7.4.4", "ws": "^7.4.4",
"yargs": "^16.2.0" "yargs": "^16.2.0"
}, },
+3 -3
View File
@@ -11,7 +11,7 @@
"node": ">=13" "node": ">=13"
}, },
"dependencies": { "dependencies": {
"adm-zip": "^0.5.3", "adm-zip": "^0.5.4",
"ansi_up": "^5.0.0", "ansi_up": "^5.0.0",
"cookies": "^0.8.0", "cookies": "^0.8.0",
"detect-browser": "^5.1.1", "detect-browser": "^5.1.1",
@@ -34,7 +34,7 @@
"serialize-javascript": "^5.0.1", "serialize-javascript": "^5.0.1",
"sockjs": "^0.3.20", "sockjs": "^0.3.20",
"superagent": "^6.1.0", "superagent": "^6.1.0",
"systeminformation": "5.3.3", "systeminformation": "5.6.2",
"wtfnode": "^0.8.4", "wtfnode": "^0.8.4",
"yargs": "^16.2.0" "yargs": "^16.2.0"
}, },
@@ -50,7 +50,7 @@
"@types/lru-cache": "^5.1.0", "@types/lru-cache": "^5.1.0",
"@types/minio": "^7.0.7", "@types/minio": "^7.0.7",
"@types/mongodb": "^3.6.9", "@types/mongodb": "^3.6.9",
"@types/nodemailer": "^6.4.0", "@types/nodemailer": "^6.4.1",
"@types/serialize-javascript": "^5.0.0", "@types/serialize-javascript": "^5.0.0",
"@types/sockjs": "^0.3.32", "@types/sockjs": "^0.3.32",
"@types/superagent": "^4.1.8", "@types/superagent": "^4.1.8",
+1 -1
View File
@@ -15,7 +15,7 @@ import * as document from '../model/document';
import * as problem from '../model/problem'; import * as problem from '../model/problem';
import * as domain from '../model/domain'; import * as domain from '../model/domain';
import * as record from '../model/record'; import * as record from '../model/record';
import * as user from '../model/user'; import user from '../model/user';
import * as message from '../model/message'; import * as message from '../model/message';
import { import {
Route, Handler, Types, param, Route, Handler, Types, param,
+1 -1
View File
@@ -6,7 +6,7 @@ import {
} from '../interface'; } from '../interface';
import paginate from '../lib/paginate'; import paginate from '../lib/paginate';
import * as system from '../model/system'; import * as system from '../model/system';
import * as user from '../model/user'; import user from '../model/user';
import * as oplog from '../model/oplog'; import * as oplog from '../model/oplog';
import * as message from '../model/message'; import * as message from '../model/message';
import * as discussion from '../model/discussion'; import * as discussion from '../model/discussion';
+1 -1
View File
@@ -6,7 +6,7 @@ import {
} from '../error'; } from '../error';
import { log2 } from '../utils'; import { log2 } from '../utils';
import type { DomainDoc } from '../interface'; import type { DomainDoc } from '../interface';
import * as user from '../model/user'; import user from '../model/user';
import * as domain from '../model/domain'; import * as domain from '../model/domain';
import * as discussion from '../model/discussion'; import * as discussion from '../model/discussion';
import * as system from '../model/system'; import * as system from '../model/system';
+2 -2
View File
@@ -14,11 +14,11 @@ import * as contest from '../model/contest';
import * as message from '../model/message'; import * as message from '../model/message';
import * as document from '../model/document'; import * as document from '../model/document';
import * as system from '../model/system'; import * as system from '../model/system';
import * as user from '../model/user'; import user from '../model/user';
import * as setting from '../model/setting'; import * as setting from '../model/setting';
import * as domain from '../model/domain'; import * as domain from '../model/domain';
import * as discussion from '../model/discussion'; import * as discussion from '../model/discussion';
import * as token from '../model/token'; import token from '../model/token';
import * as training from '../model/training'; import * as training from '../model/training';
import { PERM, PRIV } from '../model/builtin'; import { PERM, PRIV } from '../model/builtin';
import { import {
+1 -1
View File
@@ -14,7 +14,7 @@ import {
import * as bus from '../service/bus'; import * as bus from '../service/bus';
import * as domain from '../model/domain'; import * as domain from '../model/domain';
import { PERM } from '../model/builtin'; import { PERM } from '../model/builtin';
import * as user from '../model/user'; import user from '../model/user';
import * as system from '../model/system'; import * as system from '../model/system';
import * as contest from '../model/contest'; import * as contest from '../model/contest';
import * as discussion from '../model/discussion'; import * as discussion from '../model/discussion';
+1 -1
View File
@@ -5,7 +5,7 @@ import { ValidationError } from '../error';
import * as check from '../check'; import * as check from '../check';
import * as setting from '../model/setting'; import * as setting from '../model/setting';
import * as system from '../model/system'; import * as system from '../model/system';
import * as user from '../model/user'; import user from '../model/user';
import { STATUS, PRIV } from '../model/builtin'; import { STATUS, PRIV } from '../model/builtin';
import * as record from '../model/record'; import * as record from '../model/record';
import { import {
+1 -1
View File
@@ -1,7 +1,7 @@
/* eslint-disable camelcase */ /* eslint-disable camelcase */
import { BadRequestError } from '../error'; import { BadRequestError } from '../error';
import { PRIV } from '../model/builtin'; import { PRIV } from '../model/builtin';
import * as user from '../model/user'; import user from '../model/user';
import db from '../service/db'; import db from '../service/db';
import { import {
Route, Handler, Types, param, Route, Handler, Types, param,
+1 -1
View File
@@ -15,7 +15,7 @@ import * as system from '../model/system';
import * as problem from '../model/problem'; import * as problem from '../model/problem';
import * as record from '../model/record'; import * as record from '../model/record';
import * as domain from '../model/domain'; import * as domain from '../model/domain';
import * as user from '../model/user'; import user from '../model/user';
import * as solution from '../model/solution'; import * as solution from '../model/solution';
import { PERM, PRIV } from '../model/builtin'; import { PERM, PRIV } from '../model/builtin';
import storage from '../service/storage'; import storage from '../service/storage';
+6 -17
View File
@@ -1,17 +1,17 @@
import { FilterQuery, ObjectID } from 'mongodb'; import { FilterQuery, ObjectID } from 'mongodb';
import { PermissionError, RecordNotFoundError } from '../error'; import { PermissionError, RecordNotFoundError } from '../error';
import { Rdoc } from '../interface';
import { PERM, STATUS, PRIV } from '../model/builtin'; import { PERM, STATUS, PRIV } from '../model/builtin';
import * as system from '../model/system'; import * as system from '../model/system';
import * as problem from '../model/problem'; import * as problem from '../model/problem';
import * as record from '../model/record'; import * as record from '../model/record';
import * as contest from '../model/contest'; import * as contest from '../model/contest';
import * as user from '../model/user'; import user from '../model/user';
import paginate from '../lib/paginate'; import paginate from '../lib/paginate';
import * as bus from '../service/bus'; import * as bus from '../service/bus';
import { import {
Route, Handler, Connection, ConnectionHandler, Types, param, Route, Handler, Connection, ConnectionHandler, Types, param,
} from '../service/server'; } from '../service/server';
import { Rdoc } from '../interface';
const RecordHandler = contest.ContestHandlerMixin(Handler); const RecordHandler = contest.ContestHandlerMixin(Handler);
@@ -146,14 +146,10 @@ class RecordMainConnectionHandler extends RecordConnectionHandler {
@param('tid', Types.ObjectID, true) @param('tid', Types.ObjectID, true)
async prepare(domainId: string, tid?: ObjectID) { async prepare(domainId: string, tid?: ObjectID) {
this.domainId = domainId;
if (tid) { if (tid) {
const tdoc = await contest.get(domainId, tid, -1); const tdoc = await contest.get(domainId, tid, -1);
if (this.canShowRecord(tdoc)) this.tid = tid.toHexString(); if (this.canShowRecord(tdoc)) this.tid = tid.toHexString();
else { else throw new PermissionError(PERM.PERM_VIEW_CONTEST_HIDDEN_SCOREBOARD);
this.close();
return;
}
} }
this.dispose = bus.on('record/change', this.onRecordChange.bind(this)); this.dispose = bus.on('record/change', this.onRecordChange.bind(this));
} }
@@ -161,12 +157,8 @@ class RecordMainConnectionHandler extends RecordConnectionHandler {
async message(msg) { async message(msg) {
if (msg.rids instanceof Array) { if (msg.rids instanceof Array) {
const rids = msg.rids.map((id: string) => new ObjectID(id)); const rids = msg.rids.map((id: string) => new ObjectID(id));
const rdocs = await record.getMulti( const rdocs = await record.getMulti(this.domainId, { _id: { $in: rids } }).toArray();
this.domainId, { _id: { $in: rids } }, for (const rdoc of rdocs) this.onRecordChange(rdoc);
).toArray();
for (const rdoc of rdocs) {
this.onRecordChange(rdoc);
}
} }
} }
@@ -199,10 +191,7 @@ class RecordDetailConnectionHandler extends contest.ContestHandlerMixin(Connecti
const rdoc = await record.get(domainId, rid); const rdoc = await record.get(domainId, rid);
if (rdoc.contest) { if (rdoc.contest) {
const tdoc = await contest.get(domainId, rdoc.contest.tid, -1); const tdoc = await contest.get(domainId, rdoc.contest.tid, -1);
if (!this.canShowRecord(tdoc)) { if (!this.canShowRecord(tdoc)) throw new PermissionError(PERM.PERM_VIEW_CONTEST_HIDDEN_SCOREBOARD);
this.close();
return;
}
} }
this.rid = rid.toString(); this.rid = rid.toString();
this.dispose = bus.on('record/change', this.onRecordChange.bind(this)); this.dispose = bus.on('record/change', this.onRecordChange.bind(this));
+1 -1
View File
@@ -5,7 +5,7 @@ import { PermissionError, InvalidTokenError, RemoteOnlineJudgeError } from '../e
import { Logger } from '../logger'; import { Logger } from '../logger';
import { ProblemAdd } from '../lib/ui'; import { ProblemAdd } from '../lib/ui';
import { PERM } from '../model/builtin'; import { PERM } from '../model/builtin';
import * as token from '../model/token'; import token from '../model/token';
import * as problem from '../model/problem'; import * as problem from '../model/problem';
import * as system from '../model/system'; import * as system from '../model/system';
import { import {
+1 -1
View File
@@ -9,7 +9,7 @@ import { PERM, PRIV } from '../model/builtin';
import * as problem from '../model/problem'; import * as problem from '../model/problem';
import * as builtin from '../model/builtin'; import * as builtin from '../model/builtin';
import * as training from '../model/training'; import * as training from '../model/training';
import * as user from '../model/user'; import user from '../model/user';
import * as bus from '../service/bus'; import * as bus from '../service/bus';
import { import {
Route, Handler, Types, param, Route, Handler, Types, param,
+2 -2
View File
@@ -7,9 +7,9 @@ import {
import { import {
Route, Handler, Types, param, post, Route, Handler, Types, param, post,
} from '../service/server'; } from '../service/server';
import * as user from '../model/user'; import user from '../model/user';
import * as oauth from '../model/oauth'; import * as oauth from '../model/oauth';
import * as token from '../model/token'; import token from '../model/token';
import * as record from '../model/record'; import * as record from '../model/record';
import * as problem from '../model/problem'; import * as problem from '../model/problem';
import * as task from '../model/task'; import * as task from '../model/task';
+11 -4
View File
@@ -1,9 +1,12 @@
import { ArgMethod } from '../utils';
import db from '../service/db'; import db from '../service/db';
import * as bus from '../service/bus'; import * as bus from '../service/bus';
const coll = db.collection('blacklist'); const coll = db.collection('blacklist');
export async function add(ip: string) { class BlackListModel {
@ArgMethod
static async add(ip: string) {
const expireAt = new Date(new Date().getTime() + 365 * 24 * 60 * 60 * 1000); const expireAt = new Date(new Date().getTime() + 365 * 24 * 60 * 60 * 1000);
const res = await coll.findOneAndUpdate( const res = await coll.findOneAndUpdate(
{ _id: ip }, { _id: ip },
@@ -13,17 +16,21 @@ export async function add(ip: string) {
return res.value; return res.value;
} }
export async function get(ip: string) { @ArgMethod
static async get(ip: string) {
return await coll.findOne({ _id: ip }); return await coll.findOne({ _id: ip });
} }
export async function del(ip: string) { @ArgMethod
static async del(ip: string) {
return await coll.deleteOne({ _id: ip }); return await coll.deleteOne({ _id: ip });
} }
}
async function ensureIndexes() { async function ensureIndexes() {
return await coll.createIndex('expireAt', { expireAfterSeconds: 0 }); return await coll.createIndex('expireAt', { expireAfterSeconds: 0 });
} }
bus.once('app/started', ensureIndexes); bus.once('app/started', ensureIndexes);
global.Hydro.model.blacklist = { add, get, del }; export = BlackListModel;
global.Hydro.model.blacklist = BlackListModel;
+1 -1
View File
@@ -1,5 +1,5 @@
import { ObjectID, FilterQuery } from 'mongodb'; import { ObjectID, FilterQuery } from 'mongodb';
import * as user from './user'; import user from './user';
import * as problem from './problem'; import * as problem from './problem';
import * as document from './document'; import * as document from './document';
import { PERM } from './builtin'; import { PERM } from './builtin';
+1 -1
View File
@@ -1,5 +1,5 @@
import { FilterQuery, ObjectID } from 'mongodb'; import { FilterQuery, ObjectID } from 'mongodb';
import * as user from './user'; import user from './user';
import { Mdoc } from '../interface'; import { Mdoc } from '../interface';
import db from '../service/db'; import db from '../service/db';
import * as bus from '../service/bus'; import * as bus from '../service/bus';
+45 -57
View File
@@ -1,30 +1,24 @@
import { FilterQuery } from 'mongodb'; import { FilterQuery } from 'mongodb';
import { ArgMethod } from '../utils';
import { TokenDoc } from '../interface'; import { TokenDoc } from '../interface';
import db from '../service/db'; import db from '../service/db';
import * as bus from '../service/bus'; import * as bus from '../service/bus';
export const coll = db.collection('token'); class TokenModel {
static coll = db.collection('token');
static TYPE_SESSION = 0;
static TYPE_REGISTRATION = 2;
static TYPE_CHANGEMAIL = 3;
static TYPE_OAUTH = 4;
static TYPE_LOSTPASS = 5;
static TYPE_EXPORT = 6;
static TYPE_IMPORT = 7;
export const TYPE_SESSION = 0; static async add(
export const TYPE_REGISTRATION = 2;
export const TYPE_CHANGEMAIL = 3;
export const TYPE_OAUTH = 4;
export const TYPE_LOSTPASS = 5;
export const TYPE_EXPORT = 6;
export const TYPE_IMPORT = 7;
function ensureIndexes() {
return Promise.all([
coll.createIndex({ uid: 1, tokenType: 1, updateAt: -1 }, { sparse: true }),
coll.createIndex('expireAt', { expireAfterSeconds: 0 }),
]);
}
export async function add(
tokenType: number, expireSeconds: number, data: any, id = String.random(32), tokenType: number, expireSeconds: number, data: any, id = String.random(32),
): Promise<[string, TokenDoc]> { ): Promise<[string, TokenDoc]> {
const now = new Date(); const now = new Date();
const res = await coll.insertOne({ const res = await TokenModel.coll.insertOne({
...data, ...data,
_id: id, _id: id,
tokenType, tokenType,
@@ -35,20 +29,21 @@ export async function add(
return [id, res.ops[0]]; return [id, res.ops[0]];
} }
export async function get(tokenId: string, tokenType: number): Promise<TokenDoc | null> { @ArgMethod
return await coll.findOne({ _id: tokenId, tokenType }); static async get(tokenId: string, tokenType: number): Promise<TokenDoc | null> {
return await TokenModel.coll.findOne({ _id: tokenId, tokenType });
} }
export function getMulti(tokenType: number, query: FilterQuery<TokenDoc> = {}) { static getMulti(tokenType: number, query: FilterQuery<TokenDoc> = {}) {
return coll.find({ tokenType, ...query }); return TokenModel.coll.find({ tokenType, ...query });
} }
export async function update( static async update(
tokenId: string, tokenType: number, expireSeconds: number, tokenId: string, tokenType: number, expireSeconds: number,
data: object, data: object,
) { ) {
const now = new Date(); const now = new Date();
const res = await coll.findOneAndUpdate( const res = await TokenModel.coll.findOneAndUpdate(
{ _id: tokenId, tokenType }, { _id: tokenId, tokenType },
{ {
$set: { $set: {
@@ -63,55 +58,48 @@ export async function update(
return res.value; return res.value;
} }
export async function del(tokenId: string, tokenType: number) { @ArgMethod
const result = await coll.deleteOne({ _id: tokenId, tokenType }); static async del(tokenId: string, tokenType: number) {
const result = await TokenModel.coll.deleteOne({ _id: tokenId, tokenType });
return !!result.deletedCount; return !!result.deletedCount;
} }
export async function createOrUpdate( static async createOrUpdate(
tokenType: number, expireSeconds: number, data: any, tokenType: number, expireSeconds: number, data: any,
): Promise<string> { ): Promise<string> {
const d = await coll.findOne({ tokenType, ...data }); const d = await TokenModel.coll.findOne({ tokenType, ...data });
if (!d) { if (!d) {
const res = await add(tokenType, expireSeconds, data); const res = await TokenModel.add(tokenType, expireSeconds, data);
return res[0]; return res[0];
} }
await update(d._id, tokenType, expireSeconds, data); await TokenModel.update(d._id, tokenType, expireSeconds, data);
return d._id; return d._id;
} }
export function getSessionListByUid(uid: number) { @ArgMethod
return coll.find({ uid, tokenType: TYPE_SESSION }).sort('updateAt', -1).toArray(); static getSessionListByUid(uid: number) {
return TokenModel.coll.find({ uid, tokenType: TokenModel.TYPE_SESSION }).sort('updateAt', -1).toArray();
} }
export async function getMostRecentSessionByUid(uid: number) { @ArgMethod
const res = await coll.find({ uid, tokenType: TYPE_SESSION }).sort('updateAt', -1).toArray(); static async getMostRecentSessionByUid(uid: number) {
const res = await TokenModel.coll.find({ uid, tokenType: TokenModel.TYPE_SESSION }).sort('updateAt', -1).toArray();
return res[0]; return res[0];
} }
export function delByUid(uid: number) { @ArgMethod
return coll.deleteMany({ uid }); static delByUid(uid: number) {
return TokenModel.coll.deleteMany({ uid });
}
}
function ensureIndexes() {
return Promise.all([
TokenModel.coll.createIndex({ uid: 1, tokenType: 1, updateAt: -1 }, { sparse: true }),
TokenModel.coll.createIndex('expireAt', { expireAfterSeconds: 0 }),
]);
} }
bus.once('app/started', ensureIndexes); bus.once('app/started', ensureIndexes);
global.Hydro.model.token = { export = TokenModel;
coll, global.Hydro.model.token = TokenModel;
TYPE_SESSION,
TYPE_CHANGEMAIL,
TYPE_OAUTH,
TYPE_REGISTRATION,
TYPE_LOSTPASS,
TYPE_EXPORT,
TYPE_IMPORT,
add,
createOrUpdate,
get,
getMulti,
update,
del,
delByUid,
getMostRecentSessionByUid,
getSessionListByUid,
};
+73 -88
View File
@@ -1,9 +1,10 @@
import { Collection } from 'mongodb'; import { Collection } from 'mongodb';
import * as system from './system'; import * as system from './system';
import * as token from './token'; import token from './token';
import * as setting from './setting'; import * as setting from './setting';
import * as domain from './domain'; import * as domain from './domain';
import { BUILTIN_USERS, PERM, PRIV } from './builtin'; import { BUILTIN_USERS, PERM, PRIV } from './builtin';
import { ArgMethod } from '../utils';
import { UserNotFoundError, UserAlreadyExistError, LoginError } from '../error'; import { UserNotFoundError, UserAlreadyExistError, LoginError } from '../error';
import { User as _User, Udoc, Udict } from '../interface'; import { User as _User, Udoc, Udict } from '../interface';
import { Value } from '../typeutils'; import { Value } from '../typeutils';
@@ -15,66 +16,23 @@ import * as bus from '../service/bus';
const coll: Collection<Udoc> = db.collection('user'); const coll: Collection<Udoc> = db.collection('user');
const logger = new Logger('model/user'); const logger = new Logger('model/user');
export async function setPassword(uid: number, password: string): Promise<Udoc> { class User implements _User {
const salt = String.random();
const res = await coll.findOneAndUpdate(
{ _id: uid },
{ $set: { salt, hash: pwhash(password, salt), hashType: 'hydro' } },
{ returnOriginal: false },
);
return res.value;
}
export const defaultUser: Udoc = {
_id: 0,
uname: 'Unknown User',
unameLower: 'unknown user',
gravatar: 'unknown@hydro.local',
mail: 'unknown@hydro.local',
mailLower: 'unknown@hydro.local',
salt: '',
hash: '',
hashType: 'hydro',
priv: 0,
regat: new Date('2000-01-01'),
loginat: new Date('2000-01-01'),
regip: '127.0.0.1',
loginip: '127.0.0.1',
};
export class User implements _User {
udoc: () => any; udoc: () => any;
dudoc: () => any; dudoc: () => any;
_id: number; _id: number;
mail: string; mail: string;
uname: string; uname: string;
salt: () => string; salt: () => string;
hash: () => string; hash: () => string;
hashType: string; hashType: string;
priv: number; priv: number;
regat: Date; regat: Date;
loginat: Date; loginat: Date;
perm: () => bigint; perm: () => bigint;
role: string; role: string;
regip: () => string; regip: () => string;
loginip: () => string; loginip: () => string;
scope: () => bigint; scope: () => bigint;
[key: string]: any; [key: string]: any;
constructor(udoc: Udoc, dudoc, scope = PERM.PERM_ALL) { constructor(udoc: Udoc, dudoc, scope = PERM.PERM_ALL) {
@@ -132,12 +90,33 @@ export class User implements _User {
if (h(password, this.salt(), this) !== this.hash()) { if (h(password, this.salt(), this) !== this.hash()) {
throw new LoginError(this.uname); throw new LoginError(this.uname);
} else if (this.hashType !== 'hydro') { } else if (this.hashType !== 'hydro') {
setPassword(this._id, password); // eslint-disable-next-line @typescript-eslint/no-use-before-define
UserModel.setPassword(this._id, password);
} }
} }
} }
export async function getById(domainId: string, _id: number, scope = PERM.PERM_ALL): Promise<User | null> { class UserModel {
static User = User;
static defaultUser: Udoc = {
_id: 0,
uname: 'Unknown User',
unameLower: 'unknown user',
gravatar: 'unknown@hydro.local',
mail: 'unknown@hydro.local',
mailLower: 'unknown@hydro.local',
salt: '',
hash: '',
hashType: 'hydro',
priv: 0,
regat: new Date('2000-01-01'),
loginat: new Date('2000-01-01'),
regip: '127.0.0.1',
loginip: '127.0.0.1',
};
@ArgMethod
static async getById(domainId: string, _id: number, scope: bigint = PERM.PERM_ALL): Promise<User | null> {
const udoc = _id === 0 || _id === 1 const udoc = _id === 0 || _id === 1
? BUILTIN_USERS[_id] ? BUILTIN_USERS[_id]
: await coll.findOne({ _id }); : await coll.findOne({ _id });
@@ -146,15 +125,16 @@ export async function getById(domainId: string, _id: number, scope = PERM.PERM_A
return new User(udoc, dudoc, scope); return new User(udoc, dudoc, scope);
} }
export async function getList(domainId: string, uids: number[]): Promise<Udict> { static async getList(domainId: string, uids: number[]): Promise<Udict> {
const _uids = new Set(uids); const _uids = new Set(uids);
const r = {}; const r = {};
// eslint-disable-next-line no-await-in-loop // eslint-disable-next-line no-await-in-loop
for (const uid of _uids) r[uid] = (await getById(domainId, uid)) || defaultUser; for (const uid of _uids) r[uid] = (await UserModel.getById(domainId, uid)) || UserModel.defaultUser;
return r; return r;
} }
export async function getByUname(domainId: string, uname: string): Promise<User | null> { @ArgMethod
static async getByUname(domainId: string, uname: string): Promise<User | null> {
const unameLower = uname.trim().toLowerCase(); const unameLower = uname.trim().toLowerCase();
const udoc = (unameLower === 'guest') const udoc = (unameLower === 'guest')
? BUILTIN_USERS[0] ? BUILTIN_USERS[0]
@@ -163,10 +143,11 @@ export async function getByUname(domainId: string, uname: string): Promise<User
: await coll.findOne({ unameLower }); : await coll.findOne({ unameLower });
if (!udoc) return null; if (!udoc) return null;
const dudoc = await domain.getDomainUser(domainId, udoc); const dudoc = await domain.getDomainUser(domainId, udoc);
return new User(udoc, dudoc); return new UserModel.User(udoc, dudoc);
} }
export async function getByEmail(domainId: string, mail: string): Promise<User | null> { @ArgMethod
static async getByEmail(domainId: string, mail: string): Promise<User | null> {
const mailLower = mail.trim().toLowerCase(); const mailLower = mail.trim().toLowerCase();
const udoc = (mailLower === 'guest@hydro.local') const udoc = (mailLower === 'guest@hydro.local')
? BUILTIN_USERS[0] ? BUILTIN_USERS[0]
@@ -175,21 +156,35 @@ export async function getByEmail(domainId: string, mail: string): Promise<User |
: await coll.findOne({ mailLower }); : await coll.findOne({ mailLower });
if (!udoc) return null; if (!udoc) return null;
const dudoc = await domain.getDomainUser(domainId, udoc); const dudoc = await domain.getDomainUser(domainId, udoc);
return new User(udoc, dudoc); return new UserModel.User(udoc, dudoc);
} }
export async function setById(uid: number, $set?: Partial<Udoc>, $unset?: Value<Partial<Udoc>, ''>) { @ArgMethod
static async setById(uid: number, $set?: Partial<Udoc>, $unset?: Value<Partial<Udoc>, ''>) {
const op: any = {}; const op: any = {};
if ($set && Object.keys($set).length) op.$set = $set; if ($set && Object.keys($set).length) op.$set = $set;
if ($unset && Object.keys($unset).length) op.$unset = $unset; if ($unset && Object.keys($unset).length) op.$unset = $unset;
return await coll.findOneAndUpdate({ _id: uid }, op); return await coll.findOneAndUpdate({ _id: uid }, op);
} }
export function setEmail(uid: number, mail: string) { @ArgMethod
return setById(uid, { mail, mailLower: mail.trim().toLowerCase() }); static setEmail(uid: number, mail: string) {
return UserModel.setById(uid, { mail, mailLower: mail.trim().toLowerCase() });
} }
export async function inc(_id: number, field: string, n = 1) { @ArgMethod
static async setPassword(uid: number, password: string): Promise<Udoc> {
const salt = String.random();
const res = await coll.findOneAndUpdate(
{ _id: uid },
{ $set: { salt, hash: pwhash(password, salt), hashType: 'hydro' } },
{ returnOriginal: false },
);
return res.value;
}
@ArgMethod
static async inc(_id: number, field: string, n: number = 1) {
const udoc = await coll.findOne({ _id }); const udoc = await coll.findOne({ _id });
if (!udoc) throw new UserNotFoundError(_id); if (!udoc) throw new UserNotFoundError(_id);
udoc[field] = udoc[field] + n || n; udoc[field] = udoc[field] + n || n;
@@ -197,9 +192,10 @@ export async function inc(_id: number, field: string, n = 1) {
return udoc; return udoc;
} }
export async function create( @ArgMethod
static async create(
mail: string, uname: string, password: string, mail: string, uname: string, password: string,
uid = 0, regip = '127.0.0.1', priv = PRIV.PRIV_DEFAULT, uid: number = 0, regip: string = '127.0.0.1', priv: number = PRIV.PRIV_DEFAULT,
) { ) {
const salt = String.random(); const salt = String.random();
if (!uid) uid = await system.inc('user'); if (!uid) uid = await system.inc('user');
@@ -227,21 +223,23 @@ export async function create(
return uid; return uid;
} }
export function getMulti(params: any = {}) { static getMulti(params: any = {}) {
return coll.find(params); return coll.find(params);
} }
export async function getPrefixList(domainId: string, prefix: string, limit = 50) { @ArgMethod
static async getPrefixList(domainId: string, prefix: string, limit: number = 50) {
prefix = prefix.toLowerCase(); prefix = prefix.toLowerCase();
const $regex = new RegExp(`\\A\\Q${prefix}\\E`, 'gmi'); const $regex = new RegExp(`\\A\\Q${prefix}\\E`, 'gmi');
const uids = await coll.find({ unameLower: { $regex } }) const uids = await coll.find({ unameLower: { $regex } })
.limit(limit).map((doc) => doc._id).toArray(); .limit(limit).map((doc) => doc._id).toArray();
const users = []; const users = [];
for (const uid of uids) users.push(getById(domainId, uid)); for (const uid of uids) users.push(UserModel.getById(domainId, uid));
return await Promise.all(users); return await Promise.all(users);
} }
export async function setPriv(uid: number, priv: number): Promise<Udoc | null> { @ArgMethod
static async setPriv(uid: number, priv: number): Promise<Udoc | null> {
const udoc = await coll.findOneAndUpdate( const udoc = await coll.findOneAndUpdate(
{ _id: uid }, { _id: uid },
{ $set: { priv } }, { $set: { priv } },
@@ -250,22 +248,26 @@ export async function setPriv(uid: number, priv: number): Promise<Udoc | null> {
return udoc.value; return udoc.value;
} }
export async function setSuperAdmin(uid: number) { @ArgMethod
await setPriv(uid, PRIV.PRIV_ALL); static async setSuperAdmin(uid: number) {
await UserModel.setPriv(uid, PRIV.PRIV_ALL);
return uid; return uid;
} }
export async function setJudge(uid: number) { @ArgMethod
await setPriv(uid, PRIV.PRIV_USER_PROFILE | PRIV.PRIV_JUDGE); static async setJudge(uid: number) {
await UserModel.setPriv(uid, PRIV.PRIV_USER_PROFILE | PRIV.PRIV_JUDGE);
return uid; return uid;
} }
export function ban(uid: number) { @ArgMethod
static ban(uid: number) {
return Promise.all([ return Promise.all([
setPriv(uid, PRIV.PRIV_NONE), UserModel.setPriv(uid, PRIV.PRIV_NONE),
token.delByUid(uid), token.delByUid(uid),
]); ]);
} }
}
function ensureIndexes() { function ensureIndexes() {
return Promise.all([ return Promise.all([
@@ -275,22 +277,5 @@ function ensureIndexes() {
} }
bus.once('app/started', ensureIndexes); bus.once('app/started', ensureIndexes);
global.Hydro.model.user = { export = UserModel;
User, global.Hydro.model.user = UserModel;
defaultUser,
create,
getByEmail,
getById,
getByUname,
getMulti,
inc,
setById,
setEmail,
setPassword,
getPrefixList,
setPriv,
getList,
setSuperAdmin,
setJudge,
ban,
};
+2 -2
View File
@@ -2,8 +2,8 @@
import { ObjectID } from 'mongodb'; import { ObjectID } from 'mongodb';
import * as document from '../model/document'; import * as document from '../model/document';
import * as discussion from '../model/discussion'; import * as discussion from '../model/discussion';
import * as user from '../model/user'; import user from '../model/user';
import * as blacklist from '../model/blacklist'; import blacklist from '../model/blacklist';
import db from '../service/db'; import db from '../service/db';
export const description = 'Add blacklist by ip, uid'; export const description = 'Add blacklist by ip, uid';
+1 -1
View File
@@ -1,7 +1,7 @@
/* eslint-disable no-await-in-loop */ /* eslint-disable no-await-in-loop */
import { Udoc } from '../interface'; import { Udoc } from '../interface';
import { Value } from '../typeutils'; import { Value } from '../typeutils';
import * as user from '../model/user'; import user from '../model/user';
import * as document from '../model/document'; import * as document from '../model/document';
import * as setting from '../model/setting'; import * as setting from '../model/setting';
import db from '../service/db'; import db from '../service/db';
+3 -3
View File
@@ -26,11 +26,11 @@ import {
} from '../error'; } from '../error';
import hash from '../lib/hash.hydro'; import hash from '../lib/hash.hydro';
import * as misc from '../lib/misc'; import * as misc from '../lib/misc';
import * as user from '../model/user'; import user from '../model/user';
import * as domain from '../model/domain'; import * as domain from '../model/domain';
import * as system from '../model/system'; import * as system from '../model/system';
import * as blacklist from '../model/blacklist'; import blacklist from '../model/blacklist';
import * as token from '../model/token'; import token from '../model/token';
import * as opcount from '../model/opcount'; import * as opcount from '../model/opcount';
import { PERM } from '../model/builtin'; import { PERM } from '../model/builtin';
+4
View File
@@ -279,3 +279,7 @@ export function errorMessage(err: Error | string) {
err.stack = q.join('\n'); err.stack = q.join('\n');
return err; return err;
} }
export function ArgMethod(target: any, funcName: string, obj: any) {
return obj;
}
+1 -1
View File
@@ -7,7 +7,7 @@
"author": "undefined <i@undefined.moe>", "author": "undefined <i@undefined.moe>",
"license": "AGPL-3.0-only", "license": "AGPL-3.0-only",
"dependencies": { "dependencies": {
"adm-zip": "^0.5.3", "adm-zip": "^0.5.4",
"decode-html": "^2.0.0", "decode-html": "^2.0.0",
"fs-extra": "^9.1.0" "fs-extra": "^9.1.0"
}, },
+1 -1
View File
@@ -2,7 +2,7 @@ import { FilterQuery } from 'mongodb';
import { Pdoc } from 'hydrooj/dist/interface'; import { Pdoc } from 'hydrooj/dist/interface';
import * as problem from 'hydrooj/dist/model/problem'; import * as problem from 'hydrooj/dist/model/problem';
import * as record from 'hydrooj/dist/model/record'; import * as record from 'hydrooj/dist/model/record';
import * as user from 'hydrooj/dist/model/user'; import user from 'hydrooj/dist/model/user';
import { PERM, PRIV } from 'hydrooj/dist/model/builtin'; import { PERM, PRIV } from 'hydrooj/dist/model/builtin';
import { import {
Route, Handler, Types, post, Route, Handler, Types, post,