有保护所有端点的简单方法吗?

Is there an easy way to protect all endpoints?

我的 SvelteKit 应用程序中有大量端点需要保护。我不想在所有这些中添加以下内容:

    if (!request.locals.user) {
        return { status: 401 };
    };

我可以从 hooks.js 或其他简单安全的方式执行此操作吗?

目前无法在 sveltekit 中为每个端点添加挂钩,并且在全局中实现它会很困难 hooks.js 因为每次更改它时都必须维护受保护的路由路径。

按照您所说的唯一方法是在每条路由中添加身份验证检查,这也将难以维护。为了避免这种情况,我们可以将身份验证检查逻辑提取到它自己的函数中。该函数将接受持有路由挂钩的处理程序:

// compose one handler function out of number of handlers.
// it will execute handlers in sequence until one returned a value
function withHandlers(...handlers) {
    return async (request) => {
        for (const handle of handlers) {
            const result = await handle(request)
            if (result !== undefined) {
                return result
            }
        }
    }
}

// implementation of auth check
function authHook(request) {
    if (!request.locals.user) {
        return {
            status: 401,
            body: {
                message: 'unauthorized'
            }
        };
    }
}

// create a new handler with auth check
function withAuth(handle) {
    return withHandlers(authHook, handle);
}

// your final endpoint with authentication check
export const get = withAuth((request) => {
    return {
        body: `Hello ${request.locals.user}`
    };
});