feat(api): Add permissions to every route and permission config

This commit is contained in:
Jesse Wierzbinski 2024-06-07 18:57:29 -10:00
parent 19823d8eca
commit 4902f078a8
No known key found for this signature in database
79 changed files with 729 additions and 251 deletions

View file

@ -101,7 +101,10 @@ export const handleZodError = (
}
};
export const auth = (authData: APIRouteMetadata["auth"]) =>
export const auth = (
authData: APIRouteMetadata["auth"],
permissionData?: APIRouteMetadata["permissions"],
) =>
validator("header", async (value, context) => {
const auth = value.authorization
? await getFromHeader(value.authorization)
@ -109,6 +112,34 @@ export const auth = (authData: APIRouteMetadata["auth"]) =>
const error = errorResponse("Unauthorized", 401);
// Permissions check
if (permissionData) {
const userPerms = auth?.user
? auth.user.getAllPermissions()
: config.permissions.anonymous;
const requiredPerms =
permissionData.methodOverrides?.[
context.req.method as HttpVerb
] ?? permissionData.required;
if (!requiredPerms.every((perm) => userPerms.includes(perm))) {
const missingPerms = requiredPerms.filter(
(perm) => !userPerms.includes(perm),
);
return context.json(
{
error: `You do not have the required permissions to access this route. Missing: ${missingPerms.join(
", ",
)}`,
},
403,
error.headers.toJSON(),
);
}
}
if (!auth?.user) {
if (authData.required) {
return context.json(
@ -133,6 +164,8 @@ export const auth = (authData: APIRouteMetadata["auth"]) =>
error.headers.toJSON(),
);
}
// Check role permissions
} else {
return {
user: auth.user as User,