2026-04-12 08:58:41 +01:00
|
|
|
import { Context, Next } from 'hono';
|
|
|
|
|
|
|
|
|
|
import { ErrorCodes } from '@api/utils/errors';
|
2026-07-02 12:10:31 +01:00
|
|
|
import { isOrgAdminByCohortId, isCohortMember } from '@cio/db/queries/cohort';
|
2026-04-12 08:58:41 +01:00
|
|
|
|
|
|
|
|
/**
|
2026-07-02 12:10:31 +01:00
|
|
|
* Middleware to check if the authenticated user is a member of the cohort
|
|
|
|
|
* or an org admin for the cohort's organization.
|
2026-04-12 08:58:41 +01:00
|
|
|
*/
|
2026-07-02 12:10:31 +01:00
|
|
|
export const cohortMemberMiddleware = async (c: Context, next: Next) => {
|
2026-04-12 08:58:41 +01:00
|
|
|
try {
|
|
|
|
|
const user = c.get('user');
|
|
|
|
|
if (!user) {
|
|
|
|
|
return c.json(
|
|
|
|
|
{
|
|
|
|
|
success: false,
|
|
|
|
|
error: 'Unauthorized',
|
|
|
|
|
code: 'UNAUTHORIZED'
|
|
|
|
|
},
|
|
|
|
|
401
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-02 12:10:31 +01:00
|
|
|
const cohortId = c.req.param('cohortId');
|
|
|
|
|
if (!cohortId) {
|
2026-04-12 08:58:41 +01:00
|
|
|
return c.json(
|
|
|
|
|
{
|
|
|
|
|
success: false,
|
2026-07-13 02:09:57 +01:00
|
|
|
error: 'Cohort ID is required',
|
2026-07-02 12:10:31 +01:00
|
|
|
code: 'COHORT_ID_REQUIRED'
|
2026-04-12 08:58:41 +01:00
|
|
|
},
|
|
|
|
|
400
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const [member, isOrgAdmin] = await Promise.all([
|
2026-07-02 12:10:31 +01:00
|
|
|
isCohortMember(cohortId, user.id),
|
|
|
|
|
isOrgAdminByCohortId(cohortId, user.id)
|
2026-04-12 08:58:41 +01:00
|
|
|
]);
|
|
|
|
|
|
|
|
|
|
if (member || isOrgAdmin) {
|
|
|
|
|
return next();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return c.json(
|
|
|
|
|
{
|
|
|
|
|
success: false,
|
2026-07-02 12:10:31 +01:00
|
|
|
error: 'You must be a member of this cohort to perform this action',
|
|
|
|
|
code: ErrorCodes.COHORT_FORBIDDEN
|
2026-04-12 08:58:41 +01:00
|
|
|
},
|
|
|
|
|
403
|
|
|
|
|
);
|
|
|
|
|
} catch (error) {
|
2026-07-02 12:10:31 +01:00
|
|
|
console.error('Error in cohortMemberMiddleware:', error);
|
2026-04-12 08:58:41 +01:00
|
|
|
return c.json(
|
|
|
|
|
{
|
|
|
|
|
success: false,
|
2026-07-02 12:10:31 +01:00
|
|
|
error: 'Failed to verify cohort membership',
|
|
|
|
|
code: ErrorCodes.COHORT_MEMBER_CHECK_FAILED
|
2026-04-12 08:58:41 +01:00
|
|
|
},
|
|
|
|
|
500
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
};
|