]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/models/account/user.ts
Use lower instead of ilike to login users
[github/Chocobozzz/PeerTube.git] / server / models / account / user.ts
1 import { FindOptions, literal, Op, QueryTypes, where, fn, col } from 'sequelize'
2 import {
3 AfterDestroy,
4 AfterUpdate,
5 AllowNull,
6 BeforeCreate,
7 BeforeUpdate,
8 Column,
9 CreatedAt,
10 DataType,
11 Default,
12 DefaultScope,
13 HasMany,
14 HasOne,
15 Is,
16 IsEmail,
17 Model,
18 Scopes,
19 Table,
20 UpdatedAt
21 } from 'sequelize-typescript'
22 import { hasUserRight, MyUser, USER_ROLE_LABELS, UserRight, VideoPlaylistType, VideoPrivacy } from '../../../shared'
23 import { User, UserRole } from '../../../shared/models/users'
24 import {
25 isNoInstanceConfigWarningModal,
26 isNoWelcomeModal,
27 isUserAdminFlagsValid,
28 isUserAutoPlayNextVideoPlaylistValid,
29 isUserAutoPlayNextVideoValid,
30 isUserAutoPlayVideoValid,
31 isUserBlockedReasonValid,
32 isUserBlockedValid,
33 isUserEmailVerifiedValid,
34 isUserNSFWPolicyValid,
35 isUserPasswordValid,
36 isUserRoleValid,
37 isUserUsernameValid,
38 isUserVideoLanguages,
39 isUserVideoQuotaDailyValid,
40 isUserVideoQuotaValid,
41 isUserVideosHistoryEnabledValid,
42 isUserWebTorrentEnabledValid
43 } from '../../helpers/custom-validators/users'
44 import { comparePassword, cryptPassword } from '../../helpers/peertube-crypto'
45 import { OAuthTokenModel } from '../oauth/oauth-token'
46 import { getSort, throwIfNotValid } from '../utils'
47 import { VideoChannelModel } from '../video/video-channel'
48 import { VideoPlaylistModel } from '../video/video-playlist'
49 import { AccountModel } from './account'
50 import { NSFWPolicyType } from '../../../shared/models/videos/nsfw-policy.type'
51 import { values } from 'lodash'
52 import { DEFAULT_THEME_NAME, DEFAULT_USER_THEME_NAME, NSFW_POLICY_TYPES } from '../../initializers/constants'
53 import { clearCacheByUserId } from '../../lib/oauth-model'
54 import { UserNotificationSettingModel } from './user-notification-setting'
55 import { VideoModel } from '../video/video'
56 import { ActorModel } from '../activitypub/actor'
57 import { ActorFollowModel } from '../activitypub/actor-follow'
58 import { VideoImportModel } from '../video/video-import'
59 import { UserAdminFlag } from '../../../shared/models/users/user-flag.model'
60 import { isThemeNameValid } from '../../helpers/custom-validators/plugins'
61 import { getThemeOrDefault } from '../../lib/plugins/theme-utils'
62 import * as Bluebird from 'bluebird'
63 import {
64 MMyUserFormattable,
65 MUserDefault,
66 MUserFormattable,
67 MUserId,
68 MUserNotifSettingChannelDefault,
69 MUserWithNotificationSetting,
70 MVideoFullLight
71 } from '@server/typings/models'
72
73 enum ScopeNames {
74 FOR_ME_API = 'FOR_ME_API'
75 }
76
77 @DefaultScope(() => ({
78 include: [
79 {
80 model: AccountModel,
81 required: true
82 },
83 {
84 model: UserNotificationSettingModel,
85 required: true
86 }
87 ]
88 }))
89 @Scopes(() => ({
90 [ScopeNames.FOR_ME_API]: {
91 include: [
92 {
93 model: AccountModel,
94 include: [
95 {
96 model: VideoChannelModel
97 },
98 {
99 attributes: [ 'id', 'name', 'type' ],
100 model: VideoPlaylistModel.unscoped(),
101 required: true,
102 where: {
103 type: {
104 [ Op.ne ]: VideoPlaylistType.REGULAR
105 }
106 }
107 }
108 ]
109 },
110 {
111 model: UserNotificationSettingModel,
112 required: true
113 }
114 ]
115 }
116 }))
117 @Table({
118 tableName: 'user',
119 indexes: [
120 {
121 fields: [ 'username' ],
122 unique: true
123 },
124 {
125 fields: [ 'email' ],
126 unique: true
127 }
128 ]
129 })
130 export class UserModel extends Model<UserModel> {
131
132 @AllowNull(false)
133 @Is('UserPassword', value => throwIfNotValid(value, isUserPasswordValid, 'user password'))
134 @Column
135 password: string
136
137 @AllowNull(false)
138 @Is('UserPassword', value => throwIfNotValid(value, isUserUsernameValid, 'user name'))
139 @Column
140 username: string
141
142 @AllowNull(false)
143 @IsEmail
144 @Column(DataType.STRING(400))
145 email: string
146
147 @AllowNull(true)
148 @IsEmail
149 @Column(DataType.STRING(400))
150 pendingEmail: string
151
152 @AllowNull(true)
153 @Default(null)
154 @Is('UserEmailVerified', value => throwIfNotValid(value, isUserEmailVerifiedValid, 'email verified boolean', true))
155 @Column
156 emailVerified: boolean
157
158 @AllowNull(false)
159 @Is('UserNSFWPolicy', value => throwIfNotValid(value, isUserNSFWPolicyValid, 'NSFW policy'))
160 @Column(DataType.ENUM(...values(NSFW_POLICY_TYPES)))
161 nsfwPolicy: NSFWPolicyType
162
163 @AllowNull(false)
164 @Default(true)
165 @Is('UserWebTorrentEnabled', value => throwIfNotValid(value, isUserWebTorrentEnabledValid, 'WebTorrent enabled'))
166 @Column
167 webTorrentEnabled: boolean
168
169 @AllowNull(false)
170 @Default(true)
171 @Is('UserVideosHistoryEnabled', value => throwIfNotValid(value, isUserVideosHistoryEnabledValid, 'Videos history enabled'))
172 @Column
173 videosHistoryEnabled: boolean
174
175 @AllowNull(false)
176 @Default(true)
177 @Is('UserAutoPlayVideo', value => throwIfNotValid(value, isUserAutoPlayVideoValid, 'auto play video boolean'))
178 @Column
179 autoPlayVideo: boolean
180
181 @AllowNull(false)
182 @Default(false)
183 @Is('UserAutoPlayNextVideo', value => throwIfNotValid(value, isUserAutoPlayNextVideoValid, 'auto play next video boolean'))
184 @Column
185 autoPlayNextVideo: boolean
186
187 @AllowNull(false)
188 @Default(true)
189 @Is('UserAutoPlayNextVideoPlaylist', value => throwIfNotValid(value, isUserAutoPlayNextVideoPlaylistValid, 'auto play next video for playlists boolean'))
190 @Column
191 autoPlayNextVideoPlaylist: boolean
192
193 @AllowNull(true)
194 @Default(null)
195 @Is('UserVideoLanguages', value => throwIfNotValid(value, isUserVideoLanguages, 'video languages'))
196 @Column(DataType.ARRAY(DataType.STRING))
197 videoLanguages: string[]
198
199 @AllowNull(false)
200 @Default(UserAdminFlag.NONE)
201 @Is('UserAdminFlags', value => throwIfNotValid(value, isUserAdminFlagsValid, 'user admin flags'))
202 @Column
203 adminFlags?: UserAdminFlag
204
205 @AllowNull(false)
206 @Default(false)
207 @Is('UserBlocked', value => throwIfNotValid(value, isUserBlockedValid, 'blocked boolean'))
208 @Column
209 blocked: boolean
210
211 @AllowNull(true)
212 @Default(null)
213 @Is('UserBlockedReason', value => throwIfNotValid(value, isUserBlockedReasonValid, 'blocked reason', true))
214 @Column
215 blockedReason: string
216
217 @AllowNull(false)
218 @Is('UserRole', value => throwIfNotValid(value, isUserRoleValid, 'role'))
219 @Column
220 role: number
221
222 @AllowNull(false)
223 @Is('UserVideoQuota', value => throwIfNotValid(value, isUserVideoQuotaValid, 'video quota'))
224 @Column(DataType.BIGINT)
225 videoQuota: number
226
227 @AllowNull(false)
228 @Is('UserVideoQuotaDaily', value => throwIfNotValid(value, isUserVideoQuotaDailyValid, 'video quota daily'))
229 @Column(DataType.BIGINT)
230 videoQuotaDaily: number
231
232 @AllowNull(false)
233 @Default(DEFAULT_THEME_NAME)
234 @Is('UserTheme', value => throwIfNotValid(value, isThemeNameValid, 'theme'))
235 @Column
236 theme: string
237
238 @AllowNull(false)
239 @Default(false)
240 @Is(
241 'UserNoInstanceConfigWarningModal',
242 value => throwIfNotValid(value, isNoInstanceConfigWarningModal, 'no instance config warning modal')
243 )
244 @Column
245 noInstanceConfigWarningModal: boolean
246
247 @AllowNull(false)
248 @Default(false)
249 @Is(
250 'UserNoInstanceConfigWarningModal',
251 value => throwIfNotValid(value, isNoWelcomeModal, 'no welcome modal')
252 )
253 @Column
254 noWelcomeModal: boolean
255
256 @CreatedAt
257 createdAt: Date
258
259 @UpdatedAt
260 updatedAt: Date
261
262 @HasOne(() => AccountModel, {
263 foreignKey: 'userId',
264 onDelete: 'cascade',
265 hooks: true
266 })
267 Account: AccountModel
268
269 @HasOne(() => UserNotificationSettingModel, {
270 foreignKey: 'userId',
271 onDelete: 'cascade',
272 hooks: true
273 })
274 NotificationSetting: UserNotificationSettingModel
275
276 @HasMany(() => VideoImportModel, {
277 foreignKey: 'userId',
278 onDelete: 'cascade'
279 })
280 VideoImports: VideoImportModel[]
281
282 @HasMany(() => OAuthTokenModel, {
283 foreignKey: 'userId',
284 onDelete: 'cascade'
285 })
286 OAuthTokens: OAuthTokenModel[]
287
288 @BeforeCreate
289 @BeforeUpdate
290 static cryptPasswordIfNeeded (instance: UserModel) {
291 if (instance.changed('password')) {
292 return cryptPassword(instance.password)
293 .then(hash => {
294 instance.password = hash
295 return undefined
296 })
297 }
298 }
299
300 @AfterUpdate
301 @AfterDestroy
302 static removeTokenCache (instance: UserModel) {
303 return clearCacheByUserId(instance.id)
304 }
305
306 static countTotal () {
307 return this.count()
308 }
309
310 static listForApi (start: number, count: number, sort: string, search?: string) {
311 let where = undefined
312 if (search) {
313 where = {
314 [Op.or]: [
315 {
316 email: {
317 [Op.iLike]: '%' + search + '%'
318 }
319 },
320 {
321 username: {
322 [ Op.iLike ]: '%' + search + '%'
323 }
324 }
325 ]
326 }
327 }
328
329 const query: FindOptions = {
330 attributes: {
331 include: [
332 [
333 literal(
334 '(' +
335 'SELECT COALESCE(SUM("size"), 0) ' +
336 'FROM (' +
337 'SELECT MAX("videoFile"."size") AS "size" FROM "videoFile" ' +
338 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' +
339 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
340 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' +
341 'WHERE "account"."userId" = "UserModel"."id" GROUP BY "video"."id"' +
342 ') t' +
343 ')'
344 ),
345 'videoQuotaUsed'
346 ]
347 ]
348 },
349 offset: start,
350 limit: count,
351 order: getSort(sort),
352 where
353 }
354
355 return UserModel.findAndCountAll(query)
356 .then(({ rows, count }) => {
357 return {
358 data: rows,
359 total: count
360 }
361 })
362 }
363
364 static listWithRight (right: UserRight): Bluebird<MUserDefault[]> {
365 const roles = Object.keys(USER_ROLE_LABELS)
366 .map(k => parseInt(k, 10) as UserRole)
367 .filter(role => hasUserRight(role, right))
368
369 const query = {
370 where: {
371 role: {
372 [Op.in]: roles
373 }
374 }
375 }
376
377 return UserModel.findAll(query)
378 }
379
380 static listUserSubscribersOf (actorId: number): Bluebird<MUserWithNotificationSetting[]> {
381 const query = {
382 include: [
383 {
384 model: UserNotificationSettingModel.unscoped(),
385 required: true
386 },
387 {
388 attributes: [ 'userId' ],
389 model: AccountModel.unscoped(),
390 required: true,
391 include: [
392 {
393 attributes: [ ],
394 model: ActorModel.unscoped(),
395 required: true,
396 where: {
397 serverId: null
398 },
399 include: [
400 {
401 attributes: [ ],
402 as: 'ActorFollowings',
403 model: ActorFollowModel.unscoped(),
404 required: true,
405 where: {
406 targetActorId: actorId
407 }
408 }
409 ]
410 }
411 ]
412 }
413 ]
414 }
415
416 return UserModel.unscoped().findAll(query)
417 }
418
419 static listByUsernames (usernames: string[]): Bluebird<MUserDefault[]> {
420 const query = {
421 where: {
422 username: usernames
423 }
424 }
425
426 return UserModel.findAll(query)
427 }
428
429 static loadById (id: number): Bluebird<MUserDefault> {
430 return UserModel.findByPk(id)
431 }
432
433 static loadByUsername (username: string): Bluebird<MUserDefault> {
434 const query = {
435 where: {
436 username: { [ Op.iLike ]: username }
437 }
438 }
439
440 return UserModel.findOne(query)
441 }
442
443 static loadForMeAPI (username: string): Bluebird<MUserNotifSettingChannelDefault> {
444 const query = {
445 where: {
446 username: { [ Op.iLike ]: username }
447 }
448 }
449
450 return UserModel.scope(ScopeNames.FOR_ME_API).findOne(query)
451 }
452
453 static loadByEmail (email: string): Bluebird<MUserDefault> {
454 const query = {
455 where: {
456 email
457 }
458 }
459
460 return UserModel.findOne(query)
461 }
462
463 static loadByUsernameOrEmail (username: string, email?: string): Bluebird<MUserDefault> {
464 if (!email) email = username
465
466 const query = {
467 where: {
468 [ Op.or ]: [
469 where(fn('lower', col('username')), fn('lower', username)),
470
471 { email }
472 ]
473 }
474 }
475
476 return UserModel.findOne(query)
477 }
478
479 static loadByVideoId (videoId: number): Bluebird<MUserDefault> {
480 const query = {
481 include: [
482 {
483 required: true,
484 attributes: [ 'id' ],
485 model: AccountModel.unscoped(),
486 include: [
487 {
488 required: true,
489 attributes: [ 'id' ],
490 model: VideoChannelModel.unscoped(),
491 include: [
492 {
493 required: true,
494 attributes: [ 'id' ],
495 model: VideoModel.unscoped(),
496 where: {
497 id: videoId
498 }
499 }
500 ]
501 }
502 ]
503 }
504 ]
505 }
506
507 return UserModel.findOne(query)
508 }
509
510 static loadByVideoImportId (videoImportId: number): Bluebird<MUserDefault> {
511 const query = {
512 include: [
513 {
514 required: true,
515 attributes: [ 'id' ],
516 model: VideoImportModel.unscoped(),
517 where: {
518 id: videoImportId
519 }
520 }
521 ]
522 }
523
524 return UserModel.findOne(query)
525 }
526
527 static loadByChannelActorId (videoChannelActorId: number): Bluebird<MUserDefault> {
528 const query = {
529 include: [
530 {
531 required: true,
532 attributes: [ 'id' ],
533 model: AccountModel.unscoped(),
534 include: [
535 {
536 required: true,
537 attributes: [ 'id' ],
538 model: VideoChannelModel.unscoped(),
539 where: {
540 actorId: videoChannelActorId
541 }
542 }
543 ]
544 }
545 ]
546 }
547
548 return UserModel.findOne(query)
549 }
550
551 static loadByAccountActorId (accountActorId: number): Bluebird<MUserDefault> {
552 const query = {
553 include: [
554 {
555 required: true,
556 attributes: [ 'id' ],
557 model: AccountModel.unscoped(),
558 where: {
559 actorId: accountActorId
560 }
561 }
562 ]
563 }
564
565 return UserModel.findOne(query)
566 }
567
568 static getOriginalVideoFileTotalFromUser (user: MUserId) {
569 // Don't use sequelize because we need to use a sub query
570 const query = UserModel.generateUserQuotaBaseSQL()
571
572 return UserModel.getTotalRawQuery(query, user.id)
573 }
574
575 // Returns cumulative size of all video files uploaded in the last 24 hours.
576 static getOriginalVideoFileTotalDailyFromUser (user: MUserId) {
577 // Don't use sequelize because we need to use a sub query
578 const query = UserModel.generateUserQuotaBaseSQL('"video"."createdAt" > now() - interval \'24 hours\'')
579
580 return UserModel.getTotalRawQuery(query, user.id)
581 }
582
583 static async getStats () {
584 const totalUsers = await UserModel.count()
585
586 return {
587 totalUsers
588 }
589 }
590
591 static autoComplete (search: string) {
592 const query = {
593 where: {
594 username: {
595 [ Op.like ]: `%${search}%`
596 }
597 },
598 limit: 10
599 }
600
601 return UserModel.findAll(query)
602 .then(u => u.map(u => u.username))
603 }
604
605 canGetVideo (video: MVideoFullLight) {
606 const videoUserId = video.VideoChannel.Account.userId
607
608 if (video.isBlacklisted()) {
609 return videoUserId === this.id || this.hasRight(UserRight.MANAGE_VIDEO_BLACKLIST)
610 }
611
612 if (video.privacy === VideoPrivacy.PRIVATE) {
613 return video.VideoChannel && videoUserId === this.id || this.hasRight(UserRight.MANAGE_VIDEO_BLACKLIST)
614 }
615
616 if (video.privacy === VideoPrivacy.INTERNAL) return true
617
618 return false
619 }
620
621 hasRight (right: UserRight) {
622 return hasUserRight(this.role, right)
623 }
624
625 hasAdminFlag (flag: UserAdminFlag) {
626 return this.adminFlags & flag
627 }
628
629 isPasswordMatch (password: string) {
630 return comparePassword(password, this.password)
631 }
632
633 toFormattedJSON (this: MUserFormattable, parameters: { withAdminFlags?: boolean } = {}): User {
634 const videoQuotaUsed = this.get('videoQuotaUsed')
635 const videoQuotaUsedDaily = this.get('videoQuotaUsedDaily')
636
637 const json: User = {
638 id: this.id,
639 username: this.username,
640 email: this.email,
641 theme: getThemeOrDefault(this.theme, DEFAULT_USER_THEME_NAME),
642
643 pendingEmail: this.pendingEmail,
644 emailVerified: this.emailVerified,
645
646 nsfwPolicy: this.nsfwPolicy,
647 webTorrentEnabled: this.webTorrentEnabled,
648 videosHistoryEnabled: this.videosHistoryEnabled,
649 autoPlayVideo: this.autoPlayVideo,
650 autoPlayNextVideo: this.autoPlayNextVideo,
651 autoPlayNextVideoPlaylist: this.autoPlayNextVideoPlaylist,
652 videoLanguages: this.videoLanguages,
653
654 role: this.role,
655 roleLabel: USER_ROLE_LABELS[ this.role ],
656
657 videoQuota: this.videoQuota,
658 videoQuotaDaily: this.videoQuotaDaily,
659 videoQuotaUsed: videoQuotaUsed !== undefined
660 ? parseInt(videoQuotaUsed + '', 10)
661 : undefined,
662 videoQuotaUsedDaily: videoQuotaUsedDaily !== undefined
663 ? parseInt(videoQuotaUsedDaily + '', 10)
664 : undefined,
665
666 noInstanceConfigWarningModal: this.noInstanceConfigWarningModal,
667 noWelcomeModal: this.noWelcomeModal,
668
669 blocked: this.blocked,
670 blockedReason: this.blockedReason,
671
672 account: this.Account.toFormattedJSON(),
673
674 notificationSettings: this.NotificationSetting
675 ? this.NotificationSetting.toFormattedJSON()
676 : undefined,
677
678 videoChannels: [],
679
680 createdAt: this.createdAt
681 }
682
683 if (parameters.withAdminFlags) {
684 Object.assign(json, { adminFlags: this.adminFlags })
685 }
686
687 if (Array.isArray(this.Account.VideoChannels) === true) {
688 json.videoChannels = this.Account.VideoChannels
689 .map(c => c.toFormattedJSON())
690 .sort((v1, v2) => {
691 if (v1.createdAt < v2.createdAt) return -1
692 if (v1.createdAt === v2.createdAt) return 0
693
694 return 1
695 })
696 }
697
698 return json
699 }
700
701 toMeFormattedJSON (this: MMyUserFormattable): MyUser {
702 const formatted = this.toFormattedJSON()
703
704 const specialPlaylists = this.Account.VideoPlaylists
705 .map(p => ({ id: p.id, name: p.name, type: p.type }))
706
707 return Object.assign(formatted, { specialPlaylists })
708 }
709
710 async isAbleToUploadVideo (videoFile: { size: number }) {
711 if (this.videoQuota === -1 && this.videoQuotaDaily === -1) return Promise.resolve(true)
712
713 const [ totalBytes, totalBytesDaily ] = await Promise.all([
714 UserModel.getOriginalVideoFileTotalFromUser(this),
715 UserModel.getOriginalVideoFileTotalDailyFromUser(this)
716 ])
717
718 const uploadedTotal = videoFile.size + totalBytes
719 const uploadedDaily = videoFile.size + totalBytesDaily
720
721 if (this.videoQuotaDaily === -1) return uploadedTotal < this.videoQuota
722 if (this.videoQuota === -1) return uploadedDaily < this.videoQuotaDaily
723
724 return uploadedTotal < this.videoQuota && uploadedDaily < this.videoQuotaDaily
725 }
726
727 private static generateUserQuotaBaseSQL (where?: string) {
728 const andWhere = where ? 'AND ' + where : ''
729
730 return 'SELECT SUM("size") AS "total" ' +
731 'FROM (' +
732 'SELECT MAX("videoFile"."size") AS "size" FROM "videoFile" ' +
733 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' +
734 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
735 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' +
736 'WHERE "account"."userId" = $userId ' + andWhere +
737 'GROUP BY "video"."id"' +
738 ') t'
739 }
740
741 private static getTotalRawQuery (query: string, userId: number) {
742 const options = {
743 bind: { userId },
744 type: QueryTypes.SELECT as QueryTypes.SELECT
745 }
746
747 return UserModel.sequelize.query<{ total: string }>(query, options)
748 .then(([ { total } ]) => {
749 if (total === null) return 0
750
751 return parseInt(total, 10)
752 })
753 }
754 }