]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blobdiff - server/controllers/api/users/index.ts
Fix users tests
[github/Chocobozzz/PeerTube.git] / server / controllers / api / users / index.ts
index 0b70125370c34d1b758afdd899c1817c0d853906..c8e9eaeaaf2f1c59e7c7321267b6cf81c924980c 100644 (file)
@@ -2,7 +2,7 @@ import * as express from 'express'
 import * as RateLimit from 'express-rate-limit'
 import { UserCreate, UserRight, UserRole, UserUpdate } from '../../../../shared'
 import { logger } from '../../../helpers/logger'
-import { getFormattedObjects } from '../../../helpers/utils'
+import { generateRandomString, getFormattedObjects } from '../../../helpers/utils'
 import { WEBSERVER } from '../../../initializers/constants'
 import { Emailer } from '../../../lib/emailer'
 import { Redis } from '../../../lib/redis'
@@ -17,7 +17,6 @@ import {
   paginationValidator,
   setDefaultPagination,
   setDefaultSort,
-  token,
   userAutocompleteValidator,
   usersAddValidator,
   usersGetValidator,
@@ -27,12 +26,12 @@ import {
   usersUpdateValidator
 } from '../../../middlewares'
 import {
+  ensureCanManageUser,
   usersAskResetPasswordValidator,
   usersAskSendVerifyEmailValidator,
   usersBlockingValidator,
   usersResetPasswordValidator,
-  usersVerifyEmailValidator,
-  ensureCanManageUser
+  usersVerifyEmailValidator
 } from '../../../middlewares/validators'
 import { UserModel } from '../../../models/account/user'
 import { auditLoggerFactory, getAuditIdFromRes, UserAuditView } from '../../../helpers/audit-logger'
@@ -48,30 +47,25 @@ import { CONFIG } from '../../../initializers/config'
 import { sequelizeTypescript } from '../../../initializers/database'
 import { UserAdminFlag } from '../../../../shared/models/users/user-flag.model'
 import { UserRegister } from '../../../../shared/models/users/user-register.model'
-import { MUser, MUserAccountDefault } from '@server/typings/models'
+import { MUser, MUserAccountDefault } from '@server/types/models'
 import { Hooks } from '@server/lib/plugins/hooks'
+import { tokensRouter } from '@server/controllers/api/users/token'
 
 const auditLogger = auditLoggerFactory('users')
 
-const loginRateLimiter = RateLimit({
-  windowMs: CONFIG.RATES_LIMIT.LOGIN.WINDOW_MS,
-  max: CONFIG.RATES_LIMIT.LOGIN.MAX
-})
-
-// @ts-ignore
 const signupRateLimiter = RateLimit({
   windowMs: CONFIG.RATES_LIMIT.SIGNUP.WINDOW_MS,
   max: CONFIG.RATES_LIMIT.SIGNUP.MAX,
   skipFailedRequests: true
 })
 
-// @ts-ignore
-const askSendEmailLimiter = new RateLimit({
+const askSendEmailLimiter = RateLimit({
   windowMs: CONFIG.RATES_LIMIT.ASK_SEND_EMAIL.WINDOW_MS,
   max: CONFIG.RATES_LIMIT.ASK_SEND_EMAIL.MAX
 })
 
 const usersRouter = express.Router()
+usersRouter.use('/', tokensRouter)
 usersRouter.use('/', myNotificationsRouter)
 usersRouter.use('/', mySubscriptionsRouter)
 usersRouter.use('/', myBlocklistRouter)
@@ -168,13 +162,6 @@ usersRouter.post('/:id/verify-email',
   asyncMiddleware(verifyUserEmail)
 )
 
-usersRouter.post('/token',
-  loginRateLimiter,
-  token,
-  tokenSuccess
-)
-// TODO: Once https://github.com/oauthjs/node-oauth2-server/pull/289 is merged, implement revoke token route
-
 // ---------------------------------------------------------------------------
 
 export {
@@ -197,11 +184,25 @@ async function createUser (req: express.Request, res: express.Response) {
     adminFlags: body.adminFlags || UserAdminFlag.NONE
   }) as MUser
 
+  // NB: due to the validator usersAddValidator, password==='' can only be true if we can send the mail.
+  const createPassword = userToCreate.password === ''
+  if (createPassword) {
+    userToCreate.password = await generateRandomString(20)
+  }
+
   const { user, account, videoChannel } = await createUserAccountAndChannelAndPlaylist({ userToCreate: userToCreate })
 
   auditLogger.create(getAuditIdFromRes(res), new UserAuditView(user.toFormattedJSON()))
   logger.info('User %s with its channel and account created.', body.username)
 
+  if (createPassword) {
+    // this will send an email for newly created users, so then can set their first password.
+    logger.info('Sending to user %s a create password email', body.username)
+    const verificationString = await Redis.Instance.setCreatePasswordVerificationString(user.id)
+    const url = WEBSERVER.URL + '/reset-password?userId=' + user.id + '&verificationString=' + verificationString
+    await Emailer.Instance.addPasswordCreateEmailJob(userToCreate.username, user.email, url)
+  }
+
   Hooks.runAction('action:api.user.created', { body, user, account, videoChannel })
 
   return res.json({
@@ -367,12 +368,6 @@ async function verifyUserEmail (req: express.Request, res: express.Response) {
   return res.status(204).end()
 }
 
-function tokenSuccess (req: express.Request) {
-  const username = req.body.username
-
-  Hooks.runAction('action:api.user.oauth2-got-token', { username, ip: req.ip })
-}
-
 async function changeUserBlock (res: express.Response, user: MUserAccountDefault, block: boolean, reason?: string) {
   const oldUserAuditView = new UserAuditView(user.toFormattedJSON())