Service account checkpoint

This commit is contained in:
Tuan Dang
2023-03-19 17:01:36 +07:00
parent 8fb473c57c
commit 3a0ce7c084
15 changed files with 356 additions and 136 deletions
@@ -1,6 +1,8 @@
import { Request, Response, NextFunction } from 'express';
import { Types } from 'mongoose';
import { IOrganization, MembershipOrg } from '../models';
import { UnauthorizedRequestError, ValidationError } from '../utils/errors';
import { validateMembershipOrg } from '../helpers/membershipOrg';
type req = 'params' | 'body' | 'query';
@@ -9,7 +11,7 @@ type req = 'params' | 'body' | 'query';
* on request params.
* @param {Object} obj
* @param {String[]} obj.acceptedRoles - accepted organization roles
* @param {String[]} obj.acceptedStatuses - accepted organization statuses
* @param {String[]} obj.accepteStatuses - accepted organization statuses
*/
const requireOrganizationAuth = ({
acceptedRoles,
@@ -21,30 +23,13 @@ const requireOrganizationAuth = ({
location?: req;
}) => {
return async (req: Request, res: Response, next: NextFunction) => {
// organization authorization middleware
const { organizationId } = req[location];
// validate organization membership
const membershipOrg = await MembershipOrg.findOne({
user: req.user._id,
organization: organizationId
}).populate<{ organization: IOrganization }>('organization');
if (!membershipOrg) {
return next(UnauthorizedRequestError({message: "You're not a member of this Organization."}))
}
//TODO is this important to validate? I mean is it possible to save wrong role to database or get wrong role from databse? - Zamion101
if (!acceptedRoles.includes(membershipOrg.role)) {
return next(ValidationError({message: 'Failed to validate Organization Membership Role'}))
}
if (!acceptedStatuses.includes(membershipOrg.status)) {
return next(ValidationError({message: 'Failed to validate Organization Membership Status'}))
}
req.membershipOrg = membershipOrg;
req.membershipOrg = await validateMembershipOrg({
userId: req.user._id,
organizationId: new Types.ObjectId(organizationId),
acceptedRoles,
acceptedStatuses
});
return next();
};