Refactor required route role

This commit is contained in:
Tom Moor
2024-04-06 21:43:15 -04:00
parent 79899d051c
commit b458bb3af9
8 changed files with 37 additions and 40 deletions

View File

@@ -1,4 +1,7 @@
import { Next } from "koa";
import capitalize from "lodash/capitalize";
import { UserRole } from "@shared/types";
import { UserRoleHelper } from "@shared/utils/UserRoleHelper";
import Logger from "@server/logging/Logger";
import tracer, {
addTags,
@@ -14,10 +17,8 @@ import {
} from "../errors";
type AuthenticationOptions = {
/** An admin user role is required to access the route. */
admin?: boolean;
/** A member or admin user role is required to access the route. */
member?: boolean;
/** Role requuired to access the route. */
role?: UserRole;
/** Authentication is parsed, but optional. */
optional?: boolean;
};
@@ -110,16 +111,8 @@ export default function auth(options: AuthenticationOptions = {}) {
});
}
if (options.admin) {
if (!user.isAdmin) {
throw AuthorizationError("Admin role required");
}
}
if (options.member) {
if (user.isViewer) {
throw AuthorizationError("Member role required");
}
if (options.role && UserRoleHelper.isRoleLower(user.role, options.role)) {
throw AuthorizationError(`${capitalize(options.role)} role required`);
}
// not awaiting the promises here so that the request is not blocked