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