users.ts 14 KB

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