2
1

users.ts 16 KB

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