You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
341 lines
13 KiB
TypeScript
341 lines
13 KiB
TypeScript
4 years ago
|
import superagent from 'superagent';
|
||
|
import moment from 'moment-timezone';
|
||
|
import { Route, Handler } from '../service/server';
|
||
|
import * as user from '../model/user';
|
||
|
import * as token from '../model/token';
|
||
|
import * as record from '../model/record';
|
||
|
import * as problem from '../model/problem';
|
||
|
import * as task from '../model/task';
|
||
|
import * as system from '../model/system';
|
||
|
import { PERM, PRIV } from '../model/builtin';
|
||
|
import { sendMail } from '../lib/mail';
|
||
|
import * as misc from '../lib/misc';
|
||
|
import {
|
||
5 years ago
|
UserAlreadyExistError, InvalidTokenError, VerifyPasswordError,
|
||
|
UserNotFoundError, LoginError, SystemError,
|
||
4 years ago
|
BlacklistedError, UserFacingError,
|
||
4 years ago
|
} from '../error';
|
||
5 years ago
|
|
||
5 years ago
|
class UserLoginHandler extends Handler {
|
||
|
async get() {
|
||
4 years ago
|
const [loginWithGithub, loginWithGoogle] = await system.getMany(
|
||
|
['oauth.githubappid', 'oauth.googleappid'],
|
||
|
);
|
||
|
this.response.body = {
|
||
|
loginWithGithub, loginWithGoogle,
|
||
|
};
|
||
5 years ago
|
this.response.template = 'user_login.html';
|
||
|
}
|
||
5 years ago
|
|
||
4 years ago
|
async post({
|
||
|
domainId, uname, password, rememberme = false,
|
||
|
}) {
|
||
|
const udoc = await user.getByUname(domainId, uname);
|
||
5 years ago
|
if (!udoc) throw new LoginError(uname);
|
||
4 years ago
|
udoc.checkPassword(password);
|
||
5 years ago
|
await user.setById(udoc._id, { loginat: new Date(), loginip: this.request.ip });
|
||
4 years ago
|
if (udoc.priv === PRIV.PRIV_NONE) throw new BlacklistedError(uname);
|
||
5 years ago
|
this.session.uid = udoc._id;
|
||
4 years ago
|
this.session.save = rememberme;
|
||
4 years ago
|
this.response.redirect = this.request.referer.endsWith('/login') ? '/' : this.request.referer;
|
||
5 years ago
|
}
|
||
|
}
|
||
5 years ago
|
|
||
5 years ago
|
class UserLogoutHandler extends Handler {
|
||
|
async get() {
|
||
|
this.response.template = 'user_logout.html';
|
||
|
}
|
||
5 years ago
|
|
||
5 years ago
|
async post() {
|
||
4 years ago
|
this.session.uid = 0;
|
||
5 years ago
|
}
|
||
|
}
|
||
5 years ago
|
|
||
5 years ago
|
class UserRegisterHandler extends Handler {
|
||
|
async get() {
|
||
|
this.response.template = 'user_register.html';
|
||
|
}
|
||
5 years ago
|
|
||
5 years ago
|
async post({ mail }) {
|
||
4 years ago
|
if (await user.getByEmail('system', mail, true)) throw new UserAlreadyExistError(mail);
|
||
5 years ago
|
this.limitRate('send_mail', 3600, 30);
|
||
5 years ago
|
const t = await token.add(
|
||
|
token.TYPE_REGISTRATION,
|
||
5 years ago
|
await system.get('registration_token_expire_seconds'),
|
||
5 years ago
|
{ mail },
|
||
|
);
|
||
5 years ago
|
if (await system.get('smtp.user')) {
|
||
4 years ago
|
const m = await this.renderHTML('user_register_mail.html', {
|
||
4 years ago
|
path: `register/${t[0]}`,
|
||
|
url_prefix: await system.get('server.url'),
|
||
4 years ago
|
});
|
||
5 years ago
|
await sendMail(mail, 'Sign Up', 'user_register_mail', m);
|
||
|
this.response.template = 'user_register_mail_sent.html';
|
||
|
} else {
|
||
4 years ago
|
this.response.redirect = this.url('user_register_with_code', { code: t[0] });
|
||
5 years ago
|
}
|
||
|
}
|
||
|
}
|
||
5 years ago
|
|
||
5 years ago
|
class UserRegisterWithCodeHandler extends Handler {
|
||
|
async get({ code }) {
|
||
|
this.response.template = 'user_register_with_code.html';
|
||
5 years ago
|
const { mail } = await token.get(code, token.TYPE_REGISTRATION);
|
||
5 years ago
|
if (!mail) throw new InvalidTokenError(token.TYPE_REGISTRATION, code);
|
||
|
this.response.body = { mail };
|
||
|
}
|
||
5 years ago
|
|
||
|
async post({
|
||
|
code, password, verifyPassword, uname,
|
||
|
}) {
|
||
|
const { mail } = await token.get(code, token.TYPE_REGISTRATION);
|
||
5 years ago
|
if (!mail) throw new InvalidTokenError(token.TYPE_REGISTRATION, code);
|
||
5 years ago
|
if (password !== verifyPassword) throw new VerifyPasswordError();
|
||
5 years ago
|
const uid = await system.inc('user');
|
||
5 years ago
|
await user.create({
|
||
|
uid, uname, password, mail, regip: this.request.ip,
|
||
|
});
|
||
4 years ago
|
await token.del(code, token.TYPE_REGISTRATION);
|
||
5 years ago
|
this.session.uid = uid;
|
||
4 years ago
|
this.response.redirect = this.url('homepage');
|
||
5 years ago
|
}
|
||
|
}
|
||
5 years ago
|
|
||
5 years ago
|
class UserLostPassHandler extends Handler {
|
||
|
async get() {
|
||
5 years ago
|
if (!await system.get('smtp.user')) throw new SystemError('Cannot send mail');
|
||
5 years ago
|
this.response.template = 'user_lostpass.html';
|
||
|
}
|
||
5 years ago
|
|
||
5 years ago
|
async post({ mail }) {
|
||
5 years ago
|
if (!await system.get('smtp.user')) throw new SystemError('Cannot send mail');
|
||
4 years ago
|
const udoc = await user.getByEmail('system', mail);
|
||
5 years ago
|
if (!udoc) throw new UserNotFoundError(mail);
|
||
4 years ago
|
const [tid] = await token.add(
|
||
5 years ago
|
token.TYPE_LOSTPASS,
|
||
5 years ago
|
await system.get('lostpass_token_expire_seconds'),
|
||
5 years ago
|
{ uid: udoc._id },
|
||
5 years ago
|
);
|
||
4 years ago
|
const m = await this.renderHTML('user_lostpass_mail', { url: `lostpass/${tid}`, uname: udoc.uname });
|
||
5 years ago
|
await sendMail(mail, 'Lost Password', 'user_lostpass_mail', m);
|
||
|
this.response.template = 'user_lostpass_mail_sent.html';
|
||
|
}
|
||
|
}
|
||
5 years ago
|
|
||
5 years ago
|
class UserLostPassWithCodeHandler extends Handler {
|
||
4 years ago
|
async get({ domainId, code }) {
|
||
5 years ago
|
const tdoc = await token.get(code, token.TYPE_LOSTPASS);
|
||
5 years ago
|
if (!tdoc) throw new InvalidTokenError(token.TYPE_LOSTPASS, code);
|
||
4 years ago
|
const udoc = await user.getById(domainId, tdoc.uid);
|
||
5 years ago
|
this.response.body = { uname: udoc.uname };
|
||
|
}
|
||
5 years ago
|
|
||
|
async post({ code, password, verifyPassword }) {
|
||
|
const tdoc = await token.get(code, token.TYPE_LOSTPASS);
|
||
5 years ago
|
if (!tdoc) throw new InvalidTokenError(token.TYPE_LOSTPASS, code);
|
||
5 years ago
|
if (password !== verifyPassword) throw new VerifyPasswordError();
|
||
5 years ago
|
await user.setPassword(tdoc.uid, password);
|
||
4 years ago
|
await token.del(code, token.TYPE_LOSTPASS);
|
||
4 years ago
|
this.response.redirect = this.url('homepage');
|
||
5 years ago
|
}
|
||
|
}
|
||
5 years ago
|
|
||
5 years ago
|
class UserDetailHandler extends Handler {
|
||
4 years ago
|
async get({ domainId, uid }) {
|
||
5 years ago
|
const isSelfProfile = this.user._id === uid;
|
||
4 years ago
|
const udoc = await user.getById(domainId, uid, true);
|
||
5 years ago
|
const sdoc = await token.getMostRecentSessionByUid(uid);
|
||
4 years ago
|
const rdocs = await record.getByUid(domainId, uid);
|
||
4 years ago
|
const pdict = await problem.getList(
|
||
|
domainId, rdocs.map((rdoc) => rdoc.pid),
|
||
4 years ago
|
this.user.hasPerm(PERM.PERM_VIEW_PROBLEM_HIDDEN), false,
|
||
4 years ago
|
);
|
||
4 years ago
|
// Remove sensitive data
|
||
4 years ago
|
if (!isSelfProfile && sdoc) {
|
||
|
sdoc.createIp = '';
|
||
|
sdoc.updateIp = '';
|
||
|
sdoc._id = '';
|
||
|
}
|
||
5 years ago
|
this.response.template = 'user_detail.html';
|
||
4 years ago
|
this.response.body = {
|
||
|
isSelfProfile, udoc, sdoc, rdocs, pdict,
|
||
|
};
|
||
5 years ago
|
}
|
||
5 years ago
|
}
|
||
5 years ago
|
|
||
4 years ago
|
class UserDeleteHandler extends Handler {
|
||
|
async post({ password }) {
|
||
|
this.user.checkPassword(password);
|
||
|
const tid = await task.add({
|
||
|
executeAfter: moment().add(7, 'days').toDate(),
|
||
|
type: 'script',
|
||
|
id: 'deleteUser',
|
||
|
args: { uid: this.user._id },
|
||
|
});
|
||
|
await user.setById(this.user._id, { del: tid });
|
||
|
this.response.template = 'user_delete_pending.html';
|
||
|
}
|
||
|
}
|
||
|
|
||
5 years ago
|
class UserSearchHandler extends Handler {
|
||
4 years ago
|
async get({ domainId, q, exactMatch = false }) {
|
||
5 years ago
|
let udocs;
|
||
5 years ago
|
if (exactMatch) udocs = [];
|
||
5 years ago
|
else udocs = await user.getPrefixList(q, 20);
|
||
4 years ago
|
const udoc = await user.getById(domainId, parseInt(q, 10));
|
||
4 years ago
|
if (udoc) udocs.push(udoc);
|
||
5 years ago
|
for (const i in udocs) {
|
||
|
if (udocs[i].gravatar) {
|
||
4 years ago
|
udocs[i].gravatar = misc.gravatar(udocs[i].gravatar);
|
||
5 years ago
|
}
|
||
|
}
|
||
5 years ago
|
this.response.body = udocs;
|
||
5 years ago
|
}
|
||
5 years ago
|
}
|
||
|
|
||
4 years ago
|
class OauthHandler extends Handler {
|
||
4 years ago
|
async github() {
|
||
|
const [appid, [state]] = await Promise.all([
|
||
|
system.get('oauth.githubappid'),
|
||
|
token.add(token.TYPE_OAUTH, 600, { redirect: this.request.referer }),
|
||
|
]);
|
||
|
this.response.redirect = `https://github.com/login/oauth/authorize?client_id=${appid}&state=${state}`;
|
||
|
}
|
||
|
|
||
|
async google() {
|
||
|
const [appid, url, [state]] = await Promise.all([
|
||
|
system.get('oauth.googleappid'),
|
||
|
system.get('server.url'),
|
||
|
token.add(token.TYPE_OAUTH, 600, { redirect: this.request.referer }),
|
||
|
]);
|
||
|
this.response.redirect = `https://accounts.google.com/o/oauth2/v2/auth?client_id=${appid}&response_type=code&redirect_uri=${url}oauth/google/callback&scope=https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile&state=${state}`;
|
||
|
}
|
||
|
|
||
4 years ago
|
async get({ type }) {
|
||
4 years ago
|
if (type === 'github') await this.github();
|
||
|
else if (type === 'google') await this.google();
|
||
4 years ago
|
}
|
||
|
}
|
||
|
|
||
|
class OauthCallbackHandler extends Handler {
|
||
4 years ago
|
async github({ state, code }) {
|
||
4 years ago
|
const [appid, secret, url, proxy, s] = await Promise.all([
|
||
4 years ago
|
system.get('oauth.githubappid'),
|
||
|
system.get('oauth.githubsecret'),
|
||
|
system.get('server.url'),
|
||
4 years ago
|
system.get('proxy'),
|
||
4 years ago
|
token.get(state, token.TYPE_OAUTH),
|
||
|
]);
|
||
|
const res = await superagent.post('https://github.com/login/oauth/access_token')
|
||
4 years ago
|
.proxy(proxy)
|
||
4 years ago
|
.send({
|
||
4 years ago
|
client_id: appid,
|
||
|
client_secret: secret,
|
||
|
code,
|
||
|
redirect_uri: `${url}oauth/github/callback`,
|
||
|
state,
|
||
4 years ago
|
})
|
||
|
.set('accept', 'application/json');
|
||
|
if (res.body.error) {
|
||
|
throw new UserFacingError(
|
||
|
res.body.error, res.body.error_description, res.body.error_uri,
|
||
|
);
|
||
|
}
|
||
|
const t = res.body.access_token;
|
||
|
const userInfo = await superagent.get('https://api.github.com/user')
|
||
4 years ago
|
.proxy(proxy)
|
||
|
.set('User-Agent', 'Hydro-OAuth')
|
||
4 years ago
|
.set('Authorization', `token ${t}`);
|
||
|
const ret = {
|
||
4 years ago
|
email: userInfo.body.email,
|
||
4 years ago
|
bio: userInfo.body.bio,
|
||
|
uname: [userInfo.body.name, userInfo.body.login],
|
||
|
};
|
||
|
this.response.redirect = s.redirect;
|
||
|
await token.del(s, token.TYPE_OAUTH);
|
||
|
return ret;
|
||
|
}
|
||
|
|
||
|
async google({
|
||
4 years ago
|
code, error, state,
|
||
4 years ago
|
}) {
|
||
|
if (error) throw new UserFacingError(error);
|
||
|
const [
|
||
|
[appid, secret, url, proxy],
|
||
|
s,
|
||
|
] = await Promise.all([
|
||
|
system.getMany([
|
||
|
'oauth.googleappid', 'oauth.googlesecret', 'server.url', 'proxy',
|
||
|
]),
|
||
|
token.get(state, token.TYPE_OAUTH),
|
||
|
]);
|
||
|
const res = await superagent.post('https://oauth2.googleapis.com/token')
|
||
|
.proxy(proxy)
|
||
|
.send({
|
||
|
client_id: appid,
|
||
|
client_secret: secret,
|
||
|
code,
|
||
|
grant_type: 'authorization_code',
|
||
|
redirect_uri: `${url}oauth/google/callback`,
|
||
4 years ago
|
});
|
||
4 years ago
|
const payload = global.Hydro.lib.jwt.decode(res.body.id_token);
|
||
|
await token.del(state, token.TYPE_OAUTH);
|
||
|
this.response.redirect = s.redirect;
|
||
|
return {
|
||
|
email: payload.email,
|
||
|
uname: [payload.given_name, payload.name, payload.family_name],
|
||
|
viewLang: payload.locale.replace('-', '_'),
|
||
|
};
|
||
|
}
|
||
|
|
||
|
async get(args) {
|
||
|
let r;
|
||
|
if (args.type === 'github') r = await this.github(args);
|
||
|
else if (args.type === 'google') r = await this.google(args);
|
||
|
else throw new UserFacingError('Oauth type');
|
||
|
const udoc = await user.getByEmail('system', r.email, true);
|
||
|
if (udoc) {
|
||
|
this.session.uid = udoc._id;
|
||
|
} else {
|
||
4 years ago
|
this.checkPriv(PRIV.PRIV_REGISTER_USER);
|
||
4 years ago
|
let username = '';
|
||
|
r.uname = r.uname || [];
|
||
|
r.uname.push(String.random(16));
|
||
|
for (const uname of r.uname) {
|
||
|
// eslint-disable-next-line no-await-in-loop
|
||
|
const nudoc = await user.getByUname('system', uname, true);
|
||
|
if (!nudoc) {
|
||
|
username = uname;
|
||
|
break;
|
||
4 years ago
|
}
|
||
|
}
|
||
4 years ago
|
const uid = await user.create({
|
||
|
mail: r.email, uname: username, password: String.random(32), regip: this.request.ip,
|
||
|
});
|
||
4 years ago
|
const $set: any = {
|
||
4 years ago
|
oauth: args.type,
|
||
|
};
|
||
|
if (r.bio) $set.bio = r.bio;
|
||
|
if (r.viewLang) $set.viewLang = r.viewLang;
|
||
|
await user.setById(uid, $set);
|
||
|
this.session.uid = uid;
|
||
4 years ago
|
}
|
||
|
}
|
||
|
}
|
||
|
|
||
4 years ago
|
export async function apply() {
|
||
4 years ago
|
Route('user_login', '/login', UserLoginHandler);
|
||
4 years ago
|
Route('user_oauth', '/oauth/:type', OauthHandler);
|
||
|
Route('user_oauth_callback', '/oauth/:type/callback', OauthCallbackHandler);
|
||
4 years ago
|
Route('user_register', '/register', UserRegisterHandler, PRIV.PRIV_REGISTER_USER);
|
||
|
Route('user_register_with_code', '/register/:code', UserRegisterWithCodeHandler, PRIV.PRIV_REGISTER_USER);
|
||
|
Route('user_logout', '/logout', UserLogoutHandler, PRIV.PRIV_USER_PROFILE);
|
||
4 years ago
|
Route('user_lostpass', '/lostpass', UserLostPassHandler);
|
||
|
Route('user_lostpass_with_code', '/lostpass/:code', UserLostPassWithCodeHandler);
|
||
|
Route('user_search', '/user/search', UserSearchHandler);
|
||
4 years ago
|
Route('user_delete', '/user/delete', UserDeleteHandler, PRIV.PRIV_USER_PROFILE);
|
||
4 years ago
|
Route('user_detail', '/user/:uid', UserDetailHandler);
|
||
5 years ago
|
}
|
||
|
|
||
4 years ago
|
global.Hydro.handler.user = apply;
|