ActivityPub-federated video streaming platform using P2P directly in your web browser
feat: add new video password api (#7044)
Shalabh Agarwal9ed63f5e378c
diff --git a/packages/server-commands/src/videos/video-passwords-command.ts b/packages/server-commands/src/videos/video-passwords-command.tsindex 7a56311ca2..3f9b5d3cf4 100644--- a/packages/server-commands/src/videos/video-passwords-command.ts+++ b/packages/server-commands/src/videos/video-passwords-command.ts@@ -38,6 +38,22 @@ export class VideoPasswordsCommand extends AbstractCommand {})}+ addOne (options: OverrideCommandOptions & {+ videoId: number | string+ password: string+ }) {+ const { videoId, password } = options+ const path = `/api/v1/videos/${videoId}/passwords`++ return this.postBodyRequest({+ ...options,+ path,+ fields: { password },+ implicitToken: true,+ defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204+ })+ }+remove (options: OverrideCommandOptions & {id: numbervideoId: number | stringdiff --git a/packages/tests/src/api/check-params/video-passwords.ts b/packages/tests/src/api/check-params/video-passwords.tsindex 658c4d4a50..9d4d6ea789 100644--- a/packages/tests/src/api/check-params/video-passwords.ts+++ b/packages/tests/src/api/check-params/video-passwords.ts@@ -646,6 +646,54 @@ describe('Test video passwords validator', function () {})})+ describe('When adding a password', async function () {+ const passwords = (await server.videoPasswords.list({ videoId: video.id })).data+ const newPassword = 'password123'+ const emptyPassword = ''++ it('Should fail with duplicate password', async function () {+ await server.videoPasswords.addOne({+ videoId: video.id,+ password: passwords[0].password,+ expectedStatus: HttpStatusCode.BAD_REQUEST_400+ })+ })++ it('Should fail with empty password', async function () {+ await server.videoPasswords.addOne({ videoId: video.id, password: emptyPassword, expectedStatus: HttpStatusCode.BAD_REQUEST_400 })+ })++ it('Should fail for unauthenticated user', async function () {+ await server.videoPasswords.addOne({+ password: newPassword,+ token: null,+ videoId: video.id,+ expectedStatus: HttpStatusCode.FORBIDDEN_403+ })+ })++ it('Should fail for unauthorized user', async function () {+ await server.videoPasswords.addOne({+ password: newPassword,+ token: userAccessToken,+ videoId: video.id,+ expectedStatus: HttpStatusCode.BAD_REQUEST_400+ })+ })++ it('Should fail for non password protected video', async function () {+ publicVideo = await server.videos.quickUpload({ name: 'public video' })++ await server.videoPasswords.addOne({ password: newPassword, videoId: publicVideo.id, expectedStatus: HttpStatusCode.BAD_REQUEST_400 })+ })++ it('Should succeed with correct parameter', async function () {+ for (const token of [ server.accessToken, editorToken ]) {+ await server.videoPasswords.addOne({ password: token, videoId: video.id })+ }+ })+ })+after(async function () {await cleanupTests([ server ])})diff --git a/packages/tests/src/api/videos/video-passwords.ts b/packages/tests/src/api/videos/video-passwords.tsindex d943afec01..b04a870b5c 100644--- a/packages/tests/src/api/videos/video-passwords.ts+++ b/packages/tests/src/api/videos/video-passwords.ts@@ -80,17 +80,31 @@ describe('Test video passwords', function () {expect(body.total).to.equal(2)expect(body.data).to.be.an('array')expect(body.data).to.have.lengthOf(2)+await command.remove({ id: body.data[0].id, videoId: videoUUID })}+{const body = await command.list({ videoId: videoUUID })expect(body.total).to.equal(1)expect(body.data).to.be.an('array')expect(body.data).to.have.lengthOf(1)+ expect(body.data[0].password).to.equal('my super new password 1')}})+ it('Should add one password', async function () {+ await command.addOne({ password: 'the last password', videoId: videoUUID })+ const body = await command.list({ videoId: videoUUID, sort: 'createdAt' })++ expect(body.total).to.equal(2)+ expect(body.data).to.be.an('array')+ expect(body.data).to.have.lengthOf(2)+ expect(body.data[0].password).to.equal('my super new password 1')+ expect(body.data[1].password).to.equal('the last password')+ })+after(async function () {await cleanupTests([ server ])})diff --git a/server/core/controllers/api/videos/passwords.ts b/server/core/controllers/api/videos/passwords.tsindex 7f6ce10147..3c20c83dbd 100644--- a/server/core/controllers/api/videos/passwords.ts+++ b/server/core/controllers/api/videos/passwords.ts@@ -1,5 +1,6 @@import { HttpStatusCode, VideoChannelActivityAction } from '@peertube/peertube-models'import { logger, loggerTagsFactory } from '@server/helpers/logger.js'+import { sequelizeTypescript } from '@server/initializers/database.js'import { VideoChannelActivityModel } from '@server/models/video/video-channel-activity.js'import { VideoPasswordModel } from '@server/models/video/video-password.js'import express from 'express'@@ -13,6 +14,7 @@ import {setDefaultSort} from '../../../middlewares/index.js'import {+ addVideoPasswordValidator,listVideoPasswordValidator,paginationValidator,removeVideoPasswordValidator,@@ -41,6 +43,8 @@ videoPasswordRouter.put(asyncMiddleware(updateVideoPasswordList))+videoPasswordRouter.post('/:videoId/passwords', authenticate, asyncMiddleware(addVideoPasswordValidator), asyncMiddleware(addVideoPassword))+videoPasswordRouter.delete('/:videoId/passwords/:passwordId',authenticate,@@ -70,8 +74,8 @@ async function listVideoPasswords (req: express.Request, res: express.Response)}async function updateVideoPasswordList (req: express.Request, res: express.Response) {- const videoInstance = res.locals.videoAll- const videoId = videoInstance.id+ const video = res.locals.videoAll+ const videoId = video.idconst passwordArray = req.body.passwords as string[]@@ -82,18 +86,28 @@ async function updateVideoPasswordList (req: express.Request, res: express.Respoawait VideoChannelActivityModel.addVideoActivity({action: VideoChannelActivityAction.UPDATE_PASSWORDS,user: res.locals.oauth.token.User,- channel: videoInstance.VideoChannel,- video: videoInstance,+ channel: video.VideoChannel,+ video,transaction: t})})- logger.info(- `Video passwords for video with name %s and uuid %s have been updated`,- videoInstance.name,- videoInstance.uuid,- lTags(videoInstance.uuid)- )+ logger.info(`Video passwords for video with name ${video.name} and uuid ${video.uuid} have been updated`, lTags(video.uuid))++ return res.sendStatus(HttpStatusCode.NO_CONTENT_204)+}++async function addVideoPassword (req: express.Request, res: express.Response) {+ const video = res.locals.videoAll+ const videoId = video.id++ const newPassword = req.body.password as string++ await sequelizeTypescript.transaction(t => {+ return VideoPasswordModel.addPassword(newPassword, videoId, t)+ })++ logger.info(`Video password for video with name ${video.name} and uuid ${video.uuid} have been added`, lTags(video.uuid))return res.sendStatus(HttpStatusCode.NO_CONTENT_204)}diff --git a/server/core/helpers/custom-validators/videos.ts b/server/core/helpers/custom-validators/videos.tsindex 1f0e586ab0..c8b01c12d0 100644--- a/server/core/helpers/custom-validators/videos.ts+++ b/server/core/helpers/custom-validators/videos.ts@@ -173,9 +173,11 @@ export function isValidPasswordProtectedPrivacy (req: Request, res: Response) {if (privacy !== VideoPrivacy.PASSWORD_PROTECTED) return true- if (!exists(req.body.videoPasswords) && !exists(req.body.passwords)) return fail('Video passwords are missing.')+ if (!exists(req.body.videoPasswords) && !exists(req.body.passwords) && !exists(req.body.password)) {+ return fail('Video passwords are missing.')+ }- const passwords = req.body.videoPasswords || req.body.passwords+ const passwords = req.body.videoPasswords || req.body.passwords || [ req.body.password ]if (passwords.length === 0) return fail('At least one video password is required.')diff --git a/server/core/middlewares/validators/videos/video-passwords.ts b/server/core/middlewares/validators/videos/video-passwords.tsindex e403631cad..aa6fef8d3c 100644--- a/server/core/middlewares/validators/videos/video-passwords.ts+++ b/server/core/middlewares/validators/videos/video-passwords.ts@@ -41,6 +41,8 @@ export const listVideoPasswordValidator = []export const updateVideoPasswordListValidator = [+ isValidVideoIdParam('videoId'),+body('passwords').optional().isArray()@@ -49,22 +51,24 @@ export const updateVideoPasswordListValidator = [async (req: express.Request, res: express.Response, next: express.NextFunction) => {if (areValidationErrors(req, res)) return- if (!await doesVideoExist(req.params.videoId, res)) return- if (!isValidPasswordProtectedPrivacy(req, res)) return+ if (!await checkAddOrUpdatePasswords(req, res)) return- // Check if the user who did the request is able to update video passwords- const user = res.locals.oauth.token.User- if (- !await checkCanManageVideo({- user,- video: res.locals.videoAll,- right: UserRight.UPDATE_ANY_VIDEO,- req,- res,- checkIsLocal: true,- checkIsOwner: false- })- ) return+ return next()+ }+]++export const addVideoPasswordValidator = [+ isValidVideoIdParam('videoId'),++ body('password')+ .isString()+ .withMessage('Video password should be a string')+ .notEmpty()+ .withMessage('Password string should not be empty'),++ async (req: express.Request, res: express.Response, next: express.NextFunction) => {+ if (areValidationErrors(req, res)) return+ if (!await checkAddOrUpdatePasswords(req, res)) returnreturn next()}@@ -88,3 +92,28 @@ export const removeVideoPasswordValidator = [return next()}]++// ---------------------------------------------------------------------------+// Private+// ---------------------------------------------------------------------------++async function checkAddOrUpdatePasswords (req: express.Request, res: express.Response) {+ if (!await doesVideoExist(req.params.videoId, res)) return false+ if (!isValidPasswordProtectedPrivacy(req, res)) return false++ // Check if the user who did the request is able to update video passwords+ const user = res.locals.oauth.token.User+ if (+ !await checkCanManageVideo({+ user,+ video: res.locals.videoAll,+ right: UserRight.UPDATE_ANY_VIDEO,+ req,+ res,+ checkIsLocal: true,+ checkIsOwner: false+ })+ ) return false++ return true+}diff --git a/server/core/models/video/video-password.ts b/server/core/models/video/video-password.tsindex d4636f13f4..9e6e36cbe4 100644--- a/server/core/models/video/video-password.ts+++ b/server/core/models/video/video-password.ts@@ -92,13 +92,17 @@ export class VideoPasswordModel extends SequelizeModel<VideoPasswordModel> {static async addPasswords (passwords: string[], videoId: number, transaction?: Transaction): Promise<void> {for (const password of passwords) {- await VideoPasswordModel.create({- password,- videoId- }, { transaction })+ await VideoPasswordModel.addPassword(password, videoId, transaction)}}+ static async addPassword (password: string, videoId: number, transaction?: Transaction): Promise<VideoPasswordModel> {+ return await VideoPasswordModel.create({+ password,+ videoId+ }, { transaction })+ }+static async deleteAllPasswords (videoId: number, transaction?: Transaction) {await VideoPasswordModel.destroy({where: { videoId },diff --git a/support/doc/api/openapi.yaml b/support/doc/api/openapi.yamlindex 585fa3b4db..deadf2a57e 100644--- a/support/doc/api/openapi.yaml+++ b/support/doc/api/openapi.yaml@@ -4576,6 +4576,7 @@ paths:get:summary: List video passwordsdescription: "**PeerTube >= 6.0**"+ operationId: listVideoPasswordssecurity:- OAuth2:- user@@ -4598,6 +4599,7 @@ paths:put:summary: Update video passwordsdescription: "**PeerTube >= 6.0**"+ operationId: updateVideoPasswordListsecurity:- OAuth2:- user@@ -4618,11 +4620,36 @@ paths:description: successful operation'400':description: video is not password protected+ post:+ summary: Add a video password+ description: "**PeerTube >= 8.0**"+ operationId: addVideoPassword+ security:+ - OAuth2:+ - user+ tags:+ - Video Passwords+ parameters:+ - $ref: '#/components/parameters/idOrUUID'+ requestBody:+ content:+ application/json:+ schema:+ type: object+ properties:+ password:+ type: string+ responses:+ '204':+ description: successful operation+ '400':+ description: video is not password protected/api/v1/videos/{id}/passwords/{videoPasswordId}:delete:summary: Delete a video passworddescription: "**PeerTube >= 6.0**"+ operationId: removeVideoPasswordsecurity:- OAuth2:- user