]>
Commit | Line | Data |
---|---|---|
4d4e5cd4 | 1 | import * as express from 'express' |
c5911fd3 | 2 | import { extname, join } from 'path' |
e8e12200 | 3 | import * as sharp from 'sharp' |
c5911fd3 | 4 | import * as uuidv4 from 'uuid/v4' |
571389d4 | 5 | import { UserCreate, UserRight, UserRole, UserUpdate, UserUpdateMe, UserVideoRate as FormattedUserVideoRate } from '../../../shared' |
4e8c8728 | 6 | import { unlinkPromise } from '../../helpers/core-utils' |
da854ddd C |
7 | import { retryTransactionWrapper } from '../../helpers/database-utils' |
8 | import { logger } from '../../helpers/logger' | |
ecb4e35f | 9 | import { createReqFiles, generateRandomString, getFormattedObjects } from '../../helpers/utils' |
e8e12200 | 10 | import { AVATAR_MIMETYPE_EXT, AVATARS_SIZE, CONFIG, sequelizeTypescript } from '../../initializers' |
a5625b41 | 11 | import { updateActorAvatarInstance } from '../../lib/activitypub' |
265ba139 | 12 | import { sendUpdateUser } from '../../lib/activitypub/send' |
ecb4e35f C |
13 | import { Emailer } from '../../lib/emailer' |
14 | import { EmailPayload } from '../../lib/job-queue/handlers/email' | |
15 | import { Redis } from '../../lib/redis' | |
50d6de9c | 16 | import { createUserAccountAndChannel } from '../../lib/user' |
65fcc311 | 17 | import { |
1174a847 | 18 | asyncMiddleware, authenticate, ensureUserHasRight, ensureUserRegistrationAllowed, paginationValidator, setDefaultSort, |
f05a1c30 | 19 | setDefaultPagination, token, usersAddValidator, usersGetValidator, usersRegisterValidator, usersRemoveValidator, usersSortValidator, |
da854ddd | 20 | usersUpdateMeValidator, usersUpdateValidator, usersVideoRatingValidator |
65fcc311 | 21 | } from '../../middlewares' |
ecb4e35f C |
22 | import { |
23 | usersAskResetPasswordValidator, usersResetPasswordValidator, usersUpdateMyAvatarValidator, | |
24 | videosSortValidator | |
25 | } from '../../middlewares/validators' | |
3fd3ab2d C |
26 | import { AccountVideoRateModel } from '../../models/account/account-video-rate' |
27 | import { UserModel } from '../../models/account/user' | |
f8b8c36b | 28 | import { OAuthTokenModel } from '../../models/oauth/oauth-token' |
3fd3ab2d | 29 | import { VideoModel } from '../../models/video/video' |
65fcc311 | 30 | |
c5911fd3 C |
31 | const reqAvatarFile = createReqFiles('avatarfile', CONFIG.STORAGE.AVATARS_DIR, AVATAR_MIMETYPE_EXT) |
32 | ||
65fcc311 C |
33 | const usersRouter = express.Router() |
34 | ||
35 | usersRouter.get('/me', | |
36 | authenticate, | |
eb080476 | 37 | asyncMiddleware(getUserInformation) |
d38b8281 C |
38 | ) |
39 | ||
ce5496d6 C |
40 | usersRouter.get('/me/video-quota-used', |
41 | authenticate, | |
42 | asyncMiddleware(getUserVideoQuotaUsed) | |
43 | ) | |
44 | ||
fd45e8f4 C |
45 | usersRouter.get('/me/videos', |
46 | authenticate, | |
47 | paginationValidator, | |
48 | videosSortValidator, | |
1174a847 | 49 | setDefaultSort, |
f05a1c30 | 50 | setDefaultPagination, |
fd45e8f4 C |
51 | asyncMiddleware(getUserVideos) |
52 | ) | |
53 | ||
65fcc311 C |
54 | usersRouter.get('/me/videos/:videoId/rating', |
55 | authenticate, | |
a2431b7d | 56 | asyncMiddleware(usersVideoRatingValidator), |
eb080476 | 57 | asyncMiddleware(getUserVideoRating) |
d38b8281 | 58 | ) |
9bd26629 | 59 | |
65fcc311 | 60 | usersRouter.get('/', |
86d13ec2 C |
61 | authenticate, |
62 | ensureUserHasRight(UserRight.MANAGE_USERS), | |
65fcc311 C |
63 | paginationValidator, |
64 | usersSortValidator, | |
1174a847 | 65 | setDefaultSort, |
f05a1c30 | 66 | setDefaultPagination, |
eb080476 | 67 | asyncMiddleware(listUsers) |
5c39adb7 C |
68 | ) |
69 | ||
8094a898 | 70 | usersRouter.get('/:id', |
a2431b7d | 71 | asyncMiddleware(usersGetValidator), |
8094a898 C |
72 | getUser |
73 | ) | |
74 | ||
65fcc311 C |
75 | usersRouter.post('/', |
76 | authenticate, | |
954605a8 | 77 | ensureUserHasRight(UserRight.MANAGE_USERS), |
a2431b7d C |
78 | asyncMiddleware(usersAddValidator), |
79 | asyncMiddleware(createUserRetryWrapper) | |
9bd26629 C |
80 | ) |
81 | ||
65fcc311 | 82 | usersRouter.post('/register', |
a2431b7d C |
83 | asyncMiddleware(ensureUserRegistrationAllowed), |
84 | asyncMiddleware(usersRegisterValidator), | |
47e0652b | 85 | asyncMiddleware(registerUserRetryWrapper) |
2c2e9092 C |
86 | ) |
87 | ||
8094a898 C |
88 | usersRouter.put('/me', |
89 | authenticate, | |
90 | usersUpdateMeValidator, | |
eb080476 | 91 | asyncMiddleware(updateMe) |
8094a898 C |
92 | ) |
93 | ||
c5911fd3 C |
94 | usersRouter.post('/me/avatar/pick', |
95 | authenticate, | |
96 | reqAvatarFile, | |
97 | usersUpdateMyAvatarValidator, | |
98 | asyncMiddleware(updateMyAvatar) | |
99 | ) | |
100 | ||
65fcc311 C |
101 | usersRouter.put('/:id', |
102 | authenticate, | |
954605a8 | 103 | ensureUserHasRight(UserRight.MANAGE_USERS), |
a2431b7d | 104 | asyncMiddleware(usersUpdateValidator), |
eb080476 | 105 | asyncMiddleware(updateUser) |
9bd26629 C |
106 | ) |
107 | ||
65fcc311 C |
108 | usersRouter.delete('/:id', |
109 | authenticate, | |
954605a8 | 110 | ensureUserHasRight(UserRight.MANAGE_USERS), |
a2431b7d | 111 | asyncMiddleware(usersRemoveValidator), |
eb080476 | 112 | asyncMiddleware(removeUser) |
9bd26629 | 113 | ) |
6606150c | 114 | |
ecb4e35f C |
115 | usersRouter.post('/ask-reset-password', |
116 | asyncMiddleware(usersAskResetPasswordValidator), | |
117 | asyncMiddleware(askResetUserPassword) | |
118 | ) | |
119 | ||
120 | usersRouter.post('/:id/reset-password', | |
121 | asyncMiddleware(usersResetPasswordValidator), | |
122 | asyncMiddleware(resetUserPassword) | |
123 | ) | |
124 | ||
65fcc311 | 125 | usersRouter.post('/token', token, success) |
9bd26629 | 126 | // TODO: Once https://github.com/oauthjs/node-oauth2-server/pull/289 is merged, implement revoke token route |
9457bf88 C |
127 | |
128 | // --------------------------------------------------------------------------- | |
129 | ||
65fcc311 C |
130 | export { |
131 | usersRouter | |
132 | } | |
9457bf88 C |
133 | |
134 | // --------------------------------------------------------------------------- | |
135 | ||
fd45e8f4 | 136 | async function getUserVideos (req: express.Request, res: express.Response, next: express.NextFunction) { |
3fd3ab2d C |
137 | const user = res.locals.oauth.token.User as UserModel |
138 | const resultList = await VideoModel.listUserVideosForApi(user.id ,req.query.start, req.query.count, req.query.sort) | |
fd45e8f4 C |
139 | |
140 | return res.json(getFormattedObjects(resultList.data, resultList.total)) | |
141 | } | |
142 | ||
eb080476 | 143 | async function createUserRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) { |
72c7248b | 144 | const options = { |
47e0652b | 145 | arguments: [ req ], |
72c7248b C |
146 | errorMessage: 'Cannot insert the user with many retries.' |
147 | } | |
148 | ||
f05a1c30 | 149 | const { user, account } = await retryTransactionWrapper(createUser, options) |
eb080476 | 150 | |
f05a1c30 C |
151 | return res.json({ |
152 | user: { | |
153 | id: user.id, | |
154 | uuid: account.uuid | |
155 | } | |
156 | }).end() | |
72c7248b C |
157 | } |
158 | ||
47e0652b | 159 | async function createUser (req: express.Request) { |
4771e000 | 160 | const body: UserCreate = req.body |
f05a1c30 | 161 | const userToCreate = new UserModel({ |
4771e000 C |
162 | username: body.username, |
163 | password: body.password, | |
164 | email: body.email, | |
1d49e1e2 | 165 | displayNSFW: false, |
7efe153b | 166 | autoPlayVideo: true, |
954605a8 | 167 | role: body.role, |
b0f9f39e | 168 | videoQuota: body.videoQuota |
9bd26629 C |
169 | }) |
170 | ||
f05a1c30 | 171 | const { user, account } = await createUserAccountAndChannel(userToCreate) |
eb080476 | 172 | |
38fa2065 | 173 | logger.info('User %s with its channel and account created.', body.username) |
f05a1c30 C |
174 | |
175 | return { user, account } | |
9bd26629 C |
176 | } |
177 | ||
47e0652b C |
178 | async function registerUserRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) { |
179 | const options = { | |
180 | arguments: [ req ], | |
181 | errorMessage: 'Cannot insert the user with many retries.' | |
182 | } | |
183 | ||
184 | await retryTransactionWrapper(registerUser, options) | |
185 | ||
186 | return res.type('json').status(204).end() | |
187 | } | |
188 | ||
189 | async function registerUser (req: express.Request) { | |
77a5501f C |
190 | const body: UserCreate = req.body |
191 | ||
3fd3ab2d | 192 | const user = new UserModel({ |
77a5501f C |
193 | username: body.username, |
194 | password: body.password, | |
195 | email: body.email, | |
196 | displayNSFW: false, | |
7efe153b | 197 | autoPlayVideo: true, |
954605a8 | 198 | role: UserRole.USER, |
77a5501f C |
199 | videoQuota: CONFIG.USER.VIDEO_QUOTA |
200 | }) | |
201 | ||
38fa2065 | 202 | await createUserAccountAndChannel(user) |
47e0652b C |
203 | |
204 | logger.info('User %s with its channel and account registered.', body.username) | |
77a5501f C |
205 | } |
206 | ||
eb080476 | 207 | async function getUserInformation (req: express.Request, res: express.Response, next: express.NextFunction) { |
fd45e8f4 | 208 | // We did not load channels in res.locals.user |
3fd3ab2d | 209 | const user = await UserModel.loadByUsernameAndPopulateChannels(res.locals.oauth.token.user.username) |
eb080476 C |
210 | |
211 | return res.json(user.toFormattedJSON()) | |
99a64bfe C |
212 | } |
213 | ||
ce5496d6 C |
214 | async function getUserVideoQuotaUsed (req: express.Request, res: express.Response, next: express.NextFunction) { |
215 | // We did not load channels in res.locals.user | |
216 | const user = await UserModel.loadByUsernameAndPopulateChannels(res.locals.oauth.token.user.username) | |
217 | const videoQuotaUsed = await UserModel.getOriginalVideoFileTotalFromUser(user) | |
218 | ||
219 | return res.json({ | |
220 | videoQuotaUsed | |
221 | }) | |
222 | } | |
223 | ||
8094a898 | 224 | function getUser (req: express.Request, res: express.Response, next: express.NextFunction) { |
ce5496d6 | 225 | return res.json((res.locals.user as UserModel).toFormattedJSON()) |
8094a898 C |
226 | } |
227 | ||
eb080476 | 228 | async function getUserVideoRating (req: express.Request, res: express.Response, next: express.NextFunction) { |
0a6658fd | 229 | const videoId = +req.params.videoId |
571389d4 | 230 | const accountId = +res.locals.oauth.token.User.Account.id |
d38b8281 | 231 | |
3fd3ab2d | 232 | const ratingObj = await AccountVideoRateModel.load(accountId, videoId, null) |
faab3a84 C |
233 | const rating = ratingObj ? ratingObj.type : 'none' |
234 | ||
235 | const json: FormattedUserVideoRate = { | |
236 | videoId, | |
237 | rating | |
238 | } | |
239 | res.json(json) | |
d38b8281 C |
240 | } |
241 | ||
eb080476 | 242 | async function listUsers (req: express.Request, res: express.Response, next: express.NextFunction) { |
3fd3ab2d | 243 | const resultList = await UserModel.listForApi(req.query.start, req.query.count, req.query.sort) |
eb080476 C |
244 | |
245 | return res.json(getFormattedObjects(resultList.data, resultList.total)) | |
9bd26629 C |
246 | } |
247 | ||
eb080476 | 248 | async function removeUser (req: express.Request, res: express.Response, next: express.NextFunction) { |
3fd3ab2d | 249 | const user = await UserModel.loadById(req.params.id) |
eb080476 C |
250 | |
251 | await user.destroy() | |
252 | ||
253 | return res.sendStatus(204) | |
9bd26629 C |
254 | } |
255 | ||
eb080476 | 256 | async function updateMe (req: express.Request, res: express.Response, next: express.NextFunction) { |
8094a898 | 257 | const body: UserUpdateMe = req.body |
4771e000 | 258 | |
eb080476 | 259 | const user = res.locals.oauth.token.user |
1d49e1e2 | 260 | |
eb080476 C |
261 | if (body.password !== undefined) user.password = body.password |
262 | if (body.email !== undefined) user.email = body.email | |
263 | if (body.displayNSFW !== undefined) user.displayNSFW = body.displayNSFW | |
7efe153b | 264 | if (body.autoPlayVideo !== undefined) user.autoPlayVideo = body.autoPlayVideo |
eb080476 C |
265 | |
266 | await user.save() | |
265ba139 | 267 | await sendUpdateUser(user, undefined) |
eb080476 | 268 | |
d412e80e | 269 | return res.sendStatus(204) |
9bd26629 C |
270 | } |
271 | ||
c5911fd3 C |
272 | async function updateMyAvatar (req: express.Request, res: express.Response, next: express.NextFunction) { |
273 | const avatarPhysicalFile = req.files['avatarfile'][0] | |
265ba139 C |
274 | const user = res.locals.oauth.token.user |
275 | const actor = user.Account.Actor | |
c5911fd3 C |
276 | |
277 | const avatarDir = CONFIG.STORAGE.AVATARS_DIR | |
278 | const source = join(avatarDir, avatarPhysicalFile.filename) | |
279 | const extension = extname(avatarPhysicalFile.filename) | |
280 | const avatarName = uuidv4() + extension | |
281 | const destination = join(avatarDir, avatarName) | |
282 | ||
e8e12200 C |
283 | await sharp(source) |
284 | .resize(AVATARS_SIZE.width, AVATARS_SIZE.height) | |
285 | .toFile(destination) | |
286 | ||
287 | await unlinkPromise(source) | |
c5911fd3 | 288 | |
a5625b41 | 289 | const avatar = await sequelizeTypescript.transaction(async t => { |
bb82394c C |
290 | const updatedActor = await updateActorAvatarInstance(actor, avatarName, t) |
291 | await updatedActor.save({ transaction: t }) | |
c5911fd3 | 292 | |
a5625b41 | 293 | await sendUpdateUser(user, t) |
c5911fd3 | 294 | |
bb82394c | 295 | return updatedActor.Avatar |
c5911fd3 C |
296 | }) |
297 | ||
298 | return res | |
299 | .json({ | |
300 | avatar: avatar.toFormattedJSON() | |
301 | }) | |
302 | .end() | |
303 | } | |
304 | ||
eb080476 | 305 | async function updateUser (req: express.Request, res: express.Response, next: express.NextFunction) { |
8094a898 | 306 | const body: UserUpdate = req.body |
3fd3ab2d | 307 | const user = res.locals.user as UserModel |
f8b8c36b | 308 | const roleChanged = body.role !== undefined && body.role !== user.role |
8094a898 C |
309 | |
310 | if (body.email !== undefined) user.email = body.email | |
311 | if (body.videoQuota !== undefined) user.videoQuota = body.videoQuota | |
954605a8 | 312 | if (body.role !== undefined) user.role = body.role |
8094a898 | 313 | |
eb080476 C |
314 | await user.save() |
315 | ||
f8b8c36b C |
316 | // Destroy user token to refresh rights |
317 | if (roleChanged) { | |
318 | await OAuthTokenModel.deleteUserToken(user.id) | |
319 | } | |
320 | ||
265ba139 C |
321 | // Don't need to send this update to followers, these attributes are not propagated |
322 | ||
eb080476 | 323 | return res.sendStatus(204) |
8094a898 C |
324 | } |
325 | ||
ecb4e35f C |
326 | async function askResetUserPassword (req: express.Request, res: express.Response, next: express.NextFunction) { |
327 | const user = res.locals.user as UserModel | |
328 | ||
329 | const verificationString = await Redis.Instance.setResetPasswordVerificationString(user.id) | |
330 | const url = CONFIG.WEBSERVER.URL + '/reset-password?userId=' + user.id + '&verificationString=' + verificationString | |
331 | await Emailer.Instance.addForgetPasswordEmailJob(user.email, url) | |
332 | ||
333 | return res.status(204).end() | |
334 | } | |
335 | ||
336 | async function resetUserPassword (req: express.Request, res: express.Response, next: express.NextFunction) { | |
337 | const user = res.locals.user as UserModel | |
338 | user.password = req.body.password | |
339 | ||
340 | await user.save() | |
341 | ||
342 | return res.status(204).end() | |
343 | } | |
344 | ||
69818c93 | 345 | function success (req: express.Request, res: express.Response, next: express.NextFunction) { |
9457bf88 C |
346 | res.end() |
347 | } |