users.ts 17 KB

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