aboutsummaryrefslogtreecommitdiffhomepage
path: root/server/middlewares/validators/shared/video-passwords.ts
blob: efcc95dc432883e0af4558fb031b0cf6300341ec (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import express from 'express'
import { HttpStatusCode, UserRight, VideoPrivacy } from '@shared/models'
import { forceNumber } from '@shared/core-utils'
import { VideoPasswordModel } from '@server/models/video/video-password'
import { header } from 'express-validator'
import { getVideoWithAttributes } from '@server/helpers/video'

function isValidVideoPasswordHeader () {
  return header('x-peertube-video-password')
    .optional()
    .isString()
}

function checkVideoIsPasswordProtected (res: express.Response) {
  const video = getVideoWithAttributes(res)
  if (video.privacy !== VideoPrivacy.PASSWORD_PROTECTED) {
    res.fail({
      status: HttpStatusCode.BAD_REQUEST_400,
      message: 'Video is not password protected'
    })
    return false
  }

  return true
}

async function doesVideoPasswordExist (idArg: number | string, res: express.Response) {
  const video = getVideoWithAttributes(res)
  const id = forceNumber(idArg)
  const videoPassword = await VideoPasswordModel.loadByIdAndVideo({ id, videoId: video.id })

  if (!videoPassword) {
    res.fail({
      status: HttpStatusCode.NOT_FOUND_404,
      message: 'Video password not found'
    })
    return false
  }

  res.locals.videoPassword = videoPassword

  return true
}

async function isVideoPasswordDeletable (res: express.Response) {
  const user = res.locals.oauth.token.User
  const userAccount = user.Account
  const video = res.locals.videoAll

  // Check if the user who did the request is able to delete the video passwords
  if (
    user.hasRight(UserRight.UPDATE_ANY_VIDEO) === false && // Not a moderator
    video.VideoChannel.accountId !== userAccount.id // Not the video owner
  ) {
    res.fail({
      status: HttpStatusCode.FORBIDDEN_403,
      message: 'Cannot remove passwords of another user\'s video'
    })
    return false
  }

  const passwordCount = await VideoPasswordModel.countByVideoId(video.id)

  if (passwordCount <= 1) {
    res.fail({
      status: HttpStatusCode.BAD_REQUEST_400,
      message: 'Cannot delete the last password of the protected video'
    })
    return false
  }

  return true
}

export {
  isValidVideoPasswordHeader,
  checkVideoIsPasswordProtected as isVideoPasswordProtected,
  doesVideoPasswordExist,
  isVideoPasswordDeletable
}