Moderation configuration screen: WIP.

This commit is contained in:
John Livingston
2023-08-09 16:16:02 +02:00
parent 09b1c889ff
commit 0987a036a0
10 changed files with 275 additions and 64 deletions

View File

@ -0,0 +1,53 @@
import type { RegisterServerOptions } from '@peertube/peertube-types'
import type { Request, Response, NextFunction } from 'express'
import type { RequestPromiseHandler } from '../async'
import { getChannelInfosById } from '../../database/channel'
import { isUserAdminOrModerator } from '../../helpers'
/**
* Returns a middleware handler to get the channelInfos from the channel parameter.
* This is used in api related to channel moderation options.
* @param options Peertube server options
* @returns middleware function
*/
function getCheckModerationChannelMiddleware (options: RegisterServerOptions): RequestPromiseHandler {
return async (req: Request, res: Response, next: NextFunction) => {
const logger = options.peertubeHelpers.logger
const channelId = req.params.channelId
const currentUser = await options.peertubeHelpers.user.getAuthUser(res)
if (!channelId || !/^\d+$/.test(channelId)) {
res.sendStatus(400)
return
}
const channelInfos = await getChannelInfosById(options, parseInt(channelId), true)
if (!channelInfos) {
logger.warn(`Channel ${channelId} not found`)
res.sendStatus(404)
return
}
// To access this page, you must either be:
// - the channel owner,
// - an instance modo/admin
// - TODO: a channel chat moderator, as defined in this page.
if (channelInfos.ownerAccountId === currentUser.Account.id) {
logger.debug('Current user is the channel owner')
} else if (await isUserAdminOrModerator(options, res)) {
logger.debug('Current user is an instance moderator or admin')
} else {
logger.warn('Current user tries to access a channel for which he has no right.')
res.sendStatus(403)
return
}
logger.debug('User can access the moderation channel api.')
res.locals.channelInfos = channelInfos
next()
}
}
export {
getCheckModerationChannelMiddleware
}

View File

@ -0,0 +1,62 @@
import type { RegisterServerOptions } from '@peertube/peertube-types'
import type { ChannelModerationOptions, ChannelInfos } from '../../../../shared/lib/types'
/**
* Sanitize data so that they can safely be used/stored for channel moderation configuration.
* Throw an error if the format is obviously wrong.
* Cleans data (removing empty values, ...)
* @param options Peertube server options
* @param _channelInfos Channel infos
* @param data Input data
*/
async function sanitizeChannelModerationOptions (
_options: RegisterServerOptions,
_channelInfos: ChannelInfos,
data: any
): Promise<ChannelModerationOptions> {
const result = {
bot: false,
bannedJIDs: [],
forbiddenWords: []
}
if (typeof data !== 'object') {
throw new Error('Invalid data type')
}
// boolean fields
for (const f of ['bot']) {
if (!(f in data) || (typeof data[f] !== 'boolean')) {
throw new Error('Invalid data type for field ' + f)
}
result[f as keyof ChannelModerationOptions] = data[f]
}
// value/regexp array fields
for (const f of ['bannedJIDs', 'forbiddenWords']) {
if (!(f in data) || !Array.isArray(data[f])) {
throw new Error('Invalid data type for field ' + f)
}
for (const v of data[f]) {
if (typeof v !== 'string') {
throw new Error('Invalid data type in a value of field ' + f)
}
if (v === '' || /^\s+$/.test(v)) {
// ignore empty values
continue
}
// value must be a valid regexp
try {
// eslint-disable-next-line no-new
new RegExp(v)
} catch (_err) {
throw new Error('Invalid value in field ' + f)
}
(result[f as keyof ChannelModerationOptions] as string[]).push(v)
}
}
return result
}
export {
sanitizeChannelModerationOptions
}

View File

@ -0,0 +1,28 @@
import type { RegisterServerOptions } from '@peertube/peertube-types'
import type { ChannelModeration, ChannelInfos } from '../../../../shared/lib/types'
async function getChannelModerationOptions (
options: RegisterServerOptions,
channelInfos: ChannelInfos
): Promise<ChannelModeration> {
return {
channel: channelInfos,
moderation: {
bot: false,
bannedJIDs: [],
forbiddenWords: []
}
}
}
async function storeChannelModerationOptions (
_options: RegisterServerOptions,
_channelModeration: ChannelModeration
): Promise<void> {
throw new Error('Not implemented yet')
}
export {
getChannelModerationOptions,
storeChannelModerationOptions
}

View File

@ -1,61 +1,60 @@
import type { RegisterServerOptions } from '@peertube/peertube-types'
import type { Router, Request, Response, NextFunction } from 'express'
import type { ChannelModerationOptions } from '../../../../shared/lib/types'
import type { ChannelInfos } from '../../../../shared/lib/types'
import { asyncMiddleware } from '../../middlewares/async'
import { getChannelInfosById } from '../../database/channel'
import { isUserAdminOrModerator } from '../../helpers'
import { getCheckModerationChannelMiddleware } from '../../middlewares/moderation/channel'
import { getChannelModerationOptions, storeChannelModerationOptions } from '../../moderation/channel/storage'
import { sanitizeChannelModerationOptions } from '../../moderation/channel/sanitize'
async function initModerationApiRouter (options: RegisterServerOptions): Promise<Router> {
const router = options.getRouter()
const logger = options.peertubeHelpers.logger
router.get('/channel/:channelId', asyncMiddleware(
router.get('/channel/:channelId', asyncMiddleware([
getCheckModerationChannelMiddleware(options),
async (req: Request, res: Response, _next: NextFunction): Promise<void> => {
const channelId = req.params.channelId
const currentUser = await options.peertubeHelpers.user.getAuthUser(res)
if (!res.locals.channelInfos) {
logger.error('Missing channelInfos in res.locals, should not happen')
res.sendStatus(500)
return
}
const channelInfos = res.locals.channelInfos as ChannelInfos
if (!channelId || !/^\d+$/.test(channelId)) {
const result = await getChannelModerationOptions(options, channelInfos)
res.status(200)
res.json(result)
}
]))
router.post('/channel/:channelId', asyncMiddleware([
getCheckModerationChannelMiddleware(options),
async (req: Request, res: Response, _next: NextFunction): Promise<void> => {
if (!res.locals.channelInfos) {
logger.error('Missing channelInfos in res.locals, should not happen')
res.sendStatus(500)
return
}
const channelInfos = res.locals.channelInfos as ChannelInfos
logger.debug('Trying to save ChannelModerationOptions')
let moderation
try {
moderation = await sanitizeChannelModerationOptions(options, channelInfos, req.body)
} catch (err) {
logger.warn(err)
res.sendStatus(400)
return
}
const channelInfos = await getChannelInfosById(options, parseInt(channelId), true)
if (!channelInfos) {
logger.warn(`Channel ${channelId} not found`)
res.sendStatus(404)
return
}
// To access this page, you must either be:
// - the channel owner,
// - an instance modo/admin
// - TODO: a channel chat moderator, as defined in this page.
if (channelInfos.ownerAccountId === currentUser.Account.id) {
logger.debug('Current user is the channel owner')
} else if (await isUserAdminOrModerator(options, res)) {
logger.debug('Current user is an instance moderator or admin')
} else {
logger.warn('Current user tries to access a channel for which he has no right.')
res.sendStatus(403)
return
}
logger.debug('User can access the moderation channel api.')
const result: ChannelModerationOptions = {
channel: {
id: channelInfos.id,
name: channelInfos.name,
displayName: channelInfos.displayName
},
bot: false,
forbiddenWords: [],
bannedJIDs: []
}
logger.debug('Data seems ok, storing them.')
const result = await storeChannelModerationOptions(options, {
channel: channelInfos,
moderation
})
res.status(200)
res.json(result)
}
))
]))
return router
}