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