api-v1: add new middleware function

This commit is contained in:
May 2023-10-04 10:21:04 -07:00 committed by GitHub
parent ab617461fa
commit 01fe79d050
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -1,4 +1,4 @@
import * as Accounts from "./accounts";
import { Account } from "./accounts";
import express, { type RequestHandler } from "express"
import ServeError from "../lib/errors";
import * as auth from "./auth";
@ -70,4 +70,17 @@ export const requiresPermissions = function(...tokenPermissions: auth.TokenPermi
export const noAPIAccess: RequestHandler = function(req, res, next) {
if (auth.getType(auth.tokenFor(req)) == "App") ServeError(res, 403, "apps are not allowed to access this endpoint")
else next()
}
/**
* @description Blocks requests based on whether or not the token being used to access the route is of type `User` unless a condition is met.
* @param tokenPermissions Permissions which your route requires.
* @returns Express middleware
*/
export const noAPIAccessIf = function(condition: (acc:Account, token:string) => boolean):RequestHandler {
return function(req, res, next) {
let reqToken = auth.tokenFor(req)
if (auth.getType(reqToken) == "App" && !condition(res.locals.acc, reqToken)) ServeError(res, 403, "apps are not allowed to access this endpoint")
else next()
}
}}