]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/models/account/user.ts
Fix oauth server module
[github/Chocobozzz/PeerTube.git] / server / models / account / user.ts
1 import * as Sequelize from 'sequelize'
2 import {
3 AllowNull,
4 BeforeCreate,
5 BeforeUpdate,
6 Column,
7 CreatedAt,
8 DataType,
9 Default,
10 DefaultScope,
11 HasMany,
12 HasOne,
13 Is,
14 IsEmail,
15 Model,
16 Scopes,
17 Table,
18 UpdatedAt
19 } from 'sequelize-typescript'
20 import { hasUserRight, USER_ROLE_LABELS, UserRight } from '../../../shared'
21 import { User, UserRole } from '../../../shared/models/users'
22 import {
23 isUserAutoPlayVideoValid,
24 isUserBlockedReasonValid,
25 isUserBlockedValid,
26 isUserNSFWPolicyValid,
27 isUserPasswordValid,
28 isUserRoleValid,
29 isUserUsernameValid,
30 isUserVideoQuotaValid,
31 isUserVideoQuotaDailyValid
32 } from '../../helpers/custom-validators/users'
33 import { comparePassword, cryptPassword } from '../../helpers/peertube-crypto'
34 import { OAuthTokenModel } from '../oauth/oauth-token'
35 import { getSort, throwIfNotValid } from '../utils'
36 import { VideoChannelModel } from '../video/video-channel'
37 import { AccountModel } from './account'
38 import { NSFWPolicyType } from '../../../shared/models/videos/nsfw-policy.type'
39 import { values } from 'lodash'
40 import { NSFW_POLICY_TYPES } from '../../initializers'
41
42 enum ScopeNames {
43 WITH_VIDEO_CHANNEL = 'WITH_VIDEO_CHANNEL'
44 }
45
46 @DefaultScope({
47 include: [
48 {
49 model: () => AccountModel,
50 required: true
51 }
52 ]
53 })
54 @Scopes({
55 [ScopeNames.WITH_VIDEO_CHANNEL]: {
56 include: [
57 {
58 model: () => AccountModel,
59 required: true,
60 include: [ () => VideoChannelModel ]
61 }
62 ]
63 }
64 })
65 @Table({
66 tableName: 'user',
67 indexes: [
68 {
69 fields: [ 'username' ],
70 unique: true
71 },
72 {
73 fields: [ 'email' ],
74 unique: true
75 }
76 ]
77 })
78 export class UserModel extends Model<UserModel> {
79
80 @AllowNull(false)
81 @Is('UserPassword', value => throwIfNotValid(value, isUserPasswordValid, 'user password'))
82 @Column
83 password: string
84
85 @AllowNull(false)
86 @Is('UserPassword', value => throwIfNotValid(value, isUserUsernameValid, 'user name'))
87 @Column
88 username: string
89
90 @AllowNull(false)
91 @IsEmail
92 @Column(DataType.STRING(400))
93 email: string
94
95 @AllowNull(false)
96 @Is('UserNSFWPolicy', value => throwIfNotValid(value, isUserNSFWPolicyValid, 'NSFW policy'))
97 @Column(DataType.ENUM(values(NSFW_POLICY_TYPES)))
98 nsfwPolicy: NSFWPolicyType
99
100 @AllowNull(false)
101 @Default(true)
102 @Is('UserAutoPlayVideo', value => throwIfNotValid(value, isUserAutoPlayVideoValid, 'auto play video boolean'))
103 @Column
104 autoPlayVideo: boolean
105
106 @AllowNull(false)
107 @Default(false)
108 @Is('UserBlocked', value => throwIfNotValid(value, isUserBlockedValid, 'blocked boolean'))
109 @Column
110 blocked: boolean
111
112 @AllowNull(true)
113 @Default(null)
114 @Is('UserBlockedReason', value => throwIfNotValid(value, isUserBlockedReasonValid, 'blocked reason'))
115 @Column
116 blockedReason: string
117
118 @AllowNull(false)
119 @Is('UserRole', value => throwIfNotValid(value, isUserRoleValid, 'role'))
120 @Column
121 role: number
122
123 @AllowNull(false)
124 @Is('UserVideoQuota', value => throwIfNotValid(value, isUserVideoQuotaValid, 'video quota'))
125 @Column(DataType.BIGINT)
126 videoQuota: number
127
128 @AllowNull(false)
129 @Is('UserVideoQuotaDaily', value => throwIfNotValid(value, isUserVideoQuotaDailyValid, 'video quota daily'))
130 @Column(DataType.BIGINT)
131 videoQuotaDaily: number
132
133 @CreatedAt
134 createdAt: Date
135
136 @UpdatedAt
137 updatedAt: Date
138
139 @HasOne(() => AccountModel, {
140 foreignKey: 'userId',
141 onDelete: 'cascade',
142 hooks: true
143 })
144 Account: AccountModel
145
146 @HasMany(() => OAuthTokenModel, {
147 foreignKey: 'userId',
148 onDelete: 'cascade'
149 })
150 OAuthTokens: OAuthTokenModel[]
151
152 @BeforeCreate
153 @BeforeUpdate
154 static cryptPasswordIfNeeded (instance: UserModel) {
155 if (instance.changed('password')) {
156 return cryptPassword(instance.password)
157 .then(hash => {
158 instance.password = hash
159 return undefined
160 })
161 }
162 }
163
164 static countTotal () {
165 return this.count()
166 }
167
168 static listForApi (start: number, count: number, sort: string) {
169 const query = {
170 attributes: {
171 include: [
172 [
173 Sequelize.literal(
174 '(' +
175 'SELECT COALESCE(SUM("size"), 0) FROM ' +
176 '(' +
177 'SELECT MAX("videoFile"."size") AS "size" FROM "videoFile" ' +
178 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' +
179 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
180 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' +
181 'WHERE "account"."userId" = "UserModel"."id" GROUP BY "video"."id"' +
182 ') t' +
183 ')'
184 ),
185 'videoQuotaUsed'
186 ] as any // FIXME: typings
187 ]
188 },
189 offset: start,
190 limit: count,
191 order: getSort(sort)
192 }
193
194 return UserModel.findAndCountAll(query)
195 .then(({ rows, count }) => {
196 return {
197 data: rows,
198 total: count
199 }
200 })
201 }
202
203 static listEmailsWithRight (right: UserRight) {
204 const roles = Object.keys(USER_ROLE_LABELS)
205 .map(k => parseInt(k, 10) as UserRole)
206 .filter(role => hasUserRight(role, right))
207
208 const query = {
209 attribute: [ 'email' ],
210 where: {
211 role: {
212 [Sequelize.Op.in]: roles
213 }
214 }
215 }
216
217 return UserModel.unscoped()
218 .findAll(query)
219 .then(u => u.map(u => u.email))
220 }
221
222 static loadById (id: number) {
223 return UserModel.findById(id)
224 }
225
226 static loadByUsername (username: string) {
227 const query = {
228 where: {
229 username
230 }
231 }
232
233 return UserModel.findOne(query)
234 }
235
236 static loadByUsernameAndPopulateChannels (username: string) {
237 const query = {
238 where: {
239 username
240 }
241 }
242
243 return UserModel.scope(ScopeNames.WITH_VIDEO_CHANNEL).findOne(query)
244 }
245
246 static loadByEmail (email: string) {
247 const query = {
248 where: {
249 email
250 }
251 }
252
253 return UserModel.findOne(query)
254 }
255
256 static loadByUsernameOrEmail (username: string, email?: string) {
257 if (!email) email = username
258
259 const query = {
260 where: {
261 [ Sequelize.Op.or ]: [ { username }, { email } ]
262 }
263 }
264
265 return UserModel.findOne(query)
266 }
267
268 static getOriginalVideoFileTotalFromUser (user: UserModel) {
269 // Don't use sequelize because we need to use a sub query
270 const query = 'SELECT SUM("size") AS "total" FROM ' +
271 '(SELECT MAX("videoFile"."size") AS "size" FROM "videoFile" ' +
272 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' +
273 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
274 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' +
275 'WHERE "account"."userId" = $userId ' +
276 'GROUP BY "video"."id") t'
277
278 const options = {
279 bind: { userId: user.id },
280 type: Sequelize.QueryTypes.SELECT
281 }
282 return UserModel.sequelize.query(query, options)
283 .then(([ { total } ]) => {
284 if (total === null) return 0
285
286 return parseInt(total, 10)
287 })
288 }
289
290 // Returns comulative size of all video files uploaded in the last 24 hours.
291 static getOriginalVideoFileTotalDailyFromUser (user: UserModel) {
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("videoFile"."size") AS "size" FROM "videoFile" ' +
295 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' +
296 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
297 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' +
298 'WHERE "account"."userId" = $userId ' +
299 'AND "video"."createdAt" > now() - interval \'24 hours\'' +
300 'GROUP BY "video"."id") t'
301
302 const options = {
303 bind: { userId: user.id },
304 type: Sequelize.QueryTypes.SELECT
305 }
306 return UserModel.sequelize.query(query, options)
307 .then(([ { total } ]) => {
308 if (total === null) return 0
309
310 return parseInt(total, 10)
311 })
312 }
313
314 static async getStats () {
315 const totalUsers = await UserModel.count()
316
317 return {
318 totalUsers
319 }
320 }
321
322 hasRight (right: UserRight) {
323 return hasUserRight(this.role, right)
324 }
325
326 isPasswordMatch (password: string) {
327 return comparePassword(password, this.password)
328 }
329
330 toFormattedJSON (): User {
331 const videoQuotaUsed = this.get('videoQuotaUsed')
332 const videoQuotaUsedDaily = this.get('videoQuotaUsedDaily')
333
334 const json = {
335 id: this.id,
336 username: this.username,
337 email: this.email,
338 nsfwPolicy: this.nsfwPolicy,
339 autoPlayVideo: this.autoPlayVideo,
340 role: this.role,
341 roleLabel: USER_ROLE_LABELS[ this.role ],
342 videoQuota: this.videoQuota,
343 videoQuotaDaily: this.videoQuotaDaily,
344 createdAt: this.createdAt,
345 blocked: this.blocked,
346 blockedReason: this.blockedReason,
347 account: this.Account.toFormattedJSON(),
348 videoChannels: [],
349 videoQuotaUsed: videoQuotaUsed !== undefined
350 ? parseInt(videoQuotaUsed, 10)
351 : undefined,
352 videoQuotaUsedDaily: videoQuotaUsedDaily !== undefined
353 ? parseInt(videoQuotaUsedDaily, 10)
354 : undefined
355 }
356
357 if (Array.isArray(this.Account.VideoChannels) === true) {
358 json.videoChannels = this.Account.VideoChannels
359 .map(c => c.toFormattedJSON())
360 .sort((v1, v2) => {
361 if (v1.createdAt < v2.createdAt) return -1
362 if (v1.createdAt === v2.createdAt) return 0
363
364 return 1
365 })
366 }
367
368 return json
369 }
370
371 async isAbleToUploadVideo (videoFile: { size: number }) {
372 if (this.videoQuota === -1 && this.videoQuotaDaily === -1) return Promise.resolve(true)
373
374 const [ totalBytes, totalBytesDaily ] = await Promise.all([
375 UserModel.getOriginalVideoFileTotalFromUser(this),
376 UserModel.getOriginalVideoFileTotalDailyFromUser(this)
377 ])
378
379 const uploadedTotal = videoFile.size + totalBytes
380 const uploadedDaily = videoFile.size + totalBytesDaily
381 if (this.videoQuotaDaily === -1) {
382 return uploadedTotal < this.videoQuota
383 }
384 if (this.videoQuota === -1) {
385 return uploadedDaily < this.videoQuotaDaily
386 }
387
388 return (uploadedTotal < this.videoQuota) &&
389 (uploadedDaily < this.videoQuotaDaily)
390 }
391 }