1
0
mirror of https://github.com/xuthus83/pigallery2.git synced 2024-11-03 21:04:03 +08:00
pigallery2/backend/middlewares/user/UserRequestConstrainsMWs.ts

57 lines
1.6 KiB
TypeScript
Raw Normal View History

2018-03-31 03:30:30 +08:00
import {NextFunction, Request, Response} from 'express';
import {ErrorCodes, ErrorDTO} from '../../../common/entities/Error';
import {UserRoles} from '../../../common/entities/UserDTO';
import {ObjectManagerRepository} from '../../model/ObjectManagerRepository';
export class UserRequestConstrainsMWs {
2017-07-04 01:17:49 +08:00
public static forceSelfRequest(req: Request, res: Response, next: NextFunction) {
if ((typeof req.params === 'undefined') || (typeof req.params.id === 'undefined')) {
return next();
}
2017-07-04 01:17:49 +08:00
if (req.session.user.id !== req.params.id) {
2017-07-15 18:47:11 +08:00
return next(new ErrorDTO(ErrorCodes.NOT_AUTHORISED));
2017-07-04 01:17:49 +08:00
}
return next();
}
2017-07-04 01:17:49 +08:00
public static notSelfRequest(req: Request, res: Response, next: NextFunction) {
if ((typeof req.params === 'undefined') || (typeof req.params.id === 'undefined')) {
return next();
}
if (req.session.user.id === req.params.id) {
2017-07-15 18:47:11 +08:00
return next(new ErrorDTO(ErrorCodes.NOT_AUTHORISED));
2017-07-04 01:17:49 +08:00
}
2016-05-09 23:04:56 +08:00
2017-07-04 01:17:49 +08:00
return next();
}
2017-07-04 01:17:49 +08:00
public static async notSelfRequestOr2Admins(req: Request, res: Response, next: NextFunction) {
if ((typeof req.params === 'undefined') || (typeof req.params.id === 'undefined')) {
return next();
}
2016-05-09 23:04:56 +08:00
2017-07-04 01:17:49 +08:00
if (req.session.user.id !== req.params.id) {
return next();
}
2018-03-31 03:30:30 +08:00
// TODO: fix it!
2017-07-04 01:17:49 +08:00
try {
const result = await ObjectManagerRepository.getInstance().UserManager.find({minRole: UserRoles.Admin});
if (result.length <= 1) {
2017-07-15 18:47:11 +08:00
return next(new ErrorDTO(ErrorCodes.GENERAL_ERROR));
2017-07-04 01:17:49 +08:00
}
return next();
} catch (err) {
2017-07-15 18:47:11 +08:00
return next(new ErrorDTO(ErrorCodes.GENERAL_ERROR));
2017-07-04 01:17:49 +08:00
}
}
2017-07-04 01:17:49 +08:00
}