]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/models/user/user.ts
Client: explain to user we don't want scheme when making friends
[github/Chocobozzz/PeerTube.git] / server / models / user / user.ts
CommitLineData
65fcc311 1import { values } from 'lodash'
e02643f3 2import * as Sequelize from 'sequelize'
b0f9f39e 3import * as Promise from 'bluebird'
65fcc311 4
74889a71
C
5import { getSort } from '../utils'
6import { USER_ROLES } from '../../initializers'
65fcc311
C
7import {
8 cryptPassword,
9 comparePassword,
10 isUserPasswordValid,
11 isUserUsernameValid,
b0f9f39e
C
12 isUserDisplayNSFWValid,
13 isUserVideoQuotaValid
74889a71 14} from '../../helpers'
9bd26629 15
74889a71 16import { addMethodsToModel } from '../utils'
e02643f3 17import {
e02643f3
C
18 UserInstance,
19 UserAttributes,
20
21 UserMethods
22} from './user-interface'
23
24let User: Sequelize.Model<UserInstance, UserAttributes>
25let isPasswordMatch: UserMethods.IsPasswordMatch
0aef76c4 26let toFormattedJSON: UserMethods.ToFormattedJSON
e02643f3
C
27let isAdmin: UserMethods.IsAdmin
28let countTotal: UserMethods.CountTotal
29let getByUsername: UserMethods.GetByUsername
30let list: UserMethods.List
31let listForApi: UserMethods.ListForApi
32let loadById: UserMethods.LoadById
33let loadByUsername: UserMethods.LoadByUsername
34let loadByUsernameOrEmail: UserMethods.LoadByUsernameOrEmail
b0f9f39e 35let isAbleToUploadVideo: UserMethods.IsAbleToUploadVideo
e02643f3 36
127944aa
C
37export default function (sequelize: Sequelize.Sequelize, DataTypes: Sequelize.DataTypes) {
38 User = sequelize.define<UserInstance, UserAttributes>('User',
feb4bdfd
C
39 {
40 password: {
67bf9b96
C
41 type: DataTypes.STRING,
42 allowNull: false,
43 validate: {
075f16ca 44 passwordValid: value => {
65fcc311 45 const res = isUserPasswordValid(value)
67bf9b96
C
46 if (res === false) throw new Error('Password not valid.')
47 }
48 }
feb4bdfd
C
49 },
50 username: {
67bf9b96
C
51 type: DataTypes.STRING,
52 allowNull: false,
53 validate: {
075f16ca 54 usernameValid: value => {
65fcc311 55 const res = isUserUsernameValid(value)
67bf9b96
C
56 if (res === false) throw new Error('Username not valid.')
57 }
58 }
feb4bdfd 59 },
ad4a8a1c 60 email: {
5804c0db 61 type: DataTypes.STRING(400),
ad4a8a1c
C
62 allowNull: false,
63 validate: {
64 isEmail: true
65 }
66 },
1d49e1e2
C
67 displayNSFW: {
68 type: DataTypes.BOOLEAN,
69 allowNull: false,
70 defaultValue: false,
71 validate: {
075f16ca 72 nsfwValid: value => {
65fcc311 73 const res = isUserDisplayNSFWValid(value)
1d49e1e2
C
74 if (res === false) throw new Error('Display NSFW is not valid.')
75 }
76 }
77 },
feb4bdfd 78 role: {
65fcc311 79 type: DataTypes.ENUM(values(USER_ROLES)),
67bf9b96 80 allowNull: false
b0f9f39e
C
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 }
feb4bdfd
C
91 }
92 },
93 {
319d072e
C
94 indexes: [
95 {
5d67f289
C
96 fields: [ 'username' ],
97 unique: true
ad4a8a1c
C
98 },
99 {
100 fields: [ 'email' ],
101 unique: true
319d072e
C
102 }
103 ],
feb4bdfd
C
104 hooks: {
105 beforeCreate: beforeCreateOrUpdate,
106 beforeUpdate: beforeCreateOrUpdate
107 }
108 }
109 )
110
e02643f3
C
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,
0aef76c4 124 toFormattedJSON,
b0f9f39e
C
125 isAdmin,
126 isAbleToUploadVideo
e02643f3
C
127 ]
128 addMethodsToModel(User, classMethods, instanceMethods)
129
feb4bdfd 130 return User
9bd26629 131}
69b0a27c 132
69818c93 133function beforeCreateOrUpdate (user: UserInstance) {
6fcd19ba
C
134 return cryptPassword(user.password).then(hash => {
135 user.password = hash
136 return undefined
26d7d31b 137 })
feb4bdfd 138}
69b0a27c 139
26d7d31b
C
140// ------------------------------ METHODS ------------------------------
141
6fcd19ba
C
142isPasswordMatch = function (this: UserInstance, password: string) {
143 return comparePassword(password, this.password)
26d7d31b
C
144}
145
0aef76c4 146toFormattedJSON = function (this: UserInstance) {
26d7d31b 147 return {
feb4bdfd 148 id: this.id,
26d7d31b 149 username: this.username,
ad4a8a1c 150 email: this.email,
1d49e1e2 151 displayNSFW: this.displayNSFW,
d74a0680 152 role: this.role,
b0f9f39e 153 videoQuota: this.videoQuota,
feb4bdfd 154 createdAt: this.createdAt
26d7d31b
C
155 }
156}
198b205c 157
70c065d6 158isAdmin = function (this: UserInstance) {
65fcc311 159 return this.role === USER_ROLES.ADMIN
198b205c
GS
160}
161
b0f9f39e
C
162isAbleToUploadVideo = 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
26d7d31b 170// ------------------------------ STATICS ------------------------------
69b0a27c 171
feb4bdfd 172function associate (models) {
e02643f3 173 User.hasOne(models.Author, {
4712081f
C
174 foreignKey: 'userId',
175 onDelete: 'cascade'
176 })
177
e02643f3 178 User.hasMany(models.OAuthToken, {
feb4bdfd
C
179 foreignKey: 'userId',
180 onDelete: 'cascade'
181 })
182}
183
6fcd19ba
C
184countTotal = function () {
185 return this.count()
089ff2f2
C
186}
187
69818c93 188getByUsername = function (username: string) {
feb4bdfd
C
189 const query = {
190 where: {
191 username: username
192 }
193 }
194
e02643f3 195 return User.findOne(query)
9bd26629
C
196}
197
6fcd19ba
C
198list = function () {
199 return User.findAll()
00d6b0dd
C
200}
201
6fcd19ba 202listForApi = function (start: number, count: number, sort: string) {
feb4bdfd
C
203 const query = {
204 offset: start,
205 limit: count,
65fcc311 206 order: [ getSort(sort) ]
feb4bdfd
C
207 }
208
6fcd19ba
C
209 return User.findAndCountAll(query).then(({ rows, count }) => {
210 return {
211 data: rows,
212 total: count
213 }
feb4bdfd 214 })
69b0a27c
C
215}
216
6fcd19ba
C
217loadById = function (id: number) {
218 return User.findById(id)
68a3b9f2
C
219}
220
6fcd19ba 221loadByUsername = function (username: string) {
feb4bdfd
C
222 const query = {
223 where: {
556ddc31 224 username
feb4bdfd
C
225 }
226 }
227
6fcd19ba 228 return User.findOne(query)
9bd26629 229}
ad4a8a1c 230
6fcd19ba 231loadByUsernameOrEmail = function (username: string, email: string) {
ad4a8a1c
C
232 const query = {
233 where: {
234 $or: [ { username }, { email } ]
235 }
236 }
237
556ddc31
C
238 // FIXME: https://github.com/DefinitelyTyped/DefinitelyTyped/issues/18387
239 return (User as any).findOne(query)
ad4a8a1c 240}
b0f9f39e
C
241
242// ---------------------------------------------------------------------------
243
244function getOriginalVideoFileTotalFromUser (user: UserInstance) {
14d3270f
C
245 // Don't use sequelize because we need to use a subquery
246 const query = 'SELECT SUM("size") AS "total" FROM ' +
247 '(SELECT MAX("VideoFiles"."size") AS "size" FROM "VideoFiles" ' +
248 'INNER JOIN "Videos" ON "VideoFiles"."videoId" = "Videos"."id" ' +
249 'INNER JOIN "Authors" ON "Videos"."authorId" = "Authors"."id" ' +
250 'INNER JOIN "Users" ON "Authors"."userId" = "Users"."id" ' +
251 'WHERE "Users"."id" = $userId GROUP BY "Videos"."id") t'
252
253 const options = {
254 bind: { userId: user.id },
255 type: Sequelize.QueryTypes.SELECT
b0f9f39e 256 }
14d3270f
C
257 return User['sequelize'].query(query, options).then(([ { total } ]) => {
258 if (total === null) return 0
b0f9f39e 259
14d3270f
C
260 return parseInt(total, 10)
261 })
b0f9f39e 262}