Refactor required route role
This commit is contained in:
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user