PeerTube/server/models/account/user.ts

305 lines
7.9 KiB
TypeScript
Raw Normal View History

2017-05-22 13:58:25 -05:00
import * as Sequelize from 'sequelize'
2017-11-14 03:57:56 -06:00
import { hasUserRight, USER_ROLE_LABELS, UserRight } from '../../../shared'
2017-05-15 15:22:03 -05:00
import {
comparePassword,
2017-11-14 03:57:56 -06:00
cryptPassword,
isUserDisplayNSFWValid,
2017-05-15 15:22:03 -05:00
isUserPasswordValid,
2017-11-14 03:57:56 -06:00
isUserRoleValid,
2017-05-15 15:22:03 -05:00
isUserUsernameValid,
2017-11-14 03:57:56 -06:00
isUserVideoQuotaValid
2017-06-16 02:45:46 -05:00
} from '../../helpers'
2017-11-14 03:57:56 -06:00
import { addMethodsToModel, getSort } from '../utils'
import { UserAttributes, UserInstance, UserMethods } from './user-interface'
2017-05-22 13:58:25 -05:00
let User: Sequelize.Model<UserInstance, UserAttributes>
let isPasswordMatch: UserMethods.IsPasswordMatch
let hasRight: UserMethods.HasRight
2017-08-25 04:45:31 -05:00
let toFormattedJSON: UserMethods.ToFormattedJSON
2017-05-22 13:58:25 -05:00
let countTotal: UserMethods.CountTotal
let getByUsername: UserMethods.GetByUsername
let listForApi: UserMethods.ListForApi
let loadById: UserMethods.LoadById
let loadByUsername: UserMethods.LoadByUsername
2017-10-24 12:41:09 -05:00
let loadByUsernameAndPopulateChannels: UserMethods.LoadByUsernameAndPopulateChannels
2017-05-22 13:58:25 -05:00
let loadByUsernameOrEmail: UserMethods.LoadByUsernameOrEmail
2017-09-04 13:07:54 -05:00
let isAbleToUploadVideo: UserMethods.IsAbleToUploadVideo
2017-05-22 13:58:25 -05:00
2017-06-11 10:35:32 -05:00
export default function (sequelize: Sequelize.Sequelize, DataTypes: Sequelize.DataTypes) {
User = sequelize.define<UserInstance, UserAttributes>('User',
2016-12-11 14:50:51 -06:00
{
password: {
2016-12-28 08:49:23 -06:00
type: DataTypes.STRING,
allowNull: false,
validate: {
2017-07-11 10:04:57 -05:00
passwordValid: value => {
2017-05-15 15:22:03 -05:00
const res = isUserPasswordValid(value)
2016-12-28 08:49:23 -06:00
if (res === false) throw new Error('Password not valid.')
}
}
2016-12-11 14:50:51 -06:00
},
username: {
2016-12-28 08:49:23 -06:00
type: DataTypes.STRING,
allowNull: false,
validate: {
2017-07-11 10:04:57 -05:00
usernameValid: value => {
2017-05-15 15:22:03 -05:00
const res = isUserUsernameValid(value)
2016-12-28 08:49:23 -06:00
if (res === false) throw new Error('Username not valid.')
}
}
2016-12-11 14:50:51 -06:00
},
2017-02-18 02:29:59 -06:00
email: {
2017-02-18 04:56:28 -06:00
type: DataTypes.STRING(400),
2017-02-18 02:29:59 -06:00
allowNull: false,
validate: {
isEmail: true
}
},
2017-04-03 14:24:36 -05:00
displayNSFW: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
validate: {
2017-07-11 10:04:57 -05:00
nsfwValid: value => {
2017-05-15 15:22:03 -05:00
const res = isUserDisplayNSFWValid(value)
2017-04-03 14:24:36 -05:00
if (res === false) throw new Error('Display NSFW is not valid.')
}
}
},
2016-12-11 14:50:51 -06:00
role: {
type: DataTypes.INTEGER,
allowNull: false,
validate: {
roleValid: value => {
const res = isUserRoleValid(value)
if (res === false) throw new Error('Role is not valid.')
}
}
2017-09-04 13:07:54 -05:00
},
videoQuota: {
type: DataTypes.BIGINT,
allowNull: false,
validate: {
videoQuotaValid: value => {
const res = isUserVideoQuotaValid(value)
if (res === false) throw new Error('Video quota is not valid.')
}
}
2016-12-11 14:50:51 -06:00
}
},
{
2016-12-29 02:33:28 -06:00
indexes: [
{
2017-02-16 12:24:34 -06:00
fields: [ 'username' ],
unique: true
2017-02-18 02:29:59 -06:00
},
{
fields: [ 'email' ],
unique: true
2016-12-29 02:33:28 -06:00
}
],
2016-12-11 14:50:51 -06:00
hooks: {
beforeCreate: beforeCreateOrUpdate,
beforeUpdate: beforeCreateOrUpdate
}
}
)
2017-05-22 13:58:25 -05:00
const classMethods = [
associate,
countTotal,
getByUsername,
listForApi,
loadById,
loadByUsername,
2017-10-24 12:41:09 -05:00
loadByUsernameAndPopulateChannels,
2017-05-22 13:58:25 -05:00
loadByUsernameOrEmail
]
const instanceMethods = [
hasRight,
2017-05-22 13:58:25 -05:00
isPasswordMatch,
2017-08-25 04:45:31 -05:00
toFormattedJSON,
2017-09-04 13:07:54 -05:00
isAbleToUploadVideo
2017-05-22 13:58:25 -05:00
]
addMethodsToModel(User, classMethods, instanceMethods)
2016-12-11 14:50:51 -06:00
return User
}
2017-06-10 15:15:25 -05:00
function beforeCreateOrUpdate (user: UserInstance) {
if (user.changed('password')) {
return cryptPassword(user.password)
.then(hash => {
user.password = hash
return undefined
})
}
2016-12-11 14:50:51 -06:00
}
2016-08-25 10:57:37 -05:00
// ------------------------------ METHODS ------------------------------
hasRight = function (this: UserInstance, right: UserRight) {
return hasUserRight(this.role, right)
}
isPasswordMatch = function (this: UserInstance, password: string) {
return comparePassword(password, this.password)
2016-08-25 10:57:37 -05:00
}
2017-08-25 04:45:31 -05:00
toFormattedJSON = function (this: UserInstance) {
2017-10-24 12:41:09 -05:00
const json = {
2016-12-11 14:50:51 -06:00
id: this.id,
2016-08-25 10:57:37 -05:00
username: this.username,
2017-02-18 02:29:59 -06:00
email: this.email,
2017-04-03 14:24:36 -05:00
displayNSFW: this.displayNSFW,
role: this.role,
roleLabel: USER_ROLE_LABELS[this.role],
2017-09-04 13:07:54 -05:00
videoQuota: this.videoQuota,
2017-10-24 12:41:09 -05:00
createdAt: this.createdAt,
2017-11-10 07:48:08 -06:00
account: {
2017-11-09 10:51:58 -06:00
id: this.Account.id,
uuid: this.Account.uuid
2017-10-24 12:41:09 -05:00
}
2016-08-25 10:57:37 -05:00
}
2017-10-24 12:41:09 -05:00
2017-11-09 10:51:58 -06:00
if (Array.isArray(this.Account.VideoChannels) === true) {
const videoChannels = this.Account.VideoChannels
2017-10-24 12:41:09 -05:00
.map(c => c.toFormattedJSON())
.sort((v1, v2) => {
if (v1.createdAt < v2.createdAt) return -1
if (v1.createdAt === v2.createdAt) return 0
return 1
})
json['videoChannels'] = videoChannels
}
return json
2016-08-25 10:57:37 -05:00
}
Add ability for an administrator to remove any video (#61) * Add ability for an admin to remove every video on the pod. * Server: add BlacklistedVideos relation. * Server: Insert in BlacklistedVideos relation upon deletion of a video. * Server: Modify BlacklistedVideos schema to add Pod id information. * Server: Moving insertion of a blacklisted video from the `afterDestroy` hook into the process of deletion of a video. To avoid inserting a video when it is removed on its origin pod. When a video is removed on its origin pod, the `afterDestroy` hook is fire, but no request is made on the delete('/:videoId') interface. Hence, we insert into `BlacklistedVideos` only on request on delete('/:videoId') (if requirements for insertion are met). * Server: Add removeVideoFromBlacklist hook on deletion of a video. We are going to proceed in another way :). We will add a new route : /:videoId/blacklist to blacklist a video. We do not blacklist a video upon its deletion now (to distinguish a video blacklist from a regular video delete) When we blacklist a video, the video remains in the DB, so we don't have any concern about its update. It just doesn't appear in the video list. When we remove a video, we then have to remove it from the blacklist too. We could also remove a video from the blacklist to 'unremove' it and make it appear again in the video list (will be another feature). * Server: Add handler for new route post(/:videoId/blacklist) * Client: Add isBlacklistable method * Client: Update isRemovableBy method. * Client: Move 'Delete video' feature from the video-list to the video-watch module. * Server: Exclude blacklisted videos from the video list * Server: Use findAll() in BlacklistedVideos.list() method * Server: Fix addVideoToBlacklist function. * Client: Add blacklist feature. * Server: Use JavaScript Standard Style. * Server: In checkUserCanDeleteVideo, move the callback call inside the db callback function * Server: Modify BlacklistVideo relation * Server: Modifiy Videos methods. * Server: Add checkVideoIsBlacklistable method * Server: Rewrite addVideoToBlacklist method * Server: Fix checkVideoIsBlacklistable method * Server: Add return to addVideoToBlacklist method
2017-04-26 14:22:10 -05:00
2017-09-04 13:07:54 -05:00
isAbleToUploadVideo = function (this: UserInstance, videoFile: Express.Multer.File) {
if (this.videoQuota === -1) return Promise.resolve(true)
return getOriginalVideoFileTotalFromUser(this).then(totalBytes => {
return (videoFile.size + totalBytes) < this.videoQuota
})
}
2016-08-25 10:57:37 -05:00
// ------------------------------ STATICS ------------------------------
2016-12-11 14:50:51 -06:00
function associate (models) {
2017-11-09 10:51:58 -06:00
User.hasOne(models.Account, {
foreignKey: 'userId',
onDelete: 'cascade'
})
2017-05-22 13:58:25 -05:00
User.hasMany(models.OAuthToken, {
2016-12-11 14:50:51 -06:00
foreignKey: 'userId',
onDelete: 'cascade'
})
}
countTotal = function () {
return this.count()
}
2017-06-10 15:15:25 -05:00
getByUsername = function (username: string) {
2016-12-11 14:50:51 -06:00
const query = {
where: {
username: username
2017-10-24 12:41:09 -05:00
},
2017-11-09 10:51:58 -06:00
include: [ { model: User['sequelize'].models.Account, required: true } ]
2016-12-11 14:50:51 -06:00
}
2017-05-22 13:58:25 -05:00
return User.findOne(query)
}
listForApi = function (start: number, count: number, sort: string) {
2016-12-11 14:50:51 -06:00
const query = {
offset: start,
limit: count,
2017-10-24 12:41:09 -05:00
order: [ getSort(sort) ],
2017-11-09 10:51:58 -06:00
include: [ { model: User['sequelize'].models.Account, required: true } ]
2016-12-11 14:50:51 -06:00
}
return User.findAndCountAll(query).then(({ rows, count }) => {
return {
data: rows,
total: count
}
2016-12-11 14:50:51 -06:00
})
}
loadById = function (id: number) {
2017-10-24 12:41:09 -05:00
const options = {
2017-11-09 10:51:58 -06:00
include: [ { model: User['sequelize'].models.Account, required: true } ]
2017-10-24 12:41:09 -05:00
}
return User.findById(id, options)
}
loadByUsername = function (username: string) {
2016-12-11 14:50:51 -06:00
const query = {
where: {
2017-08-25 11:36:49 -05:00
username
2017-10-24 12:41:09 -05:00
},
2017-11-09 10:51:58 -06:00
include: [ { model: User['sequelize'].models.Account, required: true } ]
2017-10-24 12:41:09 -05:00
}
return User.findOne(query)
}
loadByUsernameAndPopulateChannels = function (username: string) {
const query = {
where: {
username
},
include: [
{
2017-11-09 10:51:58 -06:00
model: User['sequelize'].models.Account,
2017-10-24 12:41:09 -05:00
required: true,
include: [ User['sequelize'].models.VideoChannel ]
}
]
2016-12-11 14:50:51 -06:00
}
return User.findOne(query)
}
2017-02-18 02:29:59 -06:00
loadByUsernameOrEmail = function (username: string, email: string) {
2017-02-18 02:29:59 -06:00
const query = {
2017-11-09 10:51:58 -06:00
include: [ { model: User['sequelize'].models.Account, required: true } ],
2017-02-18 02:29:59 -06:00
where: {
2017-10-26 09:59:02 -05:00
[Sequelize.Op.or]: [ { username }, { email } ]
2017-02-18 02:29:59 -06:00
}
}
2017-08-25 11:36:49 -05:00
// FIXME: https://github.com/DefinitelyTyped/DefinitelyTyped/issues/18387
return (User as any).findOne(query)
2017-02-18 02:29:59 -06:00
}
2017-09-04 13:07:54 -05:00
// ---------------------------------------------------------------------------
function getOriginalVideoFileTotalFromUser (user: UserInstance) {
2017-10-24 12:41:09 -05:00
// Don't use sequelize because we need to use a sub query
const query = 'SELECT SUM("size") AS "total" FROM ' +
'(SELECT MAX("VideoFiles"."size") AS "size" FROM "VideoFiles" ' +
'INNER JOIN "Videos" ON "VideoFiles"."videoId" = "Videos"."id" ' +
2017-10-24 12:41:09 -05:00
'INNER JOIN "VideoChannels" ON "VideoChannels"."id" = "Videos"."channelId" ' +
2017-11-10 07:48:08 -06:00
'INNER JOIN "Accounts" ON "VideoChannels"."accountId" = "Accounts"."id" ' +
2017-11-09 10:51:58 -06:00
'INNER JOIN "Users" ON "Accounts"."userId" = "Users"."id" ' +
'WHERE "Users"."id" = $userId GROUP BY "Videos"."id") t'
const options = {
bind: { userId: user.id },
type: Sequelize.QueryTypes.SELECT
2017-09-04 13:07:54 -05:00
}
return User['sequelize'].query(query, options).then(([ { total } ]) => {
if (total === null) return 0
2017-09-04 13:07:54 -05:00
return parseInt(total, 10)
})
2017-09-04 13:07:54 -05:00
}