From 56f47830758ff8e92abcfcc5f35d474ab12fe215 Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Wed, 5 Oct 2022 15:37:15 +0200 Subject: Support two factor authentication in backend --- server/middlewares/validators/shared/index.ts | 1 + server/middlewares/validators/shared/users.ts | 62 +++++++++++++++++++++++++++ 2 files changed, 63 insertions(+) create mode 100644 server/middlewares/validators/shared/users.ts (limited to 'server/middlewares/validators/shared') diff --git a/server/middlewares/validators/shared/index.ts b/server/middlewares/validators/shared/index.ts index bbd03b248..de98cd442 100644 --- a/server/middlewares/validators/shared/index.ts +++ b/server/middlewares/validators/shared/index.ts @@ -1,5 +1,6 @@ export * from './abuses' export * from './accounts' +export * from './users' export * from './utils' export * from './video-blacklists' export * from './video-captions' diff --git a/server/middlewares/validators/shared/users.ts b/server/middlewares/validators/shared/users.ts new file mode 100644 index 000000000..fbaa7db0e --- /dev/null +++ b/server/middlewares/validators/shared/users.ts @@ -0,0 +1,62 @@ +import express from 'express' +import { ActorModel } from '@server/models/actor/actor' +import { UserModel } from '@server/models/user/user' +import { MUserDefault } from '@server/types/models' +import { HttpStatusCode } from '@shared/models' + +function checkUserIdExist (idArg: number | string, res: express.Response, withStats = false) { + const id = parseInt(idArg + '', 10) + return checkUserExist(() => UserModel.loadByIdWithChannels(id, withStats), res) +} + +function checkUserEmailExist (email: string, res: express.Response, abortResponse = true) { + return checkUserExist(() => UserModel.loadByEmail(email), res, abortResponse) +} + +async function checkUserNameOrEmailDoesNotAlreadyExist (username: string, email: string, res: express.Response) { + const user = await UserModel.loadByUsernameOrEmail(username, email) + + if (user) { + res.fail({ + status: HttpStatusCode.CONFLICT_409, + message: 'User with this username or email already exists.' + }) + return false + } + + const actor = await ActorModel.loadLocalByName(username) + if (actor) { + res.fail({ + status: HttpStatusCode.CONFLICT_409, + message: 'Another actor (account/channel) with this name on this instance already exists or has already existed.' + }) + return false + } + + return true +} + +async function checkUserExist (finder: () => Promise, res: express.Response, abortResponse = true) { + const user = await finder() + + if (!user) { + if (abortResponse === true) { + res.fail({ + status: HttpStatusCode.NOT_FOUND_404, + message: 'User not found' + }) + } + + return false + } + + res.locals.user = user + return true +} + +export { + checkUserIdExist, + checkUserEmailExist, + checkUserNameOrEmailDoesNotAlreadyExist, + checkUserExist +} -- cgit v1.2.3