users.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546
  1. import * as express from 'express'
  2. import { body, param, query } from 'express-validator'
  3. import { omit } from 'lodash'
  4. import { Hooks } from '@server/lib/plugins/hooks'
  5. import { MUserDefault } from '@server/types/models'
  6. import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes'
  7. import { UserRole } from '../../../shared/models/users'
  8. import { UserRegister } from '../../../shared/models/users/user-register.model'
  9. import { isActorPreferredUsernameValid } from '../../helpers/custom-validators/activitypub/actor'
  10. import { isIdOrUUIDValid, toBooleanOrNull, toIntOrNull } from '../../helpers/custom-validators/misc'
  11. import { isThemeNameValid } from '../../helpers/custom-validators/plugins'
  12. import {
  13. isNoInstanceConfigWarningModal,
  14. isNoWelcomeModal,
  15. isUserAdminFlagsValid,
  16. isUserAutoPlayNextVideoValid,
  17. isUserAutoPlayVideoValid,
  18. isUserBlockedReasonValid,
  19. isUserDescriptionValid,
  20. isUserDisplayNameValid,
  21. isUserNSFWPolicyValid,
  22. isUserPasswordValid,
  23. isUserPasswordValidOrEmpty,
  24. isUserRoleValid,
  25. isUserUsernameValid,
  26. isUserVideoLanguages,
  27. isUserVideoQuotaDailyValid,
  28. isUserVideoQuotaValid,
  29. isUserVideosHistoryEnabledValid
  30. } from '../../helpers/custom-validators/users'
  31. import { isVideoChannelNameValid } from '../../helpers/custom-validators/video-channels'
  32. import { logger } from '../../helpers/logger'
  33. import { doesVideoExist } from '../../helpers/middlewares'
  34. import { isSignupAllowed, isSignupAllowedForCurrentIP } from '../../helpers/signup'
  35. import { isThemeRegistered } from '../../lib/plugins/theme-utils'
  36. import { Redis } from '../../lib/redis'
  37. import { UserModel } from '../../models/account/user'
  38. import { ActorModel } from '../../models/activitypub/actor'
  39. import { areValidationErrors } from './utils'
  40. const usersListValidator = [
  41. query('blocked')
  42. .optional()
  43. .customSanitizer(toBooleanOrNull)
  44. .isBoolean().withMessage('Should be a valid boolean banned state'),
  45. (req: express.Request, res: express.Response, next: express.NextFunction) => {
  46. logger.debug('Checking usersList parameters', { parameters: req.query })
  47. if (areValidationErrors(req, res)) return
  48. return next()
  49. }
  50. ]
  51. const usersAddValidator = [
  52. body('username').custom(isUserUsernameValid).withMessage('Should have a valid username (lowercase alphanumeric characters)'),
  53. body('password').custom(isUserPasswordValidOrEmpty).withMessage('Should have a valid password'),
  54. body('email').isEmail().withMessage('Should have a valid email'),
  55. body('channelName').optional().custom(isActorPreferredUsernameValid).withMessage('Should have a valid channel name'),
  56. body('videoQuota').custom(isUserVideoQuotaValid).withMessage('Should have a valid user quota'),
  57. body('videoQuotaDaily').custom(isUserVideoQuotaDailyValid).withMessage('Should have a valid daily user quota'),
  58. body('role')
  59. .customSanitizer(toIntOrNull)
  60. .custom(isUserRoleValid).withMessage('Should have a valid role'),
  61. body('adminFlags').optional().custom(isUserAdminFlagsValid).withMessage('Should have a valid admin flags'),
  62. async (req: express.Request, res: express.Response, next: express.NextFunction) => {
  63. logger.debug('Checking usersAdd parameters', { parameters: omit(req.body, 'password') })
  64. if (areValidationErrors(req, res)) return
  65. if (!await checkUserNameOrEmailDoesNotAlreadyExist(req.body.username, req.body.email, res)) return
  66. const authUser = res.locals.oauth.token.User
  67. if (authUser.role !== UserRole.ADMINISTRATOR && req.body.role !== UserRole.USER) {
  68. return res
  69. .status(HttpStatusCode.FORBIDDEN_403)
  70. .json({ error: 'You can only create users (and not administrators or moderators)' })
  71. }
  72. if (req.body.channelName) {
  73. if (req.body.channelName === req.body.username) {
  74. return res
  75. .status(HttpStatusCode.BAD_REQUEST_400)
  76. .json({ error: 'Channel name cannot be the same as user username.' })
  77. }
  78. const existing = await ActorModel.loadLocalByName(req.body.channelName)
  79. if (existing) {
  80. return res
  81. .status(HttpStatusCode.CONFLICT_409)
  82. .json({ error: `Channel with name ${req.body.channelName} already exists.` })
  83. }
  84. }
  85. return next()
  86. }
  87. ]
  88. const usersRegisterValidator = [
  89. body('username').custom(isUserUsernameValid).withMessage('Should have a valid username'),
  90. body('password').custom(isUserPasswordValid).withMessage('Should have a valid password'),
  91. body('email').isEmail().withMessage('Should have a valid email'),
  92. body('displayName')
  93. .optional()
  94. .custom(isUserDisplayNameValid).withMessage('Should have a valid display name'),
  95. body('channel.name')
  96. .optional()
  97. .custom(isActorPreferredUsernameValid).withMessage('Should have a valid channel name'),
  98. body('channel.displayName')
  99. .optional()
  100. .custom(isVideoChannelNameValid).withMessage('Should have a valid display name'),
  101. async (req: express.Request, res: express.Response, next: express.NextFunction) => {
  102. logger.debug('Checking usersRegister parameters', { parameters: omit(req.body, 'password') })
  103. if (areValidationErrors(req, res)) return
  104. if (!await checkUserNameOrEmailDoesNotAlreadyExist(req.body.username, req.body.email, res)) return
  105. const body: UserRegister = req.body
  106. if (body.channel) {
  107. if (!body.channel.name || !body.channel.displayName) {
  108. return res
  109. .status(HttpStatusCode.BAD_REQUEST_400)
  110. .json({ error: 'Channel is optional but if you specify it, channel.name and channel.displayName are required.' })
  111. }
  112. if (body.channel.name === body.username) {
  113. return res.status(HttpStatusCode.BAD_REQUEST_400)
  114. .json({ error: 'Channel name cannot be the same as user username.' })
  115. }
  116. const existing = await ActorModel.loadLocalByName(body.channel.name)
  117. if (existing) {
  118. return res.status(HttpStatusCode.CONFLICT_409)
  119. .json({ error: `Channel with name ${body.channel.name} already exists.` })
  120. }
  121. }
  122. return next()
  123. }
  124. ]
  125. const usersRemoveValidator = [
  126. param('id').isInt().not().isEmpty().withMessage('Should have a valid id'),
  127. async (req: express.Request, res: express.Response, next: express.NextFunction) => {
  128. logger.debug('Checking usersRemove parameters', { parameters: req.params })
  129. if (areValidationErrors(req, res)) return
  130. if (!await checkUserIdExist(req.params.id, res)) return
  131. const user = res.locals.user
  132. if (user.username === 'root') {
  133. return res.status(HttpStatusCode.BAD_REQUEST_400)
  134. .json({ error: 'Cannot remove the root user' })
  135. }
  136. return next()
  137. }
  138. ]
  139. const usersBlockingValidator = [
  140. param('id').isInt().not().isEmpty().withMessage('Should have a valid id'),
  141. body('reason').optional().custom(isUserBlockedReasonValid).withMessage('Should have a valid blocking reason'),
  142. async (req: express.Request, res: express.Response, next: express.NextFunction) => {
  143. logger.debug('Checking usersBlocking parameters', { parameters: req.params })
  144. if (areValidationErrors(req, res)) return
  145. if (!await checkUserIdExist(req.params.id, res)) return
  146. const user = res.locals.user
  147. if (user.username === 'root') {
  148. return res.status(HttpStatusCode.BAD_REQUEST_400)
  149. .json({ error: 'Cannot block the root user' })
  150. }
  151. return next()
  152. }
  153. ]
  154. const deleteMeValidator = [
  155. (req: express.Request, res: express.Response, next: express.NextFunction) => {
  156. const user = res.locals.oauth.token.User
  157. if (user.username === 'root') {
  158. return res.status(HttpStatusCode.BAD_REQUEST_400)
  159. .json({ error: 'You cannot delete your root account.' })
  160. .end()
  161. }
  162. return next()
  163. }
  164. ]
  165. const usersUpdateValidator = [
  166. param('id').isInt().not().isEmpty().withMessage('Should have a valid id'),
  167. body('password').optional().custom(isUserPasswordValid).withMessage('Should have a valid password'),
  168. body('email').optional().isEmail().withMessage('Should have a valid email attribute'),
  169. body('emailVerified').optional().isBoolean().withMessage('Should have a valid email verified attribute'),
  170. body('videoQuota').optional().custom(isUserVideoQuotaValid).withMessage('Should have a valid user quota'),
  171. body('videoQuotaDaily').optional().custom(isUserVideoQuotaDailyValid).withMessage('Should have a valid daily user quota'),
  172. body('role')
  173. .optional()
  174. .customSanitizer(toIntOrNull)
  175. .custom(isUserRoleValid).withMessage('Should have a valid role'),
  176. body('adminFlags').optional().custom(isUserAdminFlagsValid).withMessage('Should have a valid admin flags'),
  177. async (req: express.Request, res: express.Response, next: express.NextFunction) => {
  178. logger.debug('Checking usersUpdate parameters', { parameters: req.body })
  179. if (areValidationErrors(req, res)) return
  180. if (!await checkUserIdExist(req.params.id, res)) return
  181. const user = res.locals.user
  182. if (user.username === 'root' && req.body.role !== undefined && user.role !== req.body.role) {
  183. return res.status(HttpStatusCode.BAD_REQUEST_400)
  184. .json({ error: 'Cannot change root role.' })
  185. }
  186. return next()
  187. }
  188. ]
  189. const usersUpdateMeValidator = [
  190. body('displayName')
  191. .optional()
  192. .custom(isUserDisplayNameValid).withMessage('Should have a valid display name'),
  193. body('description')
  194. .optional()
  195. .custom(isUserDescriptionValid).withMessage('Should have a valid description'),
  196. body('currentPassword')
  197. .optional()
  198. .custom(isUserPasswordValid).withMessage('Should have a valid current password'),
  199. body('password')
  200. .optional()
  201. .custom(isUserPasswordValid).withMessage('Should have a valid password'),
  202. body('email')
  203. .optional()
  204. .isEmail().withMessage('Should have a valid email attribute'),
  205. body('nsfwPolicy')
  206. .optional()
  207. .custom(isUserNSFWPolicyValid).withMessage('Should have a valid display Not Safe For Work policy'),
  208. body('autoPlayVideo')
  209. .optional()
  210. .custom(isUserAutoPlayVideoValid).withMessage('Should have a valid automatically plays video attribute'),
  211. body('videoLanguages')
  212. .optional()
  213. .custom(isUserVideoLanguages).withMessage('Should have a valid video languages attribute'),
  214. body('videosHistoryEnabled')
  215. .optional()
  216. .custom(isUserVideosHistoryEnabledValid).withMessage('Should have a valid videos history enabled attribute'),
  217. body('theme')
  218. .optional()
  219. .custom(v => isThemeNameValid(v) && isThemeRegistered(v)).withMessage('Should have a valid theme'),
  220. body('noInstanceConfigWarningModal')
  221. .optional()
  222. .custom(v => isNoInstanceConfigWarningModal(v)).withMessage('Should have a valid noInstanceConfigWarningModal boolean'),
  223. body('noWelcomeModal')
  224. .optional()
  225. .custom(v => isNoWelcomeModal(v)).withMessage('Should have a valid noWelcomeModal boolean'),
  226. body('autoPlayNextVideo')
  227. .optional()
  228. .custom(v => isUserAutoPlayNextVideoValid(v)).withMessage('Should have a valid autoPlayNextVideo boolean'),
  229. async (req: express.Request, res: express.Response, next: express.NextFunction) => {
  230. logger.debug('Checking usersUpdateMe parameters', { parameters: omit(req.body, 'password') })
  231. const user = res.locals.oauth.token.User
  232. if (req.body.password || req.body.email) {
  233. if (user.pluginAuth !== null) {
  234. return res.status(HttpStatusCode.BAD_REQUEST_400)
  235. .json({ error: 'You cannot update your email or password that is associated with an external auth system.' })
  236. }
  237. if (!req.body.currentPassword) {
  238. return res.status(HttpStatusCode.BAD_REQUEST_400)
  239. .json({ error: 'currentPassword parameter is missing.' })
  240. }
  241. if (await user.isPasswordMatch(req.body.currentPassword) !== true) {
  242. return res.status(HttpStatusCode.UNAUTHORIZED_401)
  243. .json({ error: 'currentPassword is invalid.' })
  244. }
  245. }
  246. if (areValidationErrors(req, res)) return
  247. return next()
  248. }
  249. ]
  250. const usersGetValidator = [
  251. param('id').isInt().not().isEmpty().withMessage('Should have a valid id'),
  252. query('withStats').optional().isBoolean().withMessage('Should have a valid stats flag'),
  253. async (req: express.Request, res: express.Response, next: express.NextFunction) => {
  254. logger.debug('Checking usersGet parameters', { parameters: req.params })
  255. if (areValidationErrors(req, res)) return
  256. if (!await checkUserIdExist(req.params.id, res, req.query.withStats)) return
  257. return next()
  258. }
  259. ]
  260. const usersVideoRatingValidator = [
  261. param('videoId').custom(isIdOrUUIDValid).not().isEmpty().withMessage('Should have a valid video id'),
  262. async (req: express.Request, res: express.Response, next: express.NextFunction) => {
  263. logger.debug('Checking usersVideoRating parameters', { parameters: req.params })
  264. if (areValidationErrors(req, res)) return
  265. if (!await doesVideoExist(req.params.videoId, res, 'id')) return
  266. return next()
  267. }
  268. ]
  269. const ensureUserRegistrationAllowed = [
  270. async (req: express.Request, res: express.Response, next: express.NextFunction) => {
  271. const allowedParams = {
  272. body: req.body,
  273. ip: req.ip
  274. }
  275. const allowedResult = await Hooks.wrapPromiseFun(
  276. isSignupAllowed,
  277. allowedParams,
  278. 'filter:api.user.signup.allowed.result'
  279. )
  280. if (allowedResult.allowed === false) {
  281. return res.status(HttpStatusCode.FORBIDDEN_403)
  282. .json({ error: allowedResult.errorMessage || 'User registration is not enabled or user limit is reached.' })
  283. }
  284. return next()
  285. }
  286. ]
  287. const ensureUserRegistrationAllowedForIP = [
  288. (req: express.Request, res: express.Response, next: express.NextFunction) => {
  289. const allowed = isSignupAllowedForCurrentIP(req.ip)
  290. if (allowed === false) {
  291. return res.status(HttpStatusCode.FORBIDDEN_403)
  292. .json({ error: 'You are not on a network authorized for registration.' })
  293. }
  294. return next()
  295. }
  296. ]
  297. const usersAskResetPasswordValidator = [
  298. body('email').isEmail().not().isEmpty().withMessage('Should have a valid email'),
  299. async (req: express.Request, res: express.Response, next: express.NextFunction) => {
  300. logger.debug('Checking usersAskResetPassword parameters', { parameters: req.body })
  301. if (areValidationErrors(req, res)) return
  302. const exists = await checkUserEmailExist(req.body.email, res, false)
  303. if (!exists) {
  304. logger.debug('User with email %s does not exist (asking reset password).', req.body.email)
  305. // Do not leak our emails
  306. return res.status(HttpStatusCode.NO_CONTENT_204).end()
  307. }
  308. return next()
  309. }
  310. ]
  311. const usersResetPasswordValidator = [
  312. param('id').isInt().not().isEmpty().withMessage('Should have a valid id'),
  313. body('verificationString').not().isEmpty().withMessage('Should have a valid verification string'),
  314. body('password').custom(isUserPasswordValid).withMessage('Should have a valid password'),
  315. async (req: express.Request, res: express.Response, next: express.NextFunction) => {
  316. logger.debug('Checking usersResetPassword parameters', { parameters: req.params })
  317. if (areValidationErrors(req, res)) return
  318. if (!await checkUserIdExist(req.params.id, res)) return
  319. const user = res.locals.user
  320. const redisVerificationString = await Redis.Instance.getResetPasswordLink(user.id)
  321. if (redisVerificationString !== req.body.verificationString) {
  322. return res
  323. .status(HttpStatusCode.FORBIDDEN_403)
  324. .json({ error: 'Invalid verification string.' })
  325. }
  326. return next()
  327. }
  328. ]
  329. const usersAskSendVerifyEmailValidator = [
  330. body('email').isEmail().not().isEmpty().withMessage('Should have a valid email'),
  331. async (req: express.Request, res: express.Response, next: express.NextFunction) => {
  332. logger.debug('Checking askUsersSendVerifyEmail parameters', { parameters: req.body })
  333. if (areValidationErrors(req, res)) return
  334. const exists = await checkUserEmailExist(req.body.email, res, false)
  335. if (!exists) {
  336. logger.debug('User with email %s does not exist (asking verify email).', req.body.email)
  337. // Do not leak our emails
  338. return res.status(HttpStatusCode.NO_CONTENT_204).end()
  339. }
  340. return next()
  341. }
  342. ]
  343. const usersVerifyEmailValidator = [
  344. param('id')
  345. .isInt().not().isEmpty().withMessage('Should have a valid id'),
  346. body('verificationString')
  347. .not().isEmpty().withMessage('Should have a valid verification string'),
  348. body('isPendingEmail')
  349. .optional()
  350. .customSanitizer(toBooleanOrNull),
  351. async (req: express.Request, res: express.Response, next: express.NextFunction) => {
  352. logger.debug('Checking usersVerifyEmail parameters', { parameters: req.params })
  353. if (areValidationErrors(req, res)) return
  354. if (!await checkUserIdExist(req.params.id, res)) return
  355. const user = res.locals.user
  356. const redisVerificationString = await Redis.Instance.getVerifyEmailLink(user.id)
  357. if (redisVerificationString !== req.body.verificationString) {
  358. return res
  359. .status(HttpStatusCode.FORBIDDEN_403)
  360. .json({ error: 'Invalid verification string.' })
  361. }
  362. return next()
  363. }
  364. ]
  365. const userAutocompleteValidator = [
  366. param('search').isString().not().isEmpty().withMessage('Should have a search parameter')
  367. ]
  368. const ensureAuthUserOwnsAccountValidator = [
  369. (req: express.Request, res: express.Response, next: express.NextFunction) => {
  370. const user = res.locals.oauth.token.User
  371. if (res.locals.account.id !== user.Account.id) {
  372. return res.status(HttpStatusCode.FORBIDDEN_403)
  373. .json({ error: 'Only owner can access ratings list.' })
  374. }
  375. return next()
  376. }
  377. ]
  378. const ensureCanManageUser = [
  379. (req: express.Request, res: express.Response, next: express.NextFunction) => {
  380. const authUser = res.locals.oauth.token.User
  381. const onUser = res.locals.user
  382. if (authUser.role === UserRole.ADMINISTRATOR) return next()
  383. if (authUser.role === UserRole.MODERATOR && onUser.role === UserRole.USER) return next()
  384. return res.status(HttpStatusCode.FORBIDDEN_403)
  385. .json({ error: 'A moderator can only manager users.' })
  386. }
  387. ]
  388. // ---------------------------------------------------------------------------
  389. export {
  390. usersListValidator,
  391. usersAddValidator,
  392. deleteMeValidator,
  393. usersRegisterValidator,
  394. usersBlockingValidator,
  395. usersRemoveValidator,
  396. usersUpdateValidator,
  397. usersUpdateMeValidator,
  398. usersVideoRatingValidator,
  399. ensureUserRegistrationAllowed,
  400. ensureUserRegistrationAllowedForIP,
  401. usersGetValidator,
  402. usersAskResetPasswordValidator,
  403. usersResetPasswordValidator,
  404. usersAskSendVerifyEmailValidator,
  405. usersVerifyEmailValidator,
  406. userAutocompleteValidator,
  407. ensureAuthUserOwnsAccountValidator,
  408. ensureCanManageUser
  409. }
  410. // ---------------------------------------------------------------------------
  411. function checkUserIdExist (idArg: number | string, res: express.Response, withStats = false) {
  412. const id = parseInt(idArg + '', 10)
  413. return checkUserExist(() => UserModel.loadByIdWithChannels(id, withStats), res)
  414. }
  415. function checkUserEmailExist (email: string, res: express.Response, abortResponse = true) {
  416. return checkUserExist(() => UserModel.loadByEmail(email), res, abortResponse)
  417. }
  418. async function checkUserNameOrEmailDoesNotAlreadyExist (username: string, email: string, res: express.Response) {
  419. const user = await UserModel.loadByUsernameOrEmail(username, email)
  420. if (user) {
  421. res.status(HttpStatusCode.CONFLICT_409)
  422. .json({ error: 'User with this username or email already exists.' })
  423. return false
  424. }
  425. const actor = await ActorModel.loadLocalByName(username)
  426. if (actor) {
  427. res.status(HttpStatusCode.CONFLICT_409)
  428. .json({ error: 'Another actor (account/channel) with this name on this instance already exists or has already existed.' })
  429. return false
  430. }
  431. return true
  432. }
  433. async function checkUserExist (finder: () => Promise<MUserDefault>, res: express.Response, abortResponse = true) {
  434. const user = await finder()
  435. if (!user) {
  436. if (abortResponse === true) {
  437. res.status(HttpStatusCode.NOT_FOUND_404)
  438. .json({ error: 'User not found' })
  439. }
  440. return false
  441. }
  442. res.locals.user = user
  443. return true
  444. }