8f7c9b01338a1e13e354766f8ef231a5ec3b0007
[oweals/peertube.git] / server / models / account / user.ts
1 import * as Sequelize from 'sequelize'
2 import { hasUserRight, USER_ROLE_LABELS, UserRight } from '../../../shared'
3 import {
4   comparePassword,
5   cryptPassword,
6   isUserDisplayNSFWValid,
7   isUserPasswordValid,
8   isUserRoleValid,
9   isUserUsernameValid,
10   isUserVideoQuotaValid
11 } from '../../helpers'
12 import { addMethodsToModel, getSort } from '../utils'
13 import { UserAttributes, UserInstance, UserMethods } from './user-interface'
14
15 let User: Sequelize.Model<UserInstance, UserAttributes>
16 let isPasswordMatch: UserMethods.IsPasswordMatch
17 let hasRight: UserMethods.HasRight
18 let toFormattedJSON: UserMethods.ToFormattedJSON
19 let countTotal: UserMethods.CountTotal
20 let getByUsername: UserMethods.GetByUsername
21 let listForApi: UserMethods.ListForApi
22 let loadById: UserMethods.LoadById
23 let loadByUsername: UserMethods.LoadByUsername
24 let loadByUsernameAndPopulateChannels: UserMethods.LoadByUsernameAndPopulateChannels
25 let loadByUsernameOrEmail: UserMethods.LoadByUsernameOrEmail
26 let isAbleToUploadVideo: UserMethods.IsAbleToUploadVideo
27
28 export default function (sequelize: Sequelize.Sequelize, DataTypes: Sequelize.DataTypes) {
29   User = sequelize.define<UserInstance, UserAttributes>('User',
30     {
31       password: {
32         type: DataTypes.STRING,
33         allowNull: false,
34         validate: {
35           passwordValid: value => {
36             const res = isUserPasswordValid(value)
37             if (res === false) throw new Error('Password not valid.')
38           }
39         }
40       },
41       username: {
42         type: DataTypes.STRING,
43         allowNull: false,
44         validate: {
45           usernameValid: value => {
46             const res = isUserUsernameValid(value)
47             if (res === false) throw new Error('Username not valid.')
48           }
49         }
50       },
51       email: {
52         type: DataTypes.STRING(400),
53         allowNull: false,
54         validate: {
55           isEmail: true
56         }
57       },
58       displayNSFW: {
59         type: DataTypes.BOOLEAN,
60         allowNull: false,
61         defaultValue: false,
62         validate: {
63           nsfwValid: value => {
64             const res = isUserDisplayNSFWValid(value)
65             if (res === false) throw new Error('Display NSFW is not valid.')
66           }
67         }
68       },
69       role: {
70         type: DataTypes.INTEGER,
71         allowNull: false,
72         validate: {
73           roleValid: value => {
74             const res = isUserRoleValid(value)
75             if (res === false) throw new Error('Role is not valid.')
76           }
77         }
78       },
79       videoQuota: {
80         type: DataTypes.BIGINT,
81         allowNull: false,
82         validate: {
83           videoQuotaValid: value => {
84             const res = isUserVideoQuotaValid(value)
85             if (res === false) throw new Error('Video quota is not valid.')
86           }
87         }
88       }
89     },
90     {
91       indexes: [
92         {
93           fields: [ 'username' ],
94           unique: true
95         },
96         {
97           fields: [ 'email' ],
98           unique: true
99         }
100       ],
101       hooks: {
102         beforeCreate: beforeCreateOrUpdate,
103         beforeUpdate: beforeCreateOrUpdate
104       }
105     }
106   )
107
108   const classMethods = [
109     associate,
110
111     countTotal,
112     getByUsername,
113     listForApi,
114     loadById,
115     loadByUsername,
116     loadByUsernameAndPopulateChannels,
117     loadByUsernameOrEmail
118   ]
119   const instanceMethods = [
120     hasRight,
121     isPasswordMatch,
122     toFormattedJSON,
123     isAbleToUploadVideo
124   ]
125   addMethodsToModel(User, classMethods, instanceMethods)
126
127   return User
128 }
129
130 function beforeCreateOrUpdate (user: UserInstance) {
131   if (user.changed('password')) {
132     return cryptPassword(user.password)
133       .then(hash => {
134         user.password = hash
135         return undefined
136       })
137   }
138 }
139
140 // ------------------------------ METHODS ------------------------------
141
142 hasRight = function (this: UserInstance, right: UserRight) {
143   return hasUserRight(this.role, right)
144 }
145
146 isPasswordMatch = function (this: UserInstance, password: string) {
147   return comparePassword(password, this.password)
148 }
149
150 toFormattedJSON = function (this: UserInstance) {
151   const json = {
152     id: this.id,
153     username: this.username,
154     email: this.email,
155     displayNSFW: this.displayNSFW,
156     role: this.role,
157     roleLabel: USER_ROLE_LABELS[this.role],
158     videoQuota: this.videoQuota,
159     createdAt: this.createdAt,
160     account: {
161       id: this.Account.id,
162       uuid: this.Account.uuid
163     }
164   }
165
166   if (Array.isArray(this.Account.VideoChannels) === true) {
167     const videoChannels = this.Account.VideoChannels
168       .map(c => c.toFormattedJSON())
169       .sort((v1, v2) => {
170         if (v1.createdAt < v2.createdAt) return -1
171         if (v1.createdAt === v2.createdAt) return 0
172
173         return 1
174       })
175
176     json['videoChannels'] = videoChannels
177   }
178
179   return json
180 }
181
182 isAbleToUploadVideo = function (this: UserInstance, videoFile: Express.Multer.File) {
183   if (this.videoQuota === -1) return Promise.resolve(true)
184
185   return getOriginalVideoFileTotalFromUser(this).then(totalBytes => {
186     return (videoFile.size + totalBytes) < this.videoQuota
187   })
188 }
189
190 // ------------------------------ STATICS ------------------------------
191
192 function associate (models) {
193   User.hasOne(models.Account, {
194     foreignKey: 'userId',
195     onDelete: 'cascade'
196   })
197
198   User.hasMany(models.OAuthToken, {
199     foreignKey: 'userId',
200     onDelete: 'cascade'
201   })
202 }
203
204 countTotal = function () {
205   return this.count()
206 }
207
208 getByUsername = function (username: string) {
209   const query = {
210     where: {
211       username: username
212     },
213     include: [ { model: User['sequelize'].models.Account, required: true } ]
214   }
215
216   return User.findOne(query)
217 }
218
219 listForApi = function (start: number, count: number, sort: string) {
220   const query = {
221     offset: start,
222     limit: count,
223     order: [ getSort(sort) ],
224     include: [ { model: User['sequelize'].models.Account, required: true } ]
225   }
226
227   return User.findAndCountAll(query).then(({ rows, count }) => {
228     return {
229       data: rows,
230       total: count
231     }
232   })
233 }
234
235 loadById = function (id: number) {
236   const options = {
237     include: [ { model: User['sequelize'].models.Account, required: true } ]
238   }
239
240   return User.findById(id, options)
241 }
242
243 loadByUsername = function (username: string) {
244   const query = {
245     where: {
246       username
247     },
248     include: [ { model: User['sequelize'].models.Account, required: true } ]
249   }
250
251   return User.findOne(query)
252 }
253
254 loadByUsernameAndPopulateChannels = function (username: string) {
255   const query = {
256     where: {
257       username
258     },
259     include: [
260       {
261         model: User['sequelize'].models.Account,
262         required: true,
263         include: [ User['sequelize'].models.VideoChannel ]
264       }
265     ]
266   }
267
268   return User.findOne(query)
269 }
270
271 loadByUsernameOrEmail = function (username: string, email: string) {
272   const query = {
273     include: [ { model: User['sequelize'].models.Account, required: true } ],
274     where: {
275       [Sequelize.Op.or]: [ { username }, { email } ]
276     }
277   }
278
279   // FIXME: https://github.com/DefinitelyTyped/DefinitelyTyped/issues/18387
280   return (User as any).findOne(query)
281 }
282
283 // ---------------------------------------------------------------------------
284
285 function getOriginalVideoFileTotalFromUser (user: UserInstance) {
286   // Don't use sequelize because we need to use a sub query
287   const query = 'SELECT SUM("size") AS "total" FROM ' +
288                 '(SELECT MAX("VideoFiles"."size") AS "size" FROM "VideoFiles" ' +
289                 'INNER JOIN "Videos" ON "VideoFiles"."videoId" = "Videos"."id" ' +
290                 'INNER JOIN "VideoChannels" ON "VideoChannels"."id" = "Videos"."channelId" ' +
291                 'INNER JOIN "Accounts" ON "VideoChannels"."accountId" = "Accounts"."id" ' +
292                 'INNER JOIN "Users" ON "Accounts"."userId" = "Users"."id" ' +
293                 'WHERE "Users"."id" = $userId GROUP BY "Videos"."id") t'
294
295   const options = {
296     bind: { userId: user.id },
297     type: Sequelize.QueryTypes.SELECT
298   }
299   return User['sequelize'].query(query, options).then(([ { total } ]) => {
300     if (total === null) return 0
301
302     return parseInt(total, 10)
303   })
304 }