]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/models/user/user.ts
Fix tests and user quota
[github/Chocobozzz/PeerTube.git] / server / models / user / user.ts
1 import { values } from 'lodash'
2 import * as Sequelize from 'sequelize'
3 import * as Promise from 'bluebird'
4
5 import { getSort } from '../utils'
6 import { USER_ROLES } from '../../initializers'
7 import {
8 cryptPassword,
9 comparePassword,
10 isUserPasswordValid,
11 isUserUsernameValid,
12 isUserDisplayNSFWValid,
13 isUserVideoQuotaValid
14 } from '../../helpers'
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 toFormattedJSON: UserMethods.ToFormattedJSON
27 let isAdmin: UserMethods.IsAdmin
28 let countTotal: UserMethods.CountTotal
29 let getByUsername: UserMethods.GetByUsername
30 let list: UserMethods.List
31 let listForApi: UserMethods.ListForApi
32 let loadById: UserMethods.LoadById
33 let loadByUsername: UserMethods.LoadByUsername
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.ENUM(values(USER_ROLES)),
80 allowNull: false
81 },
82 videoQuota: {
83 type: DataTypes.BIGINT,
84 allowNull: false,
85 validate: {
86 videoQuotaValid: value => {
87 const res = isUserVideoQuotaValid(value)
88 if (res === false) throw new Error('Video quota is not valid.')
89 }
90 }
91 }
92 },
93 {
94 indexes: [
95 {
96 fields: [ 'username' ],
97 unique: true
98 },
99 {
100 fields: [ 'email' ],
101 unique: true
102 }
103 ],
104 hooks: {
105 beforeCreate: beforeCreateOrUpdate,
106 beforeUpdate: beforeCreateOrUpdate
107 }
108 }
109 )
110
111 const classMethods = [
112 associate,
113
114 countTotal,
115 getByUsername,
116 list,
117 listForApi,
118 loadById,
119 loadByUsername,
120 loadByUsernameOrEmail
121 ]
122 const instanceMethods = [
123 isPasswordMatch,
124 toFormattedJSON,
125 isAdmin,
126 isAbleToUploadVideo
127 ]
128 addMethodsToModel(User, classMethods, instanceMethods)
129
130 return User
131 }
132
133 function beforeCreateOrUpdate (user: UserInstance) {
134 return cryptPassword(user.password).then(hash => {
135 user.password = hash
136 return undefined
137 })
138 }
139
140 // ------------------------------ METHODS ------------------------------
141
142 isPasswordMatch = function (this: UserInstance, password: string) {
143 return comparePassword(password, this.password)
144 }
145
146 toFormattedJSON = function (this: UserInstance) {
147 return {
148 id: this.id,
149 username: this.username,
150 email: this.email,
151 displayNSFW: this.displayNSFW,
152 role: this.role,
153 videoQuota: this.videoQuota,
154 createdAt: this.createdAt
155 }
156 }
157
158 isAdmin = function (this: UserInstance) {
159 return this.role === USER_ROLES.ADMIN
160 }
161
162 isAbleToUploadVideo = function (this: UserInstance, videoFile: Express.Multer.File) {
163 if (this.videoQuota === -1) return Promise.resolve(true)
164
165 return getOriginalVideoFileTotalFromUser(this).then(totalBytes => {
166 return (videoFile.size + totalBytes) < this.videoQuota
167 })
168 }
169
170 // ------------------------------ STATICS ------------------------------
171
172 function associate (models) {
173 User.hasOne(models.Author, {
174 foreignKey: 'userId',
175 onDelete: 'cascade'
176 })
177
178 User.hasMany(models.OAuthToken, {
179 foreignKey: 'userId',
180 onDelete: 'cascade'
181 })
182 }
183
184 countTotal = function () {
185 return this.count()
186 }
187
188 getByUsername = function (username: string) {
189 const query = {
190 where: {
191 username: username
192 }
193 }
194
195 return User.findOne(query)
196 }
197
198 list = function () {
199 return User.findAll()
200 }
201
202 listForApi = function (start: number, count: number, sort: string) {
203 const query = {
204 offset: start,
205 limit: count,
206 order: [ getSort(sort) ]
207 }
208
209 return User.findAndCountAll(query).then(({ rows, count }) => {
210 return {
211 data: rows,
212 total: count
213 }
214 })
215 }
216
217 loadById = function (id: number) {
218 return User.findById(id)
219 }
220
221 loadByUsername = function (username: string) {
222 const query = {
223 where: {
224 username
225 }
226 }
227
228 return User.findOne(query)
229 }
230
231 loadByUsernameOrEmail = function (username: string, email: string) {
232 const query = {
233 where: {
234 $or: [ { username }, { email } ]
235 }
236 }
237
238 // FIXME: https://github.com/DefinitelyTyped/DefinitelyTyped/issues/18387
239 return (User as any).findOne(query)
240 }
241
242 // ---------------------------------------------------------------------------
243
244 function getOriginalVideoFileTotalFromUser (user: UserInstance) {
245 // attributes = [] because we don't want other fields than the sum
246 const query = {
247 where: {
248 resolution: 0 // Original, TODO: improve readability
249 },
250 include: [
251 {
252 attributes: [],
253 model: User['sequelize'].models.Video,
254 include: [
255 {
256 attributes: [],
257 model: User['sequelize'].models.Author,
258 include: [
259 {
260 attributes: [],
261 model: User['sequelize'].models.User,
262 where: {
263 id: user.id
264 }
265 }
266 ]
267 }
268 ]
269 }
270 ]
271 }
272
273 return User['sequelize'].models.VideoFile.sum('size', query)
274 }