Files
NodeBB/src/controllers/helpers.js
Barış Soner Uşaklı 7ba70d1561 Bootstrap5 (#10894)
* chore: up deps

* chore: up composer

* fix(deps): bump 2factor to v7

* chore: up harmony

* chore: up harmony

* fix: missing await

* feat: allow middlewares to pass in template values via res.locals

* feat: buildAccountData middleware automatically added ot all account routes

* fix: properly allow values in res.locals.templateValues to be added to the template data

* refactor: user/blocks

* refactor(accounts): categories and consent

* feat: automatically 404 if exposeUid or exposeGroupName come up empty

* refactor: remove calls to getUserDataByUserSlug for most account routes, since it is populated via middleware now

* fix: allow exposeUid and exposeGroupName to work with slugs with mixed capitalization

* fix: move reputation removal check to accountHelpers method

* test: skip i18n tests if ref branch when present is not develop

* fix(deps): bump theme versions

* fix(deps): bump ntfy and 2factor

* chore: up harmony

* fix: add missing return

* fix: #11191, only focus on search input on md environments and up

* feat: allow file uploads on mobile chat

closes https://github.com/NodeBB/NodeBB/issues/11217

* chore: up themes

* chore: add lang string

* fix(deps): bump ntfy to 1.0.15

* refactor: use new if/each syntax

* chore: up composer

* fix: regression from user helper refactor

* chore: up harmony

* chore: up composer

* chore: up harmony

* chore: up harmony

* chore: up harmony

* chore: fix composer version

* feat: add increment helper

* chore: up harmony

* fix: #11228 no timestamps in future 

* chore: up harmony

* check config.theme as well

fire action:posts.loaded after processing dom

* chore: up harmony

* chore: up harmony

* chore: up harmony

* chore: up themes

* chore: up harmony

* remove extra class

* refactor: move these to core from harmony

* chore: up widgets

* chore: up widgets

* height auto

* fix: closes #11238

* dont focus inputs, annoying on mobile

* fix: dont focus twice, only focus on chat input on desktop

dont wrap widget footer in row

* chore: up harmony

* chore: up harmony

* update chat window

* chore: up themes

* fix cache buster for skins

* chat fixes

* chore: up harmony

* chore: up composer

* refactor: change hook logs to debug

* fix: scroll to post right after adding to dom

* fix: hash scrolling and highlighting correct post

* test: re-enable read API schema tests

* fix: add back schema changes for 179faa2270 and c3920ccb10

* fix: schema changes from 488f0978a4

* fix: schema changes for f4cf482a87

* fix: schema update for be6bbabd0e

* fix: schema changes for 69c96078ea

* fix: schema changes for d1364c3130

* fix: schema changes for 84ff1152f7

* fix: schema changes for b860c2605c

* fix: schema changes for 23cb67a112

* fix: schema changes for b916e42f40

* fix: schema change for a9bbb586fc

* fix: schema changes for 4b738c8cd3

* fix: schema changes for 58b5781cea

* fix: schema changes for 794bf01b21

* fix: schema changes for 80ea12c1c1, e368feef51, and 52ead114be

* fix: composer-default object in config?

* fix: schema changes for 9acdc6808c and 0930934200

* fix: schema changes for c0a52924f1

* fix: schema change for aba420a3f3, move loggedInUser to optional props

* fix: schema changes for 8c67031609

* fix: schema changes for 27e53b42f3

* fix: schema changes for 2835966518

* fix: breaking test for email confirmation API call

* fix: schema changes for refactored search page

* fix: schema changes for user object

* fix: schema changes for 9f531f957e

* fix: schema changes for c4042c70de and 23175110a2

* fix: schema changes for 9b3616b103

* fix: schema changes for 5afd5de07d

* fix: schema change for 1d7baf1217

* fix: schema changes for 57bfb37c55 and be6bbabd0e

* fix: schema changes for 6e86b4afa2 and 3efad2e13b and 68f66223e7

* fix: allowing optional qs prop in pagination keys (not sure why this didn't break before)

* fix: re-login on email change

* fix: schema changes for c926358d73

* fix: schema changes for 388a8270c9

* fix: schema change for 2658bcc821

* fix: no need to call account middlewares for chats routes

* fix: schema changes for 71743affc3

* fix: final schema changes

* test: support for anyOf and oneOf

* fix: check thumb

* dont scroll to top on back press

* remove group log

* fix: add top margin to merged and deleted alerts

* chore: up widgets

* fix: improve fix-lists mixin

* chore: up harmony/composer

* feat: allow hiding quicksearch results during search

* dont record searches made by composer

* chore: up 54

* chore: up spam be gone

* feat: add prev/next page and page count into mobile paginator

* chore: up harmony

* chore: up harmony

* use old style for IS

* fix: hide entire toolbar row if no posts or not singlePost

* fix: updated messaging for post-queue template, #11206

* fix: btn-sm on post queue back button

* fix: bump harmony, closes #11206

* fix: remove unused alert module import

* fix: bump harmony

* fix: bump harmony

* chore: up harmony

* refactor: IS scrolltop

* fix: update users:search-user-for-chat source string

* feat: support for mark-read toggle on chats dropdown and recent chats list

* feat: api v3 calls to mark chat read/unread

* feat: send event:chats.mark socket event on mark read or unread

* refactor: allow frontend to mark chats as unread, use new API v3 routes instead of socket calls, better frontend event handling

* docs: openapi schema updates for chat marking

* fix: allow unread state toggling in chats dropdown too

* fix: issue where repeated openings of the chats dropdown would continually add events for mark-read/unread

* fix: debug log

* refactor: move userSearch filter to a module

* feat(routes): allow remounting /categories (#11230)

* feat: send flags count to frontend on flags list page

* refactor: filter form client-side js to extract out some logic

* fix: applyFilters to not take any arguments, update selectedCids in updateButton instead of onHidden

* fix: use userFilter module for assignee, reporterId, targetUid

* fix(openapi): schema changes for updated flags page

* fix: dont allow adding duplicates to userFilter

* use same var

* remove log

* fix: closes #11282

* feat: lang key for x-topics

* chore: up harmony

* chore: up emoji

* chore: up harmony

* fix: update userFilter to allow new option `selectedBlock`

* fix: wrong block name passed to userFilter

* fix: https://github.com/NodeBB/NodeBB/issues/11283

* fix: chats, allow multiple dropdowns like in harmony

* chore: up harmony

* refactor: flag note adding/editing, closes #11285

* fix: remove old prepareEdit logic

* chore: add caveat about hacky code block in userFilter module

* fix: placeholders for userFilter module

* refactor: navigator so it works with multiple thumbs/navigators

* chore: up harmony

* fix: closes #11287, destroy quick reply autocomplete

on navigation

* fix: filter disabled categories on user categories page count

* chore: up harmony

* docs: update openapi spec to include info about passing in timestamps for topic creation, removing timestamp as valid request param for topic replying

* fix: send back null values on ACP search dashboard for startDate and endDate if not expicitly passed in, fix tests

* fix: tweak table order in ACP dash searches

* fix: only invoke navigator click drag on left mouse button

* feat: add back unread indicator to navigator

* clear bookmark on mark unread

* fix: navigator crash on ajaxify

* better thumb top calculation

* fix: reset user bookmark when topic is marked unread

* Revert "fix: reset user bookmark when topic is marked unread"

This reverts commit 9bcd85c2c6.

* fix: update unread indicator on scroll, add unread count

* chore: bump harmony

* fix: crash on navigator unread update when backing out of a topic

* fix: closes #11183

* fix: update topics:recent zset when rescheduling a topic

* fix: dupe quote button, increase delay, hide immediately on empty selection

* fix: navigator not showing up on first load

* refactor: remove glance

assorted fixes to navigator
dont reduce remaning count if user scrolls down and up quickly
only call topic.navigatorCallback when index changes

* more sanity checks for bookmark

dont allow setting bookmark higher than topic postcount

* closes #11218, 🚋

* Revert "fix: update topics:recent zset when rescheduling a topic"

This reverts commit 737973cca9.

* fix: #11306, show proper error if queued post doesn't exist

was showing no-privileges if someone else accepted the post

* https://github.com/NodeBB/NodeBB/issues/11307

dont use li

* chore: up harmony

* chore: bump version string

* fix: copy paste fail

* feat: closes #7382, tag filtering

add client side support for filtering by tags on /category, /recent and /unread

* chore: up harmony

* chore: up harmony

* Revert "fix: add back req.query fallback for backwards compatibility" [breaking]

This reverts commit cf6cc2c454.
This commit is no longer required as passing in a CSRF token via query parameter is no longer supported as of NodeBB v3.x

This is a breaking change.

* fix: pass csrf token in form data, re: NodeBB/NodeBB#11309

* chore: up deps

* fix: tests, use x-csrf-token query param removed

* test: fix csrf_token

* lint: remove unused

* feat: add itemprop="image" to avatar helper

* fix: get chat upload button in chat modal

* breaking: remove deprecated socket.io methods

* test: update messaging tests to not use sockets

* fix: parent post links

* fix: prevent post tooltip if mouse leaves before data/tpl is loaded

* chore: up harmony

* chore: up harmony

* chore: up harmony

* chore: up harmony

* fix: nested replies indices

* fix(deps): bump 2factor

* feat: add loggedIn user to all api routes

* chore: up themes

* refactor: audit admin v3 write api routes as per #11321

* refactor: audit category v3 write api routes as per #11321 [breaking]

docs: fix open api spec for #11321

* refactor: audit chat v3 write api routes as per #11321

* refactor: audit files v3 write api routes as per #11321

* refactor: audit flags v3 write api routes as per #11321

* refactor: audit posts v3 write api routes as per #11321

* refactor: audit topics v3 write api routes as per #11321

* refactor: audit users v3 write api routes as per #11321

* fix: lang string

* remove min height

* fix: empty topic/labels taking up space

* fix: tag filtering when changing filter to watched topics

or changing popular time limit to month

* chore: up harmony

* fix: closes #11354, show no post error if queued post already accepted/rejected

* test: #11354

* test: #11354

* fix(deps): bump 2factor

* fix: #11357 clear cache on thumb remove

* fix: thumb remove on windows, closes #11357

* test: openapi for thumbs

* test: fix openapi

---------

Co-authored-by: Julian Lam <julian@nodebb.org>
Co-authored-by: Opliko <opliko.reg@protonmail.com>
2023-03-17 11:58:31 -04:00

600 lines
16 KiB
JavaScript

'use strict';
const nconf = require('nconf');
const validator = require('validator');
const querystring = require('querystring');
const _ = require('lodash');
const chalk = require('chalk');
const translator = require('../translator');
const user = require('../user');
const privileges = require('../privileges');
const categories = require('../categories');
const plugins = require('../plugins');
const meta = require('../meta');
const middlewareHelpers = require('../middleware/helpers');
const utils = require('../utils');
const helpers = module.exports;
const relative_path = nconf.get('relative_path');
const url = nconf.get('url');
helpers.noScriptErrors = async function (req, res, error, httpStatus) {
if (req.body.noscript !== 'true') {
if (typeof error === 'string') {
return res.status(httpStatus).send(error);
}
return res.status(httpStatus).json(error);
}
const middleware = require('../middleware');
const httpStatusString = httpStatus.toString();
await middleware.buildHeaderAsync(req, res);
res.status(httpStatus).render(httpStatusString, {
path: req.path,
loggedIn: req.loggedIn,
error: error,
returnLink: true,
title: `[[global:${httpStatusString}.title]]`,
});
};
helpers.terms = {
daily: 'day',
weekly: 'week',
monthly: 'month',
};
helpers.buildQueryString = function (query, key, value) {
const queryObj = { ...query };
if (value) {
queryObj[key] = value;
} else {
delete queryObj[key];
}
delete queryObj._;
return Object.keys(queryObj).length ? `?${querystring.stringify(queryObj)}` : '';
};
helpers.addLinkTags = function (params) {
params.res.locals.linkTags = params.res.locals.linkTags || [];
params.res.locals.linkTags.push({
rel: 'canonical',
href: `${url}/${params.url}`,
});
params.tags.forEach((rel) => {
rel.href = `${url}/${params.url}${rel.href}`;
params.res.locals.linkTags.push(rel);
});
};
helpers.buildFilters = function (url, filter, query) {
return [{
name: '[[unread:all-topics]]',
url: url + helpers.buildQueryString(query, 'filter', ''),
selected: filter === '',
filter: '',
icon: 'fa-book',
}, {
name: '[[unread:new-topics]]',
url: url + helpers.buildQueryString(query, 'filter', 'new'),
selected: filter === 'new',
filter: 'new',
icon: 'fa-clock-o',
}, {
name: '[[unread:watched-topics]]',
url: url + helpers.buildQueryString(query, 'filter', 'watched'),
selected: filter === 'watched',
filter: 'watched',
icon: 'fa-bell-o',
}, {
name: '[[unread:unreplied-topics]]',
url: url + helpers.buildQueryString(query, 'filter', 'unreplied'),
selected: filter === 'unreplied',
filter: 'unreplied',
icon: 'fa-reply',
}];
};
helpers.buildTerms = function (url, term, query) {
return [{
name: '[[recent:alltime]]',
url: url + helpers.buildQueryString(query, 'term', ''),
selected: term === 'alltime',
term: 'alltime',
}, {
name: '[[recent:day]]',
url: url + helpers.buildQueryString(query, 'term', 'daily'),
selected: term === 'day',
term: 'day',
}, {
name: '[[recent:week]]',
url: url + helpers.buildQueryString(query, 'term', 'weekly'),
selected: term === 'week',
term: 'week',
}, {
name: '[[recent:month]]',
url: url + helpers.buildQueryString(query, 'term', 'monthly'),
selected: term === 'month',
term: 'month',
}];
};
helpers.notAllowed = async function (req, res, error) {
({ error } = await plugins.hooks.fire('filter:helpers.notAllowed', { req, res, error }));
await plugins.hooks.fire('response:helpers.notAllowed', { req, res, error });
if (res.headersSent) {
return;
}
if (req.loggedIn || req.uid === -1) {
if (res.locals.isAPI) {
if (req.originalUrl.startsWith(`${relative_path}/api/v3`)) {
helpers.formatApiResponse(403, res, error);
} else {
res.status(403).json({
path: req.path.replace(/^\/api/, ''),
loggedIn: req.loggedIn,
error: error,
title: '[[global:403.title]]',
bodyClass: middlewareHelpers.buildBodyClass(req, res),
});
}
} else {
const middleware = require('../middleware');
await middleware.buildHeaderAsync(req, res);
res.status(403).render('403', {
path: req.path,
loggedIn: req.loggedIn,
error,
title: '[[global:403.title]]',
});
}
} else if (res.locals.isAPI) {
req.session.returnTo = req.url.replace(/^\/api/, '');
helpers.formatApiResponse(401, res, error);
} else {
req.session.returnTo = req.url;
res.redirect(`${relative_path}/login${req.path.startsWith('/admin') ? '?local=1' : ''}`);
}
};
helpers.redirect = function (res, url, permanent) {
// this is used by sso plugins to redirect to the auth route
// { external: '/auth/sso' } or { external: 'https://domain/auth/sso' }
if (url.hasOwnProperty('external')) {
const redirectUrl = encodeURI(prependRelativePath(url.external));
if (res.locals.isAPI) {
res.set('X-Redirect', redirectUrl).status(200).json({ external: redirectUrl });
} else {
res.redirect(permanent ? 308 : 307, redirectUrl);
}
return;
}
if (res.locals.isAPI) {
url = encodeURI(url);
res.set('X-Redirect', url).status(200).json(url);
} else {
res.redirect(permanent ? 308 : 307, encodeURI(prependRelativePath(url)));
}
};
function prependRelativePath(url) {
return url.startsWith('http://') || url.startsWith('https://') ?
url : relative_path + url;
}
helpers.buildCategoryBreadcrumbs = async function (cid) {
const breadcrumbs = [];
while (parseInt(cid, 10)) {
/* eslint-disable no-await-in-loop */
const data = await categories.getCategoryFields(cid, ['name', 'slug', 'parentCid', 'disabled', 'isSection']);
if (!data.disabled && !data.isSection) {
breadcrumbs.unshift({
text: String(data.name),
url: `${relative_path}/category/${data.slug}`,
cid: cid,
});
}
cid = data.parentCid;
}
if (meta.config.homePageRoute && meta.config.homePageRoute !== 'categories') {
breadcrumbs.unshift({
text: '[[global:header.categories]]',
url: `${relative_path}/categories`,
});
}
breadcrumbs.unshift({
text: '[[global:home]]',
url: `${relative_path}/`,
});
return breadcrumbs;
};
helpers.buildBreadcrumbs = function (crumbs) {
const breadcrumbs = [
{
text: '[[global:home]]',
url: `${relative_path}/`,
},
];
crumbs.forEach((crumb) => {
if (crumb) {
if (crumb.url) {
crumb.url = `${utils.isRelativeUrl(crumb.url) ? relative_path : ''}${crumb.url}`;
}
breadcrumbs.push(crumb);
}
});
return breadcrumbs;
};
helpers.buildTitle = function (pageTitle) {
const titleLayout = meta.config.titleLayout || '{pageTitle} | {browserTitle}';
const browserTitle = validator.escape(String(meta.config.browserTitle || meta.config.title || 'NodeBB'));
pageTitle = pageTitle || '';
const title = titleLayout.replace('{pageTitle}', () => pageTitle).replace('{browserTitle}', () => browserTitle);
return title;
};
helpers.getCategories = async function (set, uid, privilege, selectedCid) {
const cids = await categories.getCidsByPrivilege(set, uid, privilege);
return await getCategoryData(cids, uid, selectedCid, Object.values(categories.watchStates), privilege);
};
helpers.getCategoriesByStates = async function (uid, selectedCid, states, privilege = 'topics:read') {
const cids = await categories.getAllCidsFromSet('categories:cid');
return await getCategoryData(cids, uid, selectedCid, states, privilege);
};
async function getCategoryData(cids, uid, selectedCid, states, privilege) {
const [visibleCategories, selectData] = await Promise.all([
helpers.getVisibleCategories({
cids, uid, states, privilege, showLinks: false,
}),
helpers.getSelectedCategory(selectedCid),
]);
const categoriesData = categories.buildForSelectCategories(visibleCategories, ['disabledClass']);
categoriesData.forEach((category) => {
category.selected = selectData.selectedCids.includes(category.cid);
});
selectData.selectedCids.sort((a, b) => a - b);
return {
categories: categoriesData,
selectedCategory: selectData.selectedCategory,
selectedCids: selectData.selectedCids,
};
}
helpers.getVisibleCategories = async function (params) {
const { cids, uid, privilege } = params;
const states = params.states || [categories.watchStates.watching, categories.watchStates.notwatching];
const showLinks = !!params.showLinks;
let [allowed, watchState, categoriesData, isAdmin, isModerator] = await Promise.all([
privileges.categories.isUserAllowedTo(privilege, cids, uid),
categories.getWatchState(cids, uid),
categories.getCategoriesData(cids),
user.isAdministrator(uid),
user.isModerator(uid, cids),
]);
const filtered = await plugins.hooks.fire('filter:helpers.getVisibleCategories', {
uid: uid,
allowed: allowed,
watchState: watchState,
categoriesData: categoriesData,
isModerator: isModerator,
isAdmin: isAdmin,
});
({ allowed, watchState, categoriesData, isModerator, isAdmin } = filtered);
categories.getTree(categoriesData, params.parentCid);
const cidToAllowed = _.zipObject(cids, allowed.map((allowed, i) => isAdmin || isModerator[i] || allowed));
const cidToCategory = _.zipObject(cids, categoriesData);
const cidToWatchState = _.zipObject(cids, watchState);
return categoriesData.filter((c) => {
if (!c) {
return false;
}
const hasVisibleChildren = checkVisibleChildren(c, cidToAllowed, cidToWatchState, states);
const isCategoryVisible = (
cidToAllowed[c.cid] &&
(showLinks || !c.link) &&
!c.disabled &&
states.includes(cidToWatchState[c.cid])
);
const shouldBeRemoved = !hasVisibleChildren && !isCategoryVisible;
const shouldBeDisaplayedAsDisabled = hasVisibleChildren && !isCategoryVisible;
if (shouldBeDisaplayedAsDisabled) {
c.disabledClass = true;
}
if (shouldBeRemoved && c.parent && c.parent.cid && cidToCategory[c.parent.cid]) {
cidToCategory[c.parent.cid].children = cidToCategory[c.parent.cid].children.filter(child => child.cid !== c.cid);
}
return !shouldBeRemoved;
});
};
helpers.getSelectedCategory = async function (cids) {
if (cids && !Array.isArray(cids)) {
cids = [cids];
}
cids = cids && cids.map(cid => parseInt(cid, 10));
let selectedCategories = await categories.getCategoriesData(cids);
const selectedCids = selectedCategories.map(c => c && c.cid).filter(Boolean);
if (selectedCategories.length > 1) {
selectedCategories = {
icon: 'fa-plus',
name: '[[unread:multiple-categories-selected]]',
bgColor: '#ddd',
};
} else if (selectedCategories.length === 1 && selectedCategories[0]) {
selectedCategories = selectedCategories[0];
} else {
selectedCategories = null;
}
return {
selectedCids: selectedCids,
selectedCategory: selectedCategories,
};
};
helpers.getSelectedTag = function (tags) {
if (tags && !Array.isArray(tags)) {
tags = [tags];
}
tags = tags || [];
const tagData = tags.map(t => validator.escape(String(t)));
let selectedTag = null;
if (tagData.length) {
selectedTag = {
label: tagData.join(', '),
};
}
return {
selectedTags: tagData,
selectedTag: selectedTag,
};
};
helpers.trimChildren = function (category) {
if (category && Array.isArray(category.children)) {
category.children = category.children.slice(0, category.subCategoriesPerPage);
category.children.forEach((child) => {
if (category.isSection) {
helpers.trimChildren(child);
} else {
child.children = undefined;
}
});
}
};
helpers.setCategoryTeaser = function (category) {
if (Array.isArray(category.posts) && category.posts.length && category.posts[0]) {
const post = category.posts[0];
category.teaser = {
url: `${nconf.get('relative_path')}/post/${post.pid}`,
timestampISO: post.timestampISO,
pid: post.pid,
index: post.index,
topic: post.topic,
user: post.user,
};
}
};
function checkVisibleChildren(c, cidToAllowed, cidToWatchState, states) {
if (!c || !Array.isArray(c.children)) {
return false;
}
return c.children.some(c => !c.disabled && (
(cidToAllowed[c.cid] && states.includes(cidToWatchState[c.cid])) ||
checkVisibleChildren(c, cidToAllowed, cidToWatchState, states)
));
}
helpers.getHomePageRoutes = async function (uid) {
const routes = [
{
route: 'categories',
name: 'Categories',
},
{
route: 'unread',
name: 'Unread',
},
{
route: 'recent',
name: 'Recent',
},
{
route: 'top',
name: 'Top',
},
{
route: 'popular',
name: 'Popular',
},
{
route: 'custom',
name: 'Custom',
},
];
const data = await plugins.hooks.fire('filter:homepage.get', {
uid: uid,
routes: routes,
});
return data.routes;
};
helpers.formatApiResponse = async (statusCode, res, payload) => {
if (res.req.method === 'HEAD') {
return res.sendStatus(statusCode);
}
if (String(statusCode).startsWith('2')) {
if (res.req.loggedIn) {
res.set('cache-control', 'private');
}
let code = 'ok';
let message = 'OK';
switch (statusCode) {
case 202:
code = 'accepted';
message = 'Accepted';
break;
case 204:
code = 'no-content';
message = 'No Content';
break;
}
res.status(statusCode).json({
status: { code, message },
response: payload || {},
});
} else if (payload instanceof Error) {
const { message } = payload;
const response = {};
// Update status code based on some common error codes
switch (message) {
case '[[error:user-banned]]':
Object.assign(response, await generateBannedResponse(res));
// intentional fall through
case '[[error:no-privileges]]':
statusCode = 403;
break;
case '[[error:invalid-uid]]':
statusCode = 401;
break;
case '[[error:no-topic]]':
statusCode = 404;
break;
}
if (message.startsWith('[[error:required-parameters-missing, ')) {
const params = message.slice('[[error:required-parameters-missing, '.length, -2).split(' ');
Object.assign(response, { params });
}
const returnPayload = await helpers.generateError(statusCode, message, res);
returnPayload.response = response;
if (global.env === 'development') {
returnPayload.stack = payload.stack;
process.stdout.write(`[${chalk.yellow('api')}] Exception caught, error with stack trace follows:\n`);
process.stdout.write(payload.stack);
}
res.status(statusCode).json(returnPayload);
} else if (!payload) {
// Non-2xx statusCode, generate predefined error
const returnPayload = await helpers.generateError(statusCode, null, res);
res.status(statusCode).json(returnPayload);
}
};
async function generateBannedResponse(res) {
const response = {};
const [reason, expiry] = await Promise.all([
user.bans.getReason(res.req.uid),
user.getUserField(res.req.uid, 'banned:expire'),
]);
response.reason = reason;
if (expiry) {
Object.assign(response, {
expiry,
expiryISO: new Date(expiry).toISOString(),
expiryLocaleString: new Date(expiry).toLocaleString(),
});
}
return response;
}
helpers.generateError = async (statusCode, message, res) => {
async function translateMessage(message) {
const { req } = res;
const settings = req.query.lang ? null : await user.getSettings(req.uid);
const language = String(req.query.lang || settings.userLang || meta.config.defaultLang);
return await translator.translate(message, language);
}
if (message && message.startsWith('[[')) {
message = await translateMessage(message);
}
const payload = {
status: {
code: 'internal-server-error',
message: message || await translateMessage(`[[error:api.${statusCode}]]`),
},
response: {},
};
switch (statusCode) {
case 400:
payload.status.code = 'bad-request';
break;
case 401:
payload.status.code = 'not-authorised';
break;
case 403:
payload.status.code = 'forbidden';
break;
case 404:
payload.status.code = 'not-found';
break;
case 426:
payload.status.code = 'upgrade-required';
break;
case 429:
payload.status.code = 'too-many-requests';
break;
case 500:
payload.status.code = 'internal-server-error';
break;
case 501:
payload.status.code = 'not-implemented';
break;
case 503:
payload.status.code = 'service-unavailable';
break;
}
return payload;
};
require('../promisify')(helpers);