import { ACCOUNT_TYPE, Account } from './model.mjs'; /** @typedef {import('koa').Context} Context */ /** @typedef {import('koa').Next} Next */ /** * Middleware function to load user account information if user is logged in and account data is not yet loaded. * @param {Context} ctx - Koa context object. * @param {Next} next - Next middleware function. */ export async function loadAccount(ctx, next) { if (ctx.state.user != null && ctx.state.user.auth_step == 'done' && ctx.state.account == null) { ctx.state.account = await Account.findByPk(ctx.state.user.uid); } await next(); } /** * Middleware function to check if the user has admin privileges. * @param {Context} ctx - Koa context object. * @param {Next} next - Next middleware function. */ export async function adminRequired(ctx, next) { /** @type {?Account} */ const account = ctx.state.account; if (account != null && (account.type == ACCOUNT_TYPE.admin || account.type == ACCOUNT_TYPE.superuser)) { await next(); } else { ctx.status = 403; // 403 (Forbidden) ctx.body = { error: 'You must be an administrator to access this resource.', errno: 'EPERM' }; } }