Merge branch 'feature/design' into develop
[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: this.Account.toFormattedJSON()
161   }
162
163   if (Array.isArray(this.Account.VideoChannels) === true) {
164     const videoChannels = this.Account.VideoChannels
165       .map(c => c.toFormattedJSON())
166       .sort((v1, v2) => {
167         if (v1.createdAt < v2.createdAt) return -1
168         if (v1.createdAt === v2.createdAt) return 0
169
170         return 1
171       })
172
173     json['videoChannels'] = videoChannels
174   }
175
176   return json
177 }
178
179 isAbleToUploadVideo = function (this: UserInstance, videoFile: Express.Multer.File) {
180   if (this.videoQuota === -1) return Promise.resolve(true)
181
182   return getOriginalVideoFileTotalFromUser(this).then(totalBytes => {
183     return (videoFile.size + totalBytes) < this.videoQuota
184   })
185 }
186
187 // ------------------------------ STATICS ------------------------------
188
189 function associate (models) {
190   User.hasOne(models.Account, {
191     foreignKey: 'userId',
192     onDelete: 'cascade'
193   })
194
195   User.hasMany(models.OAuthToken, {
196     foreignKey: 'userId',
197     onDelete: 'cascade'
198   })
199 }
200
201 countTotal = function () {
202   return this.count()
203 }
204
205 getByUsername = function (username: string) {
206   const query = {
207     where: {
208       username: username
209     },
210     include: [ { model: User['sequelize'].models.Account, required: true } ]
211   }
212
213   return User.findOne(query)
214 }
215
216 listForApi = function (start: number, count: number, sort: string) {
217   const query = {
218     offset: start,
219     limit: count,
220     order: [ getSort(sort) ],
221     include: [ { model: User['sequelize'].models.Account, required: true } ]
222   }
223
224   return User.findAndCountAll(query).then(({ rows, count }) => {
225     return {
226       data: rows,
227       total: count
228     }
229   })
230 }
231
232 loadById = function (id: number) {
233   const options = {
234     include: [ { model: User['sequelize'].models.Account, required: true } ]
235   }
236
237   return User.findById(id, options)
238 }
239
240 loadByUsername = function (username: string) {
241   const query = {
242     where: {
243       username
244     },
245     include: [ { model: User['sequelize'].models.Account, required: true } ]
246   }
247
248   return User.findOne(query)
249 }
250
251 loadByUsernameAndPopulateChannels = function (username: string) {
252   const query = {
253     where: {
254       username
255     },
256     include: [
257       {
258         model: User['sequelize'].models.Account,
259         required: true,
260         include: [ User['sequelize'].models.VideoChannel ]
261       }
262     ]
263   }
264
265   return User.findOne(query)
266 }
267
268 loadByUsernameOrEmail = function (username: string, email: string) {
269   const query = {
270     include: [ { model: User['sequelize'].models.Account, required: true } ],
271     where: {
272       [Sequelize.Op.or]: [ { username }, { email } ]
273     }
274   }
275
276   // FIXME: https://github.com/DefinitelyTyped/DefinitelyTyped/issues/18387
277   return (User as any).findOne(query)
278 }
279
280 // ---------------------------------------------------------------------------
281
282 function getOriginalVideoFileTotalFromUser (user: UserInstance) {
283   // Don't use sequelize because we need to use a sub query
284   const query = 'SELECT SUM("size") AS "total" FROM ' +
285                 '(SELECT MAX("VideoFiles"."size") AS "size" FROM "VideoFiles" ' +
286                 'INNER JOIN "Videos" ON "VideoFiles"."videoId" = "Videos"."id" ' +
287                 'INNER JOIN "VideoChannels" ON "VideoChannels"."id" = "Videos"."channelId" ' +
288                 'INNER JOIN "Accounts" ON "VideoChannels"."accountId" = "Accounts"."id" ' +
289                 'INNER JOIN "Users" ON "Accounts"."userId" = "Users"."id" ' +
290                 'WHERE "Users"."id" = $userId GROUP BY "Videos"."id") t'
291
292   const options = {
293     bind: { userId: user.id },
294     type: Sequelize.QueryTypes.SELECT
295   }
296   return User['sequelize'].query(query, options).then(([ { total } ]) => {
297     if (total === null) return 0
298
299     return parseInt(total, 10)
300   })
301 }