1 import { param, body } from 'express-validator/check'
2 import * as express from 'express'
3 import { logger } from '../../helpers/logger'
4 import { areValidationErrors } from './utils'
5 import { isAccountNameWithHostExist } from '../../helpers/custom-validators/accounts'
6 import { UserModel } from '../../models/account/user'
7 import { AccountBlocklistModel } from '../../models/account/account-blocklist'
8 import { isHostValid } from '../../helpers/custom-validators/servers'
9 import { ServerBlocklistModel } from '../../models/server/server-blocklist'
11 const blockAccountByAccountValidator = [
12 body('accountName').exists().withMessage('Should have an account name with host'),
14 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
15 logger.debug('Checking blockAccountByAccountValidator parameters', { parameters: req.body })
17 if (areValidationErrors(req, res)) return
18 if (!await isAccountNameWithHostExist(req.body.accountName, res)) return
24 const unblockAccountByAccountValidator = [
25 param('accountName').exists().withMessage('Should have an account name with host'),
27 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
28 logger.debug('Checking unblockAccountByAccountValidator parameters', { parameters: req.params })
30 if (areValidationErrors(req, res)) return
31 if (!await isAccountNameWithHostExist(req.params.accountName, res)) return
33 const user = res.locals.oauth.token.User as UserModel
34 const targetAccount = res.locals.account
35 if (!await isUnblockAccountExists(user.Account.id, targetAccount.id, res)) return
41 const unblockServerByAccountValidator = [
42 param('host').custom(isHostValid).withMessage('Should have an account name with host'),
44 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
45 logger.debug('Checking unblockServerByAccountValidator parameters', { parameters: req.params })
47 if (areValidationErrors(req, res)) return
49 const user = res.locals.oauth.token.User as UserModel
50 if (!await isUnblockServerExists(user.Account.id, req.params.host, res)) return
56 // ---------------------------------------------------------------------------
59 blockAccountByAccountValidator,
60 unblockAccountByAccountValidator,
61 unblockServerByAccountValidator
64 // ---------------------------------------------------------------------------
66 async function isUnblockAccountExists (accountId: number, targetAccountId: number, res: express.Response) {
67 const accountBlock = await AccountBlocklistModel.loadByAccountAndTarget(accountId, targetAccountId)
70 .send({ error: 'Account block entry not found.' })
76 res.locals.accountBlock = accountBlock
81 async function isUnblockServerExists (accountId: number, host: string, res: express.Response) {
82 const serverBlock = await ServerBlocklistModel.loadByAccountAndHost(accountId, host)
85 .send({ error: 'Server block entry not found.' })
91 res.locals.serverBlock = serverBlock