33 lines
1003 B
JavaScript
33 lines
1003 B
JavaScript
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.account == null) {
|
|
ctx.state.account = await Account.load(ctx.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)
|
|
}
|
|
}
|