impr: optimize permissions middleware (@fehmer) (#5801)

This commit is contained in:
Christian Fehmer 2024-08-20 14:52:30 +02:00 committed by GitHub
parent bb01dbef25
commit 4466acd6bc
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
5 changed files with 14 additions and 9 deletions

View file

@ -11,7 +11,7 @@ const configuration = Configuration.getCachedConfiguration();
const uid = new ObjectId().toHexString();
describe("ApeKeyController", () => {
const getUserMock = vi.spyOn(UserDal, "getUser");
const getUserMock = vi.spyOn(UserDal, "getPartialUser");
beforeEach(async () => {
await enableApeKeysEndpoints(true);

View file

@ -13,7 +13,7 @@ const commonMiddleware = [
},
invalidMessage: "ApeKeys are currently disabled.",
}),
checkUserPermissions({
checkUserPermissions(["canManageApeKeys"], {
criteria: (user) => {
return user.canManageApeKeys ?? true;
},

View file

@ -10,7 +10,7 @@ import { validateRequest } from "../../middlewares/validation";
const router = Router();
const checkIfUserIsQuoteMod = checkUserPermissions({
const checkIfUserIsQuoteMod = checkUserPermissions(["quoteMod"], {
criteria: (user) => {
return (
user.quoteMod === true ||
@ -171,7 +171,7 @@ router.post(
captcha: withCustomMessages.regex(/[\w-_]+/).required(),
},
}),
checkUserPermissions({
checkUserPermissions(["canReport"], {
criteria: (user) => {
return user.canReport !== false;
},

View file

@ -638,7 +638,7 @@ router.post(
captcha: withCustomMessages.regex(/[\w-_]+/).required(),
},
}),
checkUserPermissions({
checkUserPermissions(["canReport"], {
criteria: (user) => {
return user.canReport !== false;
},

View file

@ -1,7 +1,7 @@
import _ from "lodash";
import MonkeyError from "../utils/error";
import type { Response, NextFunction, RequestHandler } from "express";
import { getUser } from "../dal/user";
import { getPartialUser } from "../dal/user";
import { isAdmin } from "../dal/admin-uids";
import type { ValidationOptions } from "./configuration";
@ -34,8 +34,9 @@ export function checkIfUserIsAdmin(): RequestHandler {
* Check user permissions before handling request.
* Note that this middleware must be used after authentication in the middleware stack.
*/
export function checkUserPermissions(
options: ValidationOptions<MonkeyTypes.DBUser>
export function checkUserPermissions<K extends keyof MonkeyTypes.DBUser>(
fields: K[],
options: ValidationOptions<Pick<MonkeyTypes.DBUser, K>>
): RequestHandler {
const { criteria, invalidMessage = "You don't have permission to do this." } =
options;
@ -48,7 +49,11 @@ export function checkUserPermissions(
try {
const { uid } = req.ctx.decodedToken;
const userData = await getUser(uid, "check user permissions");
const userData = await getPartialUser(
uid,
"check user permissions",
fields
);
const hasPermission = criteria(userData);
if (!hasPermission) {