]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/models/account/user.ts
Add ability to reset our password
[github/Chocobozzz/PeerTube.git] / server / models / account / user.ts
CommitLineData
e02643f3 1import * as Sequelize from 'sequelize'
3fd3ab2d 2import {
50d6de9c
C
3 AllowNull, BeforeCreate, BeforeUpdate, Column, CreatedAt, DataType, Default, DefaultScope, HasMany, HasOne, Is, IsEmail, Model,
4 Scopes, Table, UpdatedAt
3fd3ab2d 5} from 'sequelize-typescript'
e34c85e5 6import { hasUserRight, USER_ROLE_LABELS, UserRight } from '../../../shared'
c5911fd3 7import { User } from '../../../shared/models/users'
65fcc311 8import {
50d6de9c
C
9 isUserAutoPlayVideoValid, isUserDisplayNSFWValid, isUserPasswordValid, isUserRoleValid, isUserUsernameValid,
10 isUserVideoQuotaValid
3fd3ab2d 11} from '../../helpers/custom-validators/users'
da854ddd 12import { comparePassword, cryptPassword } from '../../helpers/peertube-crypto'
3fd3ab2d
C
13import { OAuthTokenModel } from '../oauth/oauth-token'
14import { getSort, throwIfNotValid } from '../utils'
15import { VideoChannelModel } from '../video/video-channel'
16import { AccountModel } from './account'
17
d48ff09d
C
18@DefaultScope({
19 include: [
20 {
21 model: () => AccountModel,
22 required: true
23 }
24 ]
25})
26@Scopes({
27 withVideoChannel: {
28 include: [
29 {
30 model: () => AccountModel,
31 required: true,
32 include: [ () => VideoChannelModel ]
33 }
34 ]
35 }
36})
3fd3ab2d
C
37@Table({
38 tableName: 'user',
39 indexes: [
feb4bdfd 40 {
3fd3ab2d
C
41 fields: [ 'username' ],
42 unique: true
feb4bdfd
C
43 },
44 {
3fd3ab2d
C
45 fields: [ 'email' ],
46 unique: true
feb4bdfd 47 }
e02643f3 48 ]
3fd3ab2d
C
49})
50export class UserModel extends Model<UserModel> {
51
52 @AllowNull(false)
53 @Is('UserPassword', value => throwIfNotValid(value, isUserPasswordValid, 'user password'))
54 @Column
55 password: string
56
57 @AllowNull(false)
58 @Is('UserPassword', value => throwIfNotValid(value, isUserUsernameValid, 'user name'))
59 @Column
60 username: string
61
62 @AllowNull(false)
63 @IsEmail
64 @Column(DataType.STRING(400))
65 email: string
66
67 @AllowNull(false)
68 @Default(false)
69 @Is('UserDisplayNSFW', value => throwIfNotValid(value, isUserDisplayNSFWValid, 'display NSFW boolean'))
70 @Column
71 displayNSFW: boolean
72
7efe153b
AL
73 @AllowNull(false)
74 @Default(true)
75 @Is('UserAutoPlayVideo', value => throwIfNotValid(value, isUserAutoPlayVideoValid, 'auto play video boolean'))
76 @Column
77 autoPlayVideo: boolean
78
3fd3ab2d
C
79 @AllowNull(false)
80 @Is('UserRole', value => throwIfNotValid(value, isUserRoleValid, 'role'))
81 @Column
82 role: number
83
84 @AllowNull(false)
85 @Is('UserVideoQuota', value => throwIfNotValid(value, isUserVideoQuotaValid, 'video quota'))
86 @Column(DataType.BIGINT)
87 videoQuota: number
88
89 @CreatedAt
90 createdAt: Date
91
92 @UpdatedAt
93 updatedAt: Date
94
95 @HasOne(() => AccountModel, {
96 foreignKey: 'userId',
f05a1c30
C
97 onDelete: 'cascade',
98 hooks: true
3fd3ab2d
C
99 })
100 Account: AccountModel
69b0a27c 101
3fd3ab2d
C
102 @HasMany(() => OAuthTokenModel, {
103 foreignKey: 'userId',
104 onDelete: 'cascade'
105 })
106 OAuthTokens: OAuthTokenModel[]
107
108 @BeforeCreate
109 @BeforeUpdate
110 static cryptPasswordIfNeeded (instance: UserModel) {
111 if (instance.changed('password')) {
112 return cryptPassword(instance.password)
113 .then(hash => {
114 instance.password = hash
115 return undefined
116 })
117 }
59557c46 118 }
26d7d31b 119
3fd3ab2d
C
120 static countTotal () {
121 return this.count()
122 }
954605a8 123
3fd3ab2d
C
124 static listForApi (start: number, count: number, sort: string) {
125 const query = {
126 offset: start,
127 limit: count,
d48ff09d 128 order: [ getSort(sort) ]
3fd3ab2d 129 }
72c7248b 130
3fd3ab2d
C
131 return UserModel.findAndCountAll(query)
132 .then(({ rows, count }) => {
133 return {
134 data: rows,
135 total: count
136 }
72c7248b 137 })
72c7248b
C
138 }
139
3fd3ab2d 140 static loadById (id: number) {
d48ff09d 141 return UserModel.findById(id)
3fd3ab2d 142 }
feb4bdfd 143
3fd3ab2d
C
144 static loadByUsername (username: string) {
145 const query = {
146 where: {
147 username
d48ff09d 148 }
3fd3ab2d 149 }
089ff2f2 150
3fd3ab2d 151 return UserModel.findOne(query)
feb4bdfd
C
152 }
153
3fd3ab2d
C
154 static loadByUsernameAndPopulateChannels (username: string) {
155 const query = {
156 where: {
157 username
d48ff09d 158 }
3fd3ab2d 159 }
9bd26629 160
d48ff09d 161 return UserModel.scope('withVideoChannel').findOne(query)
feb4bdfd
C
162 }
163
ecb4e35f
C
164 static loadByEmail (email: string) {
165 const query = {
166 where: {
167 email
168 }
169 }
170
171 return UserModel.findOne(query)
172 }
173
ba12e8b3
C
174 static loadByUsernameOrEmail (username: string, email?: string) {
175 if (!email) email = username
176
3fd3ab2d 177 const query = {
3fd3ab2d
C
178 where: {
179 [ Sequelize.Op.or ]: [ { username }, { email } ]
180 }
6fcd19ba 181 }
69b0a27c 182
d48ff09d 183 return UserModel.findOne(query)
72c7248b
C
184 }
185
ce5496d6 186 static getOriginalVideoFileTotalFromUser (user: UserModel) {
3fd3ab2d
C
187 // Don't use sequelize because we need to use a sub query
188 const query = 'SELECT SUM("size") AS "total" FROM ' +
189 '(SELECT MAX("videoFile"."size") AS "size" FROM "videoFile" ' +
190 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' +
191 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
192 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' +
193 'INNER JOIN "user" ON "account"."userId" = "user"."id" ' +
194 'WHERE "user"."id" = $userId GROUP BY "video"."id") t'
195
196 const options = {
197 bind: { userId: user.id },
198 type: Sequelize.QueryTypes.SELECT
199 }
200 return UserModel.sequelize.query(query, options)
201 .then(([ { total } ]) => {
202 if (total === null) return 0
68a3b9f2 203
3fd3ab2d
C
204 return parseInt(total, 10)
205 })
72c7248b
C
206 }
207
3fd3ab2d
C
208 hasRight (right: UserRight) {
209 return hasUserRight(this.role, right)
210 }
72c7248b 211
3fd3ab2d
C
212 isPasswordMatch (password: string) {
213 return comparePassword(password, this.password)
feb4bdfd
C
214 }
215
c5911fd3 216 toFormattedJSON (): User {
3fd3ab2d
C
217 const json = {
218 id: this.id,
219 username: this.username,
220 email: this.email,
221 displayNSFW: this.displayNSFW,
7efe153b 222 autoPlayVideo: this.autoPlayVideo,
3fd3ab2d
C
223 role: this.role,
224 roleLabel: USER_ROLE_LABELS[ this.role ],
225 videoQuota: this.videoQuota,
226 createdAt: this.createdAt,
c5911fd3
C
227 account: this.Account.toFormattedJSON(),
228 videoChannels: []
3fd3ab2d
C
229 }
230
231 if (Array.isArray(this.Account.VideoChannels) === true) {
c5911fd3 232 json.videoChannels = this.Account.VideoChannels
3fd3ab2d
C
233 .map(c => c.toFormattedJSON())
234 .sort((v1, v2) => {
235 if (v1.createdAt < v2.createdAt) return -1
236 if (v1.createdAt === v2.createdAt) return 0
ad4a8a1c 237
3fd3ab2d
C
238 return 1
239 })
ad4a8a1c 240 }
3fd3ab2d
C
241
242 return json
ad4a8a1c
C
243 }
244
3fd3ab2d
C
245 isAbleToUploadVideo (videoFile: Express.Multer.File) {
246 if (this.videoQuota === -1) return Promise.resolve(true)
b0f9f39e 247
3fd3ab2d
C
248 return UserModel.getOriginalVideoFileTotalFromUser(this)
249 .then(totalBytes => {
250 return (videoFile.size + totalBytes) < this.videoQuota
251 })
b0f9f39e 252 }
b0f9f39e 253}