mirror of
https://github.com/versia-pub/server.git
synced 2026-03-13 05:49:16 +01:00
feat(api): ✨ Add permissions to every route and permission config
This commit is contained in:
parent
19823d8eca
commit
4902f078a8
79 changed files with 729 additions and 251 deletions
35
utils/api.ts
35
utils/api.ts
|
|
@ -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,
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue