在我的SvelteKit应用程序中,我有很多端点需要保护。我不想在所有这些中添加以下内容:
if (!request.locals.user) {
return { status: 401 };
};我可以从hooks.js或以另一种简单而安全的方式来完成这个任务吗?
发布于 2021-12-13 14:36:54
目前,没有办法在sveltekit中添加每个端点的钩子,在全局hooks.js中实现它将很困难,因为每次更改它时都必须维护受保护的路由路径。
正如你说的那样,唯一的方法就是在每条路线中增加自动检查,这也是很难维护的。为了避免这种情况,我们可以将auth检查逻辑提取到它自己的函数中。该函数将接受保存路由钩子的处理程序:
// 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}`
};
});https://stackoverflow.com/questions/70303665
复制相似问题