You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
63 lines
2.1 KiB
63 lines
2.1 KiB
import log4js from "logger";
|
|
import { getUserFromEvent } from "#server/utils/jwt";
|
|
import { getCurrentUser } from "#server/service/auth";
|
|
import { setContextUser, getContextUser } from "#server/utils/context";
|
|
|
|
interface IConfig {
|
|
auth?: 'required' | 'public' | 'optional';
|
|
/** 允许的角色列表,不指定则不校验角色 */
|
|
role?: string | string[];
|
|
}
|
|
|
|
const defaultConfig: IConfig = {
|
|
auth: 'required',
|
|
}
|
|
|
|
const logger = log4js.getLogger("ERROR");
|
|
|
|
export const defineWrappedResponseHandler = <T extends EventHandlerRequest, D>(
|
|
handlerOrConfig?: EventHandler<T, D> | IConfig,
|
|
_handler?: EventHandler<T, D>,
|
|
): EventHandler<T, D> => {
|
|
const handler = typeof handlerOrConfig === 'function' ? handlerOrConfig : _handler;
|
|
if (!handler) {
|
|
throw new Error('handler or config is required');
|
|
}
|
|
const config = Object.assign({ ...defaultConfig }, typeof handlerOrConfig === 'object' ? handlerOrConfig : {});
|
|
|
|
return defineEventHandler<T>(async (event) => {
|
|
// ---- auth guard ----
|
|
if (config.auth !== 'public') {
|
|
const payload = getUserFromEvent(event);
|
|
if (config.auth === 'required' && !payload) {
|
|
return R.error("未登录", null);
|
|
}
|
|
if (payload) {
|
|
const user = await getCurrentUser(payload);
|
|
if (config.auth === 'required' && !user) {
|
|
return R.error("用户不存在", null);
|
|
}
|
|
if (user) {
|
|
setContextUser(event, user);
|
|
}
|
|
}
|
|
}
|
|
// ---- end auth guard ----
|
|
|
|
// ---- role guard ----
|
|
if (config.role) {
|
|
const user = getContextUser(event);
|
|
if (!user) {
|
|
return R.error("未登录", null);
|
|
}
|
|
const allowedRoles = Array.isArray(config.role) ? config.role : [config.role];
|
|
if (!allowedRoles.includes(user.role)) {
|
|
return R.error("无权限", null);
|
|
}
|
|
}
|
|
// ---- end role guard ----
|
|
|
|
const response = await handler(event)
|
|
return response
|
|
})
|
|
}
|
|
|